<commit_before>'use strict';

let expressPromiseRouter = require('express-promise-router');
let bodyParser = require('body-parser');

let pasteModel = require('./models/paste.js');
let ClientError = require('./errors.js').ClientError;

let rootRouter = expressPromiseRouter();
let apiRouter = expressPromiseRouter();

rootRouter.use('/api', apiRouter);
rootRouter.use(bodyParser.urlencoded({extended: true}));
apiRouter.use(bodyParser.json());

rootRouter.get('/', function(request, response) {
  response.render('pasteform');
});

rootRouter.get('/paste/:id', function(request, response) {
  return request.db.paste.fetchById(request.params.id).then(function(paste) {
    if (paste === null) {
      throw ClientError({
        title: 'could not find paste with ID ' + request.params.id,
        statusCode: 404,
      });
    } else {
      // TODO: replace this with a real template
      let body = `<h1>${paste.name}</h1><pre>${paste.content}</pre>\r\n`;
      response.send(body);
    }
  });
});

apiRouter.get('/pastes/:id', function(request, response) {
  return request.db.paste.fetchById(request.params.id).then(function(paste) {
    if (paste === null) {
      throw ClientError({
        title: 'could not find paste with ID ' + request.params.id,
        statusCode: 404,
      });
    } else {
      response.json(paste);
    }
  });
});

apiRouter.post('/pastes', function(request, response) {
  return request.db.paste.insertNew(request.body).then(function(pasteId) {
    response.status(201).json({id: pasteId});
  });
});

module.exports = rootRouter;
<commit_msg>Validation error should provoke status 400<commit_after>'use strict';

let expressPromiseRouter = require('express-promise-router');
let bodyParser = require('body-parser');

let pasteModel = require('./models/paste.js');
let ClientError = require('./errors.js').ClientError;

let rootRouter = expressPromiseRouter();
let apiRouter = expressPromiseRouter();

rootRouter.use('/api', apiRouter);
rootRouter.use(bodyParser.urlencoded({extended: true}));
apiRouter.use(bodyParser.json());

rootRouter.get('/', function(request, response) {
  response.render('pasteform');
});

rootRouter.get('/paste/:id', function(request, response) {
  return request.db.paste.fetchById(request.params.id).then(function(paste) {
    if (paste === null) {
      throw ClientError({
        title: 'could not find paste with ID ' + request.params.id,
        statusCode: 404,
      });
    } else {
      // TODO: replace this with a real template
      let body = `<h1>${paste.name}</h1><pre>${paste.content}</pre>\r\n`;
      response.send(body);
    }
  });
});

apiRouter.get('/pastes/:id', function(request, response) {
  return request.db.paste.fetchById(request.params.id).then(function(paste) {
    if (paste === null) {
      throw ClientError({
        title: 'could not find paste with ID ' + request.params.id,
        statusCode: 404,
      });
    } else {
      response.json(paste);
    }
  });
});

apiRouter.post('/pastes', function(request, response) {
  return request.db.paste.insertNew(request.body).catch(function(err) {
    if (err.name === 'ValidationError' && err.isJoi) {
      throw ClientError({
        title: 'validation failed: ' + err.details,
        statusCode: 400,
      });
    } else {
      throw err;
    }
  }).then(function(pasteId) {
    response.status(201).json({id: pasteId});
  });
});

module.exports = rootRouter;
<|endoftext|>


<commit_before>/**
 * Created with JetBrains WebStorm.
 * User: Aymeric CHAUVIN
 * Date: 26/06/12
 * Time: 18:00
 */

/**
 A class to manage the game logic and time

 @class GameLoop
 @static
 */
var GameLoop = function ()
{
    /**
     The value that limits the maximum frames per second
     @property {Integer} fps
     */
    var fps;

    /**
     The function to update the game logic
     @property {Function} updateFunc
     */
    var updateFunc;

    /**
     The function to draw the game graphics
     @property {Function} drawFunc
     */
    var drawFunc;

    /**
     This method is used to initialize any game logic parameters

     @method Initialize
     @param {Function} _updateFunc The update function
     @param {Function} _drawFunc The draw function
     @param {Integer} _fps The maximum frames per second value
     @return {Boolean} `true` if ok; otherwise `false`
     @private
     */
    function Initialize(_updateFunc, _drawFunc, _fps)
    {
        if (typeof(_updateFunc) != 'undefined' && typeof(_drawFunc) != 'undefined' && typeof(_fps) != 'undefined')
        {
            this.updateFunc = _updateFunc;
            this.drawFunc = _drawFunc;
            this.fps = _fps;
        }
        else
        {
            return false;
        }
        return true;
    }

    /**
     This function handles the GameLoop time logic

     @method Run
     @return {Nothing}
     @private
     */
    function Run()
    {
        setInterval(function ()
        {
            this.updateFunc();
            this.drawFunc();
        }, 1000 / this.fps);
    }

    return function ()
    {
        this.Initialize = Initialize;
        this.Run = Run;
    }

}();
<commit_msg>Added the namespace to the class<commit_after>/**
 * Created with JetBrains WebStorm.
 * User: Aymeric CHAUVIN
 * Date: 26/06/12
 * Time: 18:00
 */

/**
 A class to manage the game logic and time

 @namespace GameLoop
 @class GameLoop
 @static
 */
var GameLoop = function ()
{
    /**
     The value that limits the maximum frames per second
     @property {Integer} fps
     */
    var fps;

    /**
     The function to update the game logic
     @property {Function} updateFunc
     */
    var updateFunc;

    /**
     The function to draw the game graphics
     @property {Function} drawFunc
     */
    var drawFunc;

    /**
     This method is used to initialize any game logic parameters

     @method Initialize
     @param {Function} _updateFunc The update function
     @param {Function} _drawFunc The draw function
     @param {Integer} _fps The maximum frames per second value
     @return {Boolean} `true` if ok; otherwise `false`
     @private
     */
    function Initialize(_updateFunc, _drawFunc, _fps)
    {
        if (typeof(_updateFunc) != 'undefined' && typeof(_drawFunc) != 'undefined' && typeof(_fps) != 'undefined')
        {
            this.updateFunc = _updateFunc;
            this.drawFunc = _drawFunc;
            this.fps = _fps;
        }
        else
        {
            return false;
        }
        return true;
    }

    /**
     This function handles the GameLoop time logic

     @method Run
     @return {Nothing}
     @private
     */
    function Run()
    {
        setInterval(function ()
        {
            this.updateFunc();
            this.drawFunc();
        }, 1000 / this.fps);
    }

    return function ()
    {
        this.Initialize = Initialize;
        this.Run = Run;
    }

}();
<|endoftext|>


<commit_before>const ArgumentPrecondition = require('./ArgumentPrecondition.js');

class Argument {
  constructor(options) {
    this.name = options.name;
    this.key = options.key;
    this.type = options.type;
    this.example = options.example;
    this.default = options.default;
    this.preconditions = options.preconditions !== undefined ?  options.preconditions : [];
    this.isOptional = options.default === undefined;
    this.isRemainder = options.isRemainder !== undefined ?  options.isRemainder : false;

    validateArgument(this, this.constructor.name);
  }
}

module.exports = Argument;

const validateArgument = function(argument, name) {
  if (typeof argument.name !== 'string') {
    throw new TypeError(name + ': The name must be a string.');
  } else if (typeof argument.key !== 'string' || argument.key !== argument.key.toLowerCase()) {
    throw new TypeError(name + ': The key must be a lowercase string.');
  } else if (/\s/.test(argument.key)) {
    throw new TypeError(name + ': The key may not contain any whitespace characters.');
  } else if (typeof argument.type !== 'string' || argument.type !== argument.type.toLowerCase()) {
    throw new TypeError(name + ': The type must be a lowercase string.');
  } else if (typeof argument.example !== 'string') {
    throw new TypeError(name + ': The example must be a string.');
  } else if (!Array.isArray(argument.preconditions)) {
    throw new TypeError(name + ': The preconditions must be an array.');
  }

  for (const precondition of argument.preconditions) {
    if (typeof precondition !== 'object') {
      throw new TypeError(name + ': All argument precondition exports must be an instance of the argument precondition.');
    } else if (!(precondition instanceof ArgumentPrecondition)) {
      throw new TypeError(name + ': All argument preconditions must inherit the ArgumentPrecondition class.');
    }
  }
};
<commit_msg>I should drink more coffee<commit_after>const ArgumentPrecondition = require('./ArgumentPrecondition.js');

class Argument {
  constructor(options) {
    this.name = options.name;
    this.key = options.key;
    this.type = options.type;
    this.example = options.example;
    this.default = options.default;
    this.preconditions = options.preconditions !== undefined ?  options.preconditions : [];
    this.isOptional = options.default !== undefined;
    this.isRemainder = options.isRemainder !== undefined ?  options.isRemainder : false;

    validateArgument(this, this.constructor.name);
  }
}

module.exports = Argument;

const validateArgument = function(argument, name) {
  if (typeof argument.name !== 'string') {
    throw new TypeError(name + ': The name must be a string.');
  } else if (typeof argument.key !== 'string' || argument.key !== argument.key.toLowerCase()) {
    throw new TypeError(name + ': The key must be a lowercase string.');
  } else if (/\s/.test(argument.key)) {
    throw new TypeError(name + ': The key may not contain any whitespace characters.');
  } else if (typeof argument.type !== 'string' || argument.type !== argument.type.toLowerCase()) {
    throw new TypeError(name + ': The type must be a lowercase string.');
  } else if (typeof argument.example !== 'string') {
    throw new TypeError(name + ': The example must be a string.');
  } else if (!Array.isArray(argument.preconditions)) {
    throw new TypeError(name + ': The preconditions must be an array.');
  }

  for (const precondition of argument.preconditions) {
    if (typeof precondition !== 'object') {
      throw new TypeError(name + ': All argument precondition exports must be an instance of the argument precondition.');
    } else if (!(precondition instanceof ArgumentPrecondition)) {
      throw new TypeError(name + ': All argument preconditions must inherit the ArgumentPrecondition class.');
    }
  }
};
<|endoftext|>


<commit_before>const request = require('supertest');

const app = require('../src/server');

module.exports = {
    createCookieString: function(cookie) {
        if(cookie) {
            return "oAuth2ClientShell="
                // https://github.com/expressjs/express/issues/2815
                + encodeURIComponent("j:" + JSON.stringify(cookie));
            }
        return "oAuth2ClientShell=";
    },
    getCsrfTokens: function(cb) {
        request(app)
            .get('/')
            .expect('set-cookie', /_csrf=.*?[;,]/)
            .expect(/name="_csrf" value="(.*?)"/)
            .end(function(err, res) {
                if (err) return done(err);

                const cookieCsrf = /_csrf=(.*?);/.exec(res.headers['set-cookie'])[1];
                const formCsrf = /name="_csrf" value="(.*?)"/.exec(res.text)[1];
                cb(cookieCsrf, formCsrf);
        });
    }
};
<commit_msg>test - refactoring utils file. (#52)<commit_after>const request = require('supertest');

const app = require('../src/server');

function createCookieString(cookie) {
    if(cookie) {
        return "oAuth2ClientShell="
            // https://github.com/expressjs/express/issues/2815
            + encodeURIComponent("j:" + JSON.stringify(cookie));
        }
    return "oAuth2ClientShell=";
}

function getCsrfTokens(cb) {
    request(app)
        .get('/')
        .expect('set-cookie', /_csrf=.*?[;,]/)
        .expect(/name="_csrf" value="(.*?)"/)
        .end(function(err, res) {
            if (err) return done(err);

            const cookieCsrf = /_csrf=(.*?);/.exec(res.headers['set-cookie'])[1];
            const formCsrf = /name="_csrf" value="(.*?)"/.exec(res.text)[1];
            cb(cookieCsrf, formCsrf);
    });
}

module.exports = {
    createCookieString: createCookieString,
    getCsrfTokens: getCsrfTokens
};
<|endoftext|>


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

  function addClass(elements, myClass) {
    if (!elements) { return; }

    if (typeof(elements) === 'string') {
      elements = document.querySelectorAll(elements);
    }

    // If match is a single DOM element, make it an array to simplify behavior
    else if (elements.tagName) {
      elements=[elements];
    }

    // Add class to all chosen elements
    for (var i = 0; i < elements.length; i++) {
      if ( (' '+elements[i].className+' ').indexOf(' ' + myClass + ' ') < 0 ) {
        elements[i].className += ' ' + myClass;
      }
    }
  }

  function removeClass(elements, myClass) {
    if (!elements) { return; }

    if (typeof(elements) === 'string') {
      elements = document.querySelectorAll(elements);
    }

    // If match is a single DOM element, make it an array to simplify behavior
    else if (elements.tagName) {
      elements=[elements];
    }
    // Create pattern to find class name
    var reg = new RegExp('(^| )'+myClass+'($| )', 'g');

    // Remove class from all chosen elements
    for (var i = 0; i < elements.length; i++) {
      elements[i].className = elements[i].className.replace(reg, ' ');
    }
  }

  // Helper function for dispatching cross browser dispatch events
  // from http://youmightnotneedjquery.com/#trigger_custom
  function dispatchEvent (el, eventName, emmiter) {
    // IE < Edge Polyfill
    // from https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
    function _CustomEvent (event, params) {
      params = params || { bubbles: false, cancelable: false, detail: undefined };
      var evt = document.createEvent('CustomEvent');
      evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
      return evt;
    }

    _CustomEvent.prototype = window.Event.prototype;

    var event;

    if (window.CustomEvent && typeof window.CustomEvent === 'function') {
      event = new window.CustomEvent(eventName, { detail: emmiter });
    } else {
      event = new _CustomEvent(eventName, { bubbles: false, cancelable: false, detail: emmiter });
    }

    event && el.dispatchEvent(event);
  }

  // Helper function to get all focusable children from a node
  function getFocusableChildren (node) {
    var focusableElements = ['a[href]', 'area[href]', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', 'iframe', 'object', 'embed', '[contenteditable]', '[tabindex]:not([tabindex^="-"])'];

    return $$(focusableElements.join(','), node).filter(function (child) {
      return !!(child.offsetWidth || child.offsetHeight || child.getClientRects().length);
    });
  }

  // Helper function to get all nodes in context matching selector as an array
  function $$ (selector, context) {
    return Array.prototype.slice.call((context || document).querySelectorAll(selector));
  }

  // Helper function trapping the tab key inside a node
  function trapTabKey (node, event) {
    var focusableChildren = getFocusableChildren(node);
    var focusedItemIndex = focusableChildren.indexOf(document.activeElement);

    if (event.shiftKey && focusedItemIndex === 0) {
      focusableChildren[focusableChildren.length - 1].focus();
      event.preventDefault();
    } else if (!event.shiftKey && focusedItemIndex === focusableChildren.length - 1) {
      focusableChildren[0].focus();
      event.preventDefault();
    }
  }

  // Helper function to focus first focusable item in node
  function setFocusToFirstItem (node) {
    var focusableChildren = getFocusableChildren(node);
    if (focusableChildren.length) focusableChildren[0].focus();
  }

  var focusedBeforeDialog;

  /**
   * rbDialog constructor
   * @param {Node} node - Dialog element
   * @param {Node} main - Main element of the page
   */
  var rbDialog = function (node, main) {
    main = main || document.querySelector('#main');
    var that = this;
    var openers = $$('[data-rb-dialog-show="' + node.id + '"]');
    var closers = $$('[data-rb-dialog-hide]', node)
      .concat($$('[data-rb-dialog-hide="' + node.id + '"]'));

    if (node.hasAttribute('aria-hidden')) {
      this.shown = !JSON.parse(node.getAttribute('aria-hidden'));
    }

    this.show = show;
    this.hide = hide;
    this.destroy = destroy;

    openers.forEach(function (opener) {
      opener.addEventListener('click', show);
    });

    closers.forEach(function (closer) {
      closer.addEventListener('click', hide);
    });

    function bindKeypress (event) {
      if (that.shown && event.which === 27) {
        event.preventDefault();
        hide(event.which);
      }

      if (that.shown && event.which === 9) {
        trapTabKey(node, event);
      }
    }

    function maintainFocus (event) {
      if (that.shown && !node.contains(event.target)) {
        setFocusToFirstItem(node);
      }
    }

    function show () {
      if (that.shown) return;

      that.shown = true;

      addClass(main, 'is-dialog-open');

      node.removeAttribute('aria-hidden');
      main.setAttribute('aria-hidden', 'true');
      focusedBeforeDialog = document.activeElement;
      setFocusToFirstItem(node);
      document.body.addEventListener('focus', maintainFocus, true);
      document.addEventListener('keydown', bindKeypress);
      dispatchEvent(node, 'dialog:show', this);
    }

    function hide (key) {
      if (!that.shown) return;

      if ((event && (event.target.dataset.rbDialogHide !== undefined ||
          event.target.parentElement.dataset.rbDialogHide !== undefined ||
          event.target.parentElement.parentElement.dataset.rbDialogHide !== undefined)) ||
          key === 27) {
        that.shown = false;

        removeClass(main, 'is-dialog-open');

        node.setAttribute('aria-hidden', 'true');
        main.removeAttribute('aria-hidden');
        focusedBeforeDialog && focusedBeforeDialog.focus();
        document.body.removeEventListener('focus', maintainFocus, true);
        document.removeEventListener('keydown', bindKeypress);
        dispatchEvent(node, 'dialog:hide', this);
      }
    }

    function destroy () {
      hide();

      openers.forEach(function (opener) {
        opener.removeEventListener('click', show);
      });

      closers.forEach(function (closer) {
        closer.removeEventListener('click', hide);
      });
    }
  };

  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = rbDialog;
  } else if (typeof define === 'function' && define.amd) {
    define('rbDialog', [], function () {
      return rbDialog;
    });
  } else if (typeof global === 'object') {
    global.rbDialog = rbDialog;
  }
}(this));

(function () {
  document.addEventListener('DOMContentLoaded', function () {
    var dialogs = document.querySelectorAll('.dialog');

    var len = dialogs.length;
    for (var i = 0; i < len; i++) {
      var dialogEl = dialogs[i];
      var obscures = dialogEl.dataset.rbDialogObscures;
      var mainEl = document.getElementById(obscures);

      mainEl.parentNode.insertBefore(dialogEl, mainEl.nextSibling);

      var dialog = new window.rbDialog(dialogEl, mainEl);
    }
  });
}());
<commit_msg>Add fallback for IE's srcElement<commit_after>(function (global) {
  'use strict';

  function addClass(elements, myClass) {
    if (!elements) { return; }

    if (typeof(elements) === 'string') {
      elements = document.querySelectorAll(elements);
    }

    // If match is a single DOM element, make it an array to simplify behavior
    else if (elements.tagName) {
      elements=[elements];
    }

    // Add class to all chosen elements
    for (var i = 0; i < elements.length; i++) {
      if ( (' '+elements[i].className+' ').indexOf(' ' + myClass + ' ') < 0 ) {
        elements[i].className += ' ' + myClass;
      }
    }
  }

  function removeClass(elements, myClass) {
    if (!elements) { return; }

    if (typeof(elements) === 'string') {
      elements = document.querySelectorAll(elements);
    }

    // If match is a single DOM element, make it an array to simplify behavior
    else if (elements.tagName) {
      elements=[elements];
    }
    // Create pattern to find class name
    var reg = new RegExp('(^| )'+myClass+'($| )', 'g');

    // Remove class from all chosen elements
    for (var i = 0; i < elements.length; i++) {
      elements[i].className = elements[i].className.replace(reg, ' ');
    }
  }

  // Helper function for dispatching cross browser dispatch events
  // from http://youmightnotneedjquery.com/#trigger_custom
  function dispatchEvent (el, eventName, emmiter) {
    // IE < Edge Polyfill
    // from https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
    function _CustomEvent (event, params) {
      params = params || { bubbles: false, cancelable: false, detail: undefined };
      var evt = document.createEvent('CustomEvent');
      evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
      return evt;
    }

    _CustomEvent.prototype = window.Event.prototype;

    var event;

    if (window.CustomEvent && typeof window.CustomEvent === 'function') {
      event = new window.CustomEvent(eventName, { detail: emmiter });
    } else {
      event = new _CustomEvent(eventName, { bubbles: false, cancelable: false, detail: emmiter });
    }

    event && el.dispatchEvent(event);
  }

  // Helper function to get all focusable children from a node
  function getFocusableChildren (node) {
    var focusableElements = ['a[href]', 'area[href]', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', 'iframe', 'object', 'embed', '[contenteditable]', '[tabindex]:not([tabindex^="-"])'];

    return $$(focusableElements.join(','), node).filter(function (child) {
      return !!(child.offsetWidth || child.offsetHeight || child.getClientRects().length);
    });
  }

  // Helper function to get all nodes in context matching selector as an array
  function $$ (selector, context) {
    return Array.prototype.slice.call((context || document).querySelectorAll(selector));
  }

  // Helper function trapping the tab key inside a node
  function trapTabKey (node, event) {
    var focusableChildren = getFocusableChildren(node);
    var focusedItemIndex = focusableChildren.indexOf(document.activeElement);

    if (event.shiftKey && focusedItemIndex === 0) {
      focusableChildren[focusableChildren.length - 1].focus();
      event.preventDefault();
    } else if (!event.shiftKey && focusedItemIndex === focusableChildren.length - 1) {
      focusableChildren[0].focus();
      event.preventDefault();
    }
  }

  // Helper function to focus first focusable item in node
  function setFocusToFirstItem (node) {
    var focusableChildren = getFocusableChildren(node);
    if (focusableChildren.length) focusableChildren[0].focus();
  }

  var focusedBeforeDialog;

  /**
   * rbDialog constructor
   * @param {Node} node - Dialog element
   * @param {Node} main - Main element of the page
   */
  var rbDialog = function (node, main) {
    main = main || document.querySelector('#main');
    var that = this;
    var openers = $$('[data-rb-dialog-show="' + node.id + '"]');
    var closers = $$('[data-rb-dialog-hide]', node)
      .concat($$('[data-rb-dialog-hide="' + node.id + '"]'));

    if (node.hasAttribute('aria-hidden')) {
      this.shown = !JSON.parse(node.getAttribute('aria-hidden'));
    }

    this.show = show;
    this.hide = hide;
    this.destroy = destroy;

    openers.forEach(function (opener) {
      opener.addEventListener('click', show);
    });

    closers.forEach(function (closer) {
      closer.addEventListener('click', hide);
    });

    function bindKeypress (event) {
      if (that.shown && event.which === 27) {
        event.preventDefault();
        hide(event.which);
      }

      if (that.shown && event.which === 9) {
        trapTabKey(node, event);
      }
    }

    function maintainFocus (event) {
      var target;
      if (event) {
        if (event.target) {
          target = event.target;
        } else if (event.srcElement) {
          target = event.srcElement;
        }
      }

      if (that.shown && !node.contains(target)) {
        setFocusToFirstItem(node);
      }
    }

    function show () {
      if (that.shown) return;

      that.shown = true;

      addClass(main, 'is-dialog-open');

      node.removeAttribute('aria-hidden');
      main.setAttribute('aria-hidden', 'true');
      focusedBeforeDialog = document.activeElement;
      setFocusToFirstItem(node);
      document.body.addEventListener('focus', maintainFocus, true);
      document.addEventListener('keydown', bindKeypress);
      dispatchEvent(node, 'dialog:show', this);
    }

    function hide (key) {
      if (!that.shown) return;

      var target;
      if (event) {
        if (event.target) {
          target = event.target;
        } else if (event.srcElement) {
          target = event.srcElement;
        }
      }

      if ((event && (target.dataset.rbDialogHide !== undefined ||
          target.parentElement.dataset.rbDialogHide !== undefined ||
          target.parentElement.parentElement.dataset.rbDialogHide !== undefined)) ||
          key === 27) {
        that.shown = false;

        removeClass(main, 'is-dialog-open');

        node.setAttribute('aria-hidden', 'true');
        main.removeAttribute('aria-hidden');
        focusedBeforeDialog && focusedBeforeDialog.focus();
        document.body.removeEventListener('focus', maintainFocus, true);
        document.removeEventListener('keydown', bindKeypress);
        dispatchEvent(node, 'dialog:hide', this);
      }
    }

    function destroy () {
      hide();

      openers.forEach(function (opener) {
        opener.removeEventListener('click', show);
      });

      closers.forEach(function (closer) {
        closer.removeEventListener('click', hide);
      });
    }
  };

  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = rbDialog;
  } else if (typeof define === 'function' && define.amd) {
    define('rbDialog', [], function () {
      return rbDialog;
    });
  } else if (typeof global === 'object') {
    global.rbDialog = rbDialog;
  }
}(this));

(function () {
  document.addEventListener('DOMContentLoaded', function () {
    var dialogs = document.querySelectorAll('.dialog');

    var len = dialogs.length;
    for (var i = 0; i < len; i++) {
      var dialogEl = dialogs[i];
      var obscures = dialogEl.dataset.rbDialogObscures;
      var mainEl = document.getElementById(obscures);

      mainEl.parentNode.insertBefore(dialogEl, mainEl.nextSibling);

      var dialog = new window.rbDialog(dialogEl, mainEl);
    }
  });
}());
<|endoftext|>


<commit_before>/*global System*/
import { string } from "lively.lang";
import { Color } from "lively.graphics";
import { Morph } from "../index.js";
import { ClipboardHelper } from "./clipboard-helper.js";
import Selection from "./selection.js";
import { renderText } from "./rendering.js";

export class Text extends Morph {

  static makeLabel(string, props) {
    return new Text({
      textString: string,
      fontFamily: "Helvetica Neue, Arial",
      fontColor: Color.black,
      fontSize: 11,
      readOnly: true,
      ...props
    });
  }

  constructor(props) {
    super({
      readOnly: false,
      clipMode: "hidden",
      textString: "",
      fixedWidth: false, fixedHeight: false,
      padding: { top: 0, right: 0, bottom: 0, left: 0 },
      draggable: false,
      _selection: { start: 0, end: 0 },
      fontFamily: "Sans-Serif",
      fontSize: 12,
      ...props
    });
    this.fit();
    this._needsFit = false;
    this._needsSelect = false;

    // Note: clipboardHelper may already exist if this Text morph was copied
    this.clipboardHelper || this.addMorph(new ClipboardHelper());
  }

  get fontMetric() { return this.env.fontMetric; }

  get clipboardHelper() { return this.submorphs.filter(m => m.isClipboardHelper)[0]; }

  get isText() { return true }

  get textString() { return this.getProperty("textString") }
  set textString(value) {
    let oldText = this.textString;
    oldText && this.deleteText(0, oldText.length);
    this.insertText(0, value);
  }

  get readOnly() { return this.getProperty("readOnly"); }
  set readOnly(value) {
    this.nativeCursor = value ? "default" : "auto";
    this.addValueChange("readOnly", value);
  }

  get hasFocus() { return this.clipboardHelper._hasFocus; }

  get rejectsInput() { return this.readOnly || !this.hasFocus }

  get fixedWidth() { return this.getProperty("fixedWidth") }
  set fixedWidth(value) {
    this.addValueChange("fixedWidth", value);
    this._needsFit = true;
  }

  get fixedHeight() { return this.getProperty("fixedHeight") }
  set fixedHeight(value) {
    this.addValueChange("fixedHeight", value);
    this._needsFit = true;
  }

  get padding() {
    var _this = this;
    return {
      get top() { return _this.paddingTop; },
      set top(v) { _this.paddingTop = v; },
      get right() { return _this.paddingRight; },
      set right(v) { _this.paddingRight = v; },
      get bottom() { return _this.paddingBottom; },
      set bottom(v) { _this.paddingBottom = v; },
      get left() { return _this.paddingLeft; },
      set left(v) { _this.paddingLeft = v; },
    }
  }

  set padding(value) {
    if (typeof value === "number") {
      this.paddingTop = this.paddingRight = this.paddingBottom = this.paddingLeft = value;
    } else {
      ({ top: this.paddingTop, right: this.paddingRight, bottom: this.paddingBottom, left: this.paddingLeft }) = value;
    }
  }

  get paddingTop() { return this.getProperty("paddingTop") }
  set paddingTop(value) {
    this.addValueChange("paddingTop", typeof value === "number" ? value : 0);
    this._needsFit = true;
  }

  get paddingRight() { return this.getProperty("paddingRight") }
  set paddingRight(value) {
    this.addValueChange("paddingRight", typeof value === "number" ? value : 0);
    this._needsFit = true;
  }

  get paddingBottom() { return this.getProperty("paddingBottom") }
  set paddingBottom(value) {
    this.addValueChange("paddingBottom",typeof value === "number" ? value : 0);
    this._needsFit = true;
  }

  get paddingLeft() { return this.getProperty("paddingLeft") }
  set paddingLeft(value) {
    this.addValueChange("paddingLeft", typeof value === "number" ? value : 0);
    this._needsFit = true;
  }

  get fontFamily() { return this.getProperty("fontFamily") }
  set fontFamily(value) {
    this.addValueChange("fontFamily", value);
    this._needsFit = true;
  }

  get fontSize() { return this.getProperty("fontSize") }
  set fontSize(value) {
    this.addValueChange("fontSize", value);
    this._needsFit = true;
  }

  get fontColor() { return this.getProperty("fontColor") }
  set fontColor(value) {
    this.addValueChange("fontColor", value);
  }

  get placeholder() { return this.getProperty("placeholder") }
  set placeholder(value) {
    this.addValueChange("placeholder", value);
    this._needsFit = true;
  }

  get _selection() { return this.getProperty("_selection") }
  set _selection(value) { this.addValueChange("_selection", value); }

  get selection() { return new Selection(this) }

  insertText(pos, str) {
    var str = String(str),
        oldText = this.textString,
        newText = oldText ? oldText.substr(0, pos) + str + oldText.substr(pos) : str;
    this._needsFit = true;

    this.addValueChange(
      "textString", newText,
      {action: "insert", pos: pos, str: str});
  }

  deleteText(start, end) {
    var oldText = this.textString,
        newText = oldText.substr(0, start) + oldText.substr(end);
    this._needsFit = true;

    this.addValueChange(
      "textString", newText,
      {action: "delete", start: start, end: end});
  }

  selectionOrLineString() {
    var sel = this.selection;
    if (sel.text) return sel.text;
    var line = string.lineIndexComputer(this.textString)(sel.start),
        [start, end] = string.lineNumberToIndexesComputer(this.textString)(line);
    return this.textString.slice(start, end).trim();
  }

  aboutToRender(renderer) {
    super.aboutToRender(renderer);
    this.fitIfNeeded();
  }

  render(renderer) {
    return renderText(renderer, this);
  }

  fit() {
    var { fixedHeight, fixedWidth, padding } = this;
    if (fixedHeight && fixedWidth) return;

    var {fontMetric, fontFamily, fontSize, placeholder, textString} = this,
        {height: placeholderHeight, width: placeholderWidth} = fontMetric.sizeForStr(fontFamily, fontSize, placeholder || " "),
        {height, width} = fontMetric.sizeForStr(fontFamily, fontSize, textString);
    if (!fixedHeight)
      this.height = Math.max(placeholderHeight, height) + padding.top + padding.bottom;
    if (!fixedWidth)
      this.width = Math.max(placeholderWidth, width) + padding.left + padding.right;
  }

  fitIfNeeded() {
    if (this._needsFit) { this.fit(); this._needsFit = false; }
  }

  onMouseDown(evt) { this.onMouseMove(evt); }

  onMouseMove(evt) {
    var { clickedOnMorph, clickedOnPosition } = evt.state;
    if (clickedOnMorph === this) {
      var { fontFamily, fontSize, textString, fontMetric, selection, paddingLeft, paddingTop } = this,
          offset = pt(paddingLeft, paddingTop),
          startPos = this.localize(clickedOnPosition.subPt(offset)),
          endPos = this.localize(evt.position.subPt(offset)),
          { start: curStart, end: curEnd } = selection,
          start = fontMetric.indexFromPoint(fontFamily, fontSize, textString, startPos),
          end = fontMetric.indexFromPoint(fontFamily, fontSize, textString, endPos);
      if (start > end)
        [start, end] = [end, start];
      if (end !== curEnd || start !== curStart)
        selection.range = { start: start, end: end };
    }
  }

  onKeyUp(evt) {
    switch (evt.keyString()) {
      case 'Command-D': case 'Command-P': evt.stop(); break;
    }
  }

  async onKeyDown(evt) {
    var keyString = evt.keyString(),
        key = evt.domEvt.key,
        sel = this.selection;
    switch (keyString) {
      case 'Command-C': case 'Command-X': case 'Command-V':
        break; // handled by onCut()/onPaste()

      case 'Command-A':
        evt.stop();
        sel.range = { start: 0, end: this.textString.length };
        break;

      case 'Command-D':
        evt.stop();
        var result = await lively.vm.runEval(this.selectionOrLineString(), {System, targetModule: "lively://test-text/1"});
        this.world()[result.isError ? "logError" : "setStatusMessage"](result.value);
        break;

      case 'Command-P':
        evt.stop();
        var result = await lively.vm.runEval(this.selectionOrLineString(), {System, targetModule: "lively://test-text/1"});
        this.textString = this.textString.slice(0, sel.end) + result.value + this.textString.slice(sel.end);
        break;

      case 'Command-S':
        evt.stop();
        this.doSave();
        break;

      case 'Backspace':
        if (this.rejectsInput) break;
        evt.stop();
        sel.isCollapsed && sel.start && sel.start--;
        sel.text = "";
        sel.collapse();
        break;

      case 'Del': // forward-delete
        if (this.rejectsInput) break;
        evt.stop();
        sel.isCollapsed && sel.end++;
        sel.text = "";
        sel.collapse();
        break;

      case 'Left': case 'Right':
        evt.stop();
        sel.start += (keyString === 'Right' ? 1 : (sel.start > 0 ? -1 : 0));
        sel.collapse();
        break;

      case 'Up': case 'Down':
        evt.stop();
        var text = this.textString,
            line = string.lineIndexComputer(text)(sel.start),
            otherLine = line + (keyString === "Down" ? 1 : -1),
            rangeComp = string.lineNumberToIndexesComputer(text),
            [lineStart, lineEnd] = rangeComp(line),
            otherLineRange = rangeComp(otherLine),
            [otherLineStart, otherLineEnd] = otherLineRange || [lineStart, lineEnd];
        sel.start = Math.min(otherLineStart + (sel.start - lineStart), otherLineEnd-1);
        sel.collapse();
        break;

      default:
        if (this.rejectsInput) break;
        evt.stop();
        switch (key) {
          case 'Enter':
            sel.text = "\n"; break;
          case 'Space':
            sel.text = " "; break;
          case 'Tab':
            sel.text = "\t"; break;
          default:
            if (key.length === 1) sel.text = key;
            else return; // ignored key
        }
        sel.collapse(sel.start + 1);
    }
  }

  doSave() { /*...*/ }

  onCut(evt) {
    if (this.rejectsInput) return;
    this.onCopy(evt);
    var sel = this.selection;
    sel.text = "";
    sel.collapse();
  }

  onCopy(evt) {
    if (!this.hasFocus) return;
    evt.stop();
    evt.domEvt.clipboardData.setData("text", this.selection.text);
  }

  onPaste(evt) {
    if (this.rejectsInput) return;
    evt.stop();
    var sel = this.selection;
    sel.text = evt.domEvt.clipboardData.getData("text");
    sel.collapse(sel.end);
  }

  onFocus(evt) {
    this.clipboardHelper.focus();
    this.makeDirty();
  }

  onBlur(evt) { this.makeDirty(); }
}
<commit_msg>fix tests<commit_after>/*global System*/
import { string } from "lively.lang";
import { Color, pt } from "lively.graphics";
import { Morph } from "../index.js";
import { ClipboardHelper } from "./clipboard-helper.js";
import Selection from "./selection.js";
import { renderText } from "./rendering.js";

export class Text extends Morph {

  static makeLabel(string, props) {
    return new Text({
      textString: string,
      fontFamily: "Helvetica Neue, Arial",
      fontColor: Color.black,
      fontSize: 11,
      readOnly: true,
      ...props
    });
  }

  constructor(props) {
    super({
      readOnly: false,
      clipMode: "hidden",
      textString: "",
      fixedWidth: false, fixedHeight: false,
      padding: { top: 0, right: 0, bottom: 0, left: 0 },
      draggable: false,
      _selection: { start: 0, end: 0 },
      fontFamily: "Sans-Serif",
      fontSize: 12,
      ...props
    });
    this.fit();
    this._needsFit = false;
    this._needsSelect = false;

    // Note: clipboardHelper may already exist if this Text morph was copied
    this.clipboardHelper || this.addMorph(new ClipboardHelper());
  }

  get fontMetric() { return this.env.fontMetric; }

  get clipboardHelper() { return this.submorphs.filter(m => m.isClipboardHelper)[0]; }

  get isText() { return true }

  get textString() { return this.getProperty("textString") }
  set textString(value) {
    let oldText = this.textString;
    oldText && this.deleteText(0, oldText.length);
    this.insertText(0, value);
  }

  get readOnly() { return this.getProperty("readOnly"); }
  set readOnly(value) {
    this.nativeCursor = value ? "default" : "auto";
    this.addValueChange("readOnly", value);
  }

  get hasFocus() { return this.clipboardHelper._hasFocus; }

  get rejectsInput() { return this.readOnly || !this.hasFocus }

  get fixedWidth() { return this.getProperty("fixedWidth") }
  set fixedWidth(value) {
    this.addValueChange("fixedWidth", value);
    this._needsFit = true;
  }

  get fixedHeight() { return this.getProperty("fixedHeight") }
  set fixedHeight(value) {
    this.addValueChange("fixedHeight", value);
    this._needsFit = true;
  }

  get padding() {
    var _this = this;
    return {
      get top() { return _this.paddingTop; },
      set top(v) { _this.paddingTop = v; },
      get right() { return _this.paddingRight; },
      set right(v) { _this.paddingRight = v; },
      get bottom() { return _this.paddingBottom; },
      set bottom(v) { _this.paddingBottom = v; },
      get left() { return _this.paddingLeft; },
      set left(v) { _this.paddingLeft = v; },
    }
  }

  set padding(value) {
    if (typeof value === "number") {
      this.paddingTop = this.paddingRight = this.paddingBottom = this.paddingLeft = value;
    } else {
      ({ top: this.paddingTop, right: this.paddingRight, bottom: this.paddingBottom, left: this.paddingLeft }) = value;
    }
  }

  get paddingTop() { return this.getProperty("paddingTop") }
  set paddingTop(value) {
    this.addValueChange("paddingTop", typeof value === "number" ? value : 0);
    this._needsFit = true;
  }

  get paddingRight() { return this.getProperty("paddingRight") }
  set paddingRight(value) {
    this.addValueChange("paddingRight", typeof value === "number" ? value : 0);
    this._needsFit = true;
  }

  get paddingBottom() { return this.getProperty("paddingBottom") }
  set paddingBottom(value) {
    this.addValueChange("paddingBottom",typeof value === "number" ? value : 0);
    this._needsFit = true;
  }

  get paddingLeft() { return this.getProperty("paddingLeft") }
  set paddingLeft(value) {
    this.addValueChange("paddingLeft", typeof value === "number" ? value : 0);
    this._needsFit = true;
  }

  get fontFamily() { return this.getProperty("fontFamily") }
  set fontFamily(value) {
    this.addValueChange("fontFamily", value);
    this._needsFit = true;
  }

  get fontSize() { return this.getProperty("fontSize") }
  set fontSize(value) {
    this.addValueChange("fontSize", value);
    this._needsFit = true;
  }

  get fontColor() { return this.getProperty("fontColor") }
  set fontColor(value) {
    this.addValueChange("fontColor", value);
  }

  get placeholder() { return this.getProperty("placeholder") }
  set placeholder(value) {
    this.addValueChange("placeholder", value);
    this._needsFit = true;
  }

  get _selection() { return this.getProperty("_selection") }
  set _selection(value) { this.addValueChange("_selection", value); }

  get selection() { return new Selection(this) }

  insertText(pos, str) {
    var str = String(str),
        oldText = this.textString,
        newText = oldText ? oldText.substr(0, pos) + str + oldText.substr(pos) : str;
    this._needsFit = true;

    this.addValueChange(
      "textString", newText,
      {action: "insert", pos: pos, str: str});
  }

  deleteText(start, end) {
    var oldText = this.textString,
        newText = oldText.substr(0, start) + oldText.substr(end);
    this._needsFit = true;

    this.addValueChange(
      "textString", newText,
      {action: "delete", start: start, end: end});
  }

  selectionOrLineString() {
    var sel = this.selection;
    if (sel.text) return sel.text;
    var line = string.lineIndexComputer(this.textString)(sel.start),
        [start, end] = string.lineNumberToIndexesComputer(this.textString)(line);
    return this.textString.slice(start, end).trim();
  }

  aboutToRender(renderer) {
    super.aboutToRender(renderer);
    this.fitIfNeeded();
  }

  render(renderer) {
    return renderText(renderer, this);
  }

  fit() {
    var { fixedHeight, fixedWidth, padding } = this;
    if (fixedHeight && fixedWidth) return;

    var {fontMetric, fontFamily, fontSize, placeholder, textString} = this,
        {height: placeholderHeight, width: placeholderWidth} = fontMetric.sizeForStr(fontFamily, fontSize, placeholder || " "),
        {height, width} = fontMetric.sizeForStr(fontFamily, fontSize, textString);
    if (!fixedHeight)
      this.height = Math.max(placeholderHeight, height) + padding.top + padding.bottom;
    if (!fixedWidth)
      this.width = Math.max(placeholderWidth, width) + padding.left + padding.right;
  }

  fitIfNeeded() {
    if (this._needsFit) { this.fit(); this._needsFit = false; }
  }

  onMouseDown(evt) { this.onMouseMove(evt); }

  onMouseMove(evt) {
    var { clickedOnMorph, clickedOnPosition } = evt.state;
    if (clickedOnMorph === this) {
      var { fontFamily, fontSize, textString, fontMetric, selection, paddingLeft, paddingTop } = this,
          offset = pt(paddingLeft, paddingTop),
          startPos = this.localize(clickedOnPosition.subPt(offset)),
          endPos = this.localize(evt.position.subPt(offset)),
          { start: curStart, end: curEnd } = selection,
          start = fontMetric.indexFromPoint(fontFamily, fontSize, textString, startPos),
          end = fontMetric.indexFromPoint(fontFamily, fontSize, textString, endPos);
      if (start > end)
        [start, end] = [end, start];
      if (end !== curEnd || start !== curStart)
        selection.range = { start: start, end: end };
    }
  }

  onKeyUp(evt) {
    switch (evt.keyString()) {
      case 'Command-D': case 'Command-P': evt.stop(); break;
    }
  }

  async onKeyDown(evt) {
    var keyString = evt.keyString(),
        key = evt.domEvt.key,
        sel = this.selection;
    switch (keyString) {
      case 'Command-C': case 'Command-X': case 'Command-V':
        break; // handled by onCut()/onPaste()

      case 'Command-A':
        evt.stop();
        sel.range = { start: 0, end: this.textString.length };
        break;

      case 'Command-D':
        evt.stop();
        var result = await lively.vm.runEval(this.selectionOrLineString(), {System, targetModule: "lively://test-text/1"});
        this.world()[result.isError ? "logError" : "setStatusMessage"](result.value);
        break;

      case 'Command-P':
        evt.stop();
        var result = await lively.vm.runEval(this.selectionOrLineString(), {System, targetModule: "lively://test-text/1"});
        this.textString = this.textString.slice(0, sel.end) + result.value + this.textString.slice(sel.end);
        break;

      case 'Command-S':
        evt.stop();
        this.doSave();
        break;

      case 'Backspace':
        if (this.rejectsInput) break;
        evt.stop();
        sel.isCollapsed && sel.start && sel.start--;
        sel.text = "";
        sel.collapse();
        break;

      case 'Del': // forward-delete
        if (this.rejectsInput) break;
        evt.stop();
        sel.isCollapsed && sel.end++;
        sel.text = "";
        sel.collapse();
        break;

      case 'Left': case 'Right':
        evt.stop();
        sel.start += (keyString === 'Right' ? 1 : (sel.start > 0 ? -1 : 0));
        sel.collapse();
        break;

      case 'Up': case 'Down':
        evt.stop();
        var text = this.textString,
            line = string.lineIndexComputer(text)(sel.start),
            otherLine = line + (keyString === "Down" ? 1 : -1),
            rangeComp = string.lineNumberToIndexesComputer(text),
            [lineStart, lineEnd] = rangeComp(line),
            otherLineRange = rangeComp(otherLine),
            [otherLineStart, otherLineEnd] = otherLineRange || [lineStart, lineEnd];
        sel.start = Math.min(otherLineStart + (sel.start - lineStart), otherLineEnd-1);
        sel.collapse();
        break;

      default:
        if (this.rejectsInput) break;
        evt.stop();
        switch (key) {
          case 'Enter':
            sel.text = "\n"; break;
          case 'Space':
            sel.text = " "; break;
          case 'Tab':
            sel.text = "\t"; break;
          default:
            if (key.length === 1) sel.text = key;
            else return; // ignored key
        }
        sel.collapse(sel.start + 1);
    }
  }

  doSave() { /*...*/ }

  onCut(evt) {
    if (this.rejectsInput) return;
    this.onCopy(evt);
    var sel = this.selection;
    sel.text = "";
    sel.collapse();
  }

  onCopy(evt) {
    if (!this.hasFocus) return;
    evt.stop();
    evt.domEvt.clipboardData.setData("text", this.selection.text);
  }

  onPaste(evt) {
    if (this.rejectsInput) return;
    evt.stop();
    var sel = this.selection;
    sel.text = evt.domEvt.clipboardData.getData("text");
    sel.collapse(sel.end);
  }

  onFocus(evt) {
    this.clipboardHelper.focus();
    this.makeDirty();
  }

  onBlur(evt) { this.makeDirty(); }
}
<|endoftext|>


<commit_before>var check = require('check-types');
var q = require('q');
var _ = require('lodash');
var installModule = require('./module-install');
var reportSuccess = require('./report').reportSuccess;
var reportFailure = require('./report').reportFailure;

var cleanVersions = require('./registry').cleanVersions;
check.verifyFunction(cleanVersions, 'cleanVersions should be a function');

var revertModules = require('./revert');
check.verifyFunction(revertModules, 'revert is not a function, but ' +
    JSON.stringify(revertModules));

var npmTest = require('./npm-test').test;
var execTest = require('./exec-test');

// expect array of objects, each {name, versions (Array) }
// returns promise
function testModulesVersions(options, available) {
    check.verifyObject(options, 'missing options');
    check.verifyArray(available, 'expected array of available modules');

    var cleaned = cleanVersions(options.modules);
    var listed = _.zipObject(cleaned);

    console.log('newer version available');
    console.log(available);

    if (options.all) {
        var install = installAll(available);
        console.assert(install, 'could not get install all promise');
        var test = testPromise(options.command);
        console.assert(test, 'could not get test promise for command', options.command);
        console.dir(listed);
        console.dir(options.modules);
        var revert = revertModules.bind(null, listed);
        console.assert(revert, 'could not get revert promise');
        return install.then(test).then(revert);
    }

    return installEachTestRevert(listed, available, options.command);
}

// returns promise, does not revert
function installAll(available) {
    check.verifyArray(available, 'expected array');

    var installFunctions = available.map(function (nameVersions) {
        var name = nameVersions.name;
        var version = nameVersions.versions[0];
        check.verifyString(name, 'missing module name from ' +
            JSON.stringify(nameVersions));
        check.verifyString(version, 'missing module version from ' +
            JSON.stringify(nameVersions));

        var installFunction = installModule.bind(null, name, version);
        return installFunction;
    });
    var installAllPromise = installFunctions.reduce(q.when, q());
    return installAllPromise;
}

function installEachTestRevert(listed, available, command) {
    check.verifyObject(listed, 'expected listed object');
    check.verifyArray(available, 'expected array');

    var checkModulesFunctions = available.map(function (nameVersion) {
        var name = nameVersion.name;
        var currentVersion = listed[name];
        check.verifyString(currentVersion, 'cannot find current version for ' + name +
            ' among current dependencies ' + JSON.stringify(listed));

        var revertFunction = installModule.bind(null, name, currentVersion);
        var checkModuleFunction = testModuleVersions.bind(null, {
            moduleVersions: nameVersion,
            revertFunction: revertFunction,
            command: command
        });
        return checkModuleFunction;
    });
    var checkAllPromise = checkModulesFunctions.reduce(q.when, q());
    return checkAllPromise;
}

// test particular dependency with multiple versions
// returns promise
function testModuleVersions(options, results) {
    check.verifyObject(options, 'missing options');
    var nameVersions = options.moduleVersions;
    var restoreVersionFunc = options.revertFunction;

    var name = nameVersions.name;
    var versions = nameVersions.versions;
    check.verifyString(name, 'expected name string');
    check.verifyArray(versions, 'expected versions array');
    results = results || [];
    check.verifyArray(results, 'expected results array');

    var deferred = q.defer();
    var checkPromises = versions.map(function (version) {
        return testModuleVersion.bind(null, {
            name: name,
            version: version,
            command: options.command
        });
    });
    var checkAllPromise = checkPromises.reduce(q.when, q());
    checkAllPromise
    .then(restoreVersionFunc)
    .then(function (result) {
        results.push(result);
        deferred.resolve(results);
    }, function (error) {
        console.error('could not check', nameVersions, error);
        deferred.reject(error);
    });

    return deferred.promise;
}

// checks specific module@version
// returns promise
function testModuleVersion(options, results) {
    check.verifyObject(options, 'missing test module options');
    check.verifyString(options.name, 'missing module name');
    check.verifyString(options.version, 'missing version string');

    if (options.command) {
        check.verifyString(options.command, 'expected command string');
    }

    results = results || [];
    check.verifyArray(results, 'missing previous results array');

    var nameVersion = options.name + '@' + options.version;
    console.log('testing', nameVersion);

    var result = {
        name: options.name,
        version: options.version,
        works: true
    };

    var test = testPromise(options.command);
    console.assert(test, 'could not get test promise for command', options.command);

    var deferred = q.defer();
    var installPromise = installModule(options.name, options.version);
    installPromise.then(test).then(function () {
        reportSuccess(nameVersion + ' test success');
        results.push(result);
        deferred.resolve(results);
    }, function (error) {
        reportFailure(nameVersion + ' test failed :(');
        console.error(error);
        result.works = false;
        results.push(result);
        deferred.resolve(results);
    });
    return deferred.promise;
}

function testPromise(command) {
    var testFunction = npmTest;
    if (command) {
        check.verifyString(command, 'expected string command, not ' + command);
        testFunction = execTest.bind(null, command);
    }
    return testFunction;
}

module.exports = {
    testModulesVersions: testModulesVersions,
    testModuleVersion: testModuleVersion
};<commit_msg>using same reporter for available versions, fixes #50<commit_after>var check = require('check-types');
var q = require('q');
var _ = require('lodash');
var installModule = require('./module-install');
var reportSuccess = require('./report').reportSuccess;
var reportFailure = require('./report').reportFailure;

var cleanVersions = require('./registry').cleanVersions;
check.verifyFunction(cleanVersions, 'cleanVersions should be a function');

var revertModules = require('./revert');
check.verifyFunction(revertModules, 'revert is not a function, but ' +
    JSON.stringify(revertModules));

var npmTest = require('./npm-test').test;
var execTest = require('./exec-test');
var report = require('./report-available');

// expect array of objects, each {name, versions (Array) }
// returns promise
function testModulesVersions(options, available) {
    check.verifyObject(options, 'missing options');
    check.verifyArray(available, 'expected array of available modules');

    var cleaned = cleanVersions(options.modules);
    var listed = _.zipObject(cleaned);

    report(available);

    if (options.all) {
        var install = installAll(available);
        console.assert(install, 'could not get install all promise');
        var test = testPromise(options.command);
        console.assert(test, 'could not get test promise for command', options.command);
        console.dir(listed);
        console.dir(options.modules);
        var revert = revertModules.bind(null, listed);
        console.assert(revert, 'could not get revert promise');
        return install.then(test).then(revert);
    }

    return installEachTestRevert(listed, available, options.command);
}

// returns promise, does not revert
function installAll(available) {
    check.verifyArray(available, 'expected array');

    var installFunctions = available.map(function (nameVersions) {
        var name = nameVersions.name;
        var version = nameVersions.versions[0];
        check.verifyString(name, 'missing module name from ' +
            JSON.stringify(nameVersions));
        check.verifyString(version, 'missing module version from ' +
            JSON.stringify(nameVersions));

        var installFunction = installModule.bind(null, name, version);
        return installFunction;
    });
    var installAllPromise = installFunctions.reduce(q.when, q());
    return installAllPromise;
}

function installEachTestRevert(listed, available, command) {
    check.verifyObject(listed, 'expected listed object');
    check.verifyArray(available, 'expected array');

    var checkModulesFunctions = available.map(function (nameVersion) {
        var name = nameVersion.name;
        var currentVersion = listed[name];
        check.verifyString(currentVersion, 'cannot find current version for ' + name +
            ' among current dependencies ' + JSON.stringify(listed));

        var revertFunction = installModule.bind(null, name, currentVersion);
        var checkModuleFunction = testModuleVersions.bind(null, {
            moduleVersions: nameVersion,
            revertFunction: revertFunction,
            command: command
        });
        return checkModuleFunction;
    });
    var checkAllPromise = checkModulesFunctions.reduce(q.when, q());
    return checkAllPromise;
}

// test particular dependency with multiple versions
// returns promise
function testModuleVersions(options, results) {
    check.verifyObject(options, 'missing options');
    var nameVersions = options.moduleVersions;
    var restoreVersionFunc = options.revertFunction;

    var name = nameVersions.name;
    var versions = nameVersions.versions;
    check.verifyString(name, 'expected name string');
    check.verifyArray(versions, 'expected versions array');
    results = results || [];
    check.verifyArray(results, 'expected results array');

    var deferred = q.defer();
    var checkPromises = versions.map(function (version) {
        return testModuleVersion.bind(null, {
            name: name,
            version: version,
            command: options.command
        });
    });
    var checkAllPromise = checkPromises.reduce(q.when, q());
    checkAllPromise
    .then(restoreVersionFunc)
    .then(function (result) {
        results.push(result);
        deferred.resolve(results);
    }, function (error) {
        console.error('could not check', nameVersions, error);
        deferred.reject(error);
    });

    return deferred.promise;
}

// checks specific module@version
// returns promise
function testModuleVersion(options, results) {
    check.verifyObject(options, 'missing test module options');
    check.verifyString(options.name, 'missing module name');
    check.verifyString(options.version, 'missing version string');

    if (options.command) {
        check.verifyString(options.command, 'expected command string');
    }

    results = results || [];
    check.verifyArray(results, 'missing previous results array');

    var nameVersion = options.name + '@' + options.version;
    console.log('testing', nameVersion);

    var result = {
        name: options.name,
        version: options.version,
        works: true
    };

    var test = testPromise(options.command);
    console.assert(test, 'could not get test promise for command', options.command);

    var deferred = q.defer();
    var installPromise = installModule(options.name, options.version);
    installPromise.then(test).then(function () {
        reportSuccess(nameVersion + ' test success');
        results.push(result);
        deferred.resolve(results);
    }, function (error) {
        reportFailure(nameVersion + ' test failed :(');
        console.error(error);
        result.works = false;
        results.push(result);
        deferred.resolve(results);
    });
    return deferred.promise;
}

function testPromise(command) {
    var testFunction = npmTest;
    if (command) {
        check.verifyString(command, 'expected string command, not ' + command);
        testFunction = execTest.bind(null, command);
    }
    return testFunction;
}

module.exports = {
    testModulesVersions: testModulesVersions,
    testModuleVersion: testModuleVersion
};<|endoftext|>


<commit_before>/*global $ */
/*jslint
 white: true,
 vars: true,
 indent: 2
*/
(function($) {
  "use strict";
  $.fn.hideOtherLinks = function() {
    $(this).each(function(i, elm){
      var $el = $(elm),
          showHide = $(''),
          shownElements = [],
          hiddenElements = [],
          currentlyAppending = shownElements;

      $($el.contents()).each(function(i, el) {
        if (el.nodeValue && el.nodeValue === ".") {
          return;
        }
        currentlyAppending.push(el);
        if ($(el).is('a')) {
          currentlyAppending = hiddenElements;
        }
      });

      if (hiddenElements.length) {

        $el.empty();

        $(shownElements).each(function(i, el) {
          $el[0].appendChild(el);
        });

        $(hiddenElements).each(function(i, el) {
          showHide[0].appendChild(el);
        });

        $el.append(showHide);
        $el.append(".");

        showHide.hide();

        var otherCount = showHide.find('a').length;
        var toggle = $('+ '+ otherCount +' other'+ (otherCount > 1 ? 's' : '') +'');

        toggle.on('click', function(e) {
          e.preventDefault();
          $(this).remove();
          showHide.show().focus();
        });

        showHide.before(toggle);

        $el.attr('aria-live', 'polite');

      }

    });
    return this;
  };
})(jQuery);
<commit_msg>Stop IE7 showing empty show more links.<commit_after>/*global $ */
/*jslint
 white: true,
 vars: true,
 indent: 2
*/
(function($) {
  "use strict";
  $.fn.hideOtherLinks = function() {
    $(this).each(function(i, elm){
      var $el = $(elm),
          showHide = $(''),
          shownElements = [],
          hiddenElements = [],
          currentlyAppending = shownElements;

      $($el.contents()).each(function(i, el) {
        if (el.nodeValue && (el.nodeValue === "." || el.nodeValue === ' ')) {
          return;
        }
        currentlyAppending.push(el);
        if ($(el).is('a')) {
          currentlyAppending = hiddenElements;
        }
      });

      if (hiddenElements.length) {

        $el.empty();

        $(shownElements).each(function(i, el) {
          $el[0].appendChild(el);
        });

        $(hiddenElements).each(function(i, el) {
          showHide[0].appendChild(el);
        });

        $el.append(showHide);
        $el.append(".");

        showHide.hide();

        var otherCount = showHide.find('a').length;
        var toggle = $('+ '+ otherCount +' other'+ (otherCount > 1 ? 's' : '') +'');

        toggle.on('click', function(e) {
          e.preventDefault();
          $(this).remove();
          showHide.show().focus();
        });

        showHide.before(toggle);

        $el.attr('aria-live', 'polite');

      }

    });
    return this;
  };
})(jQuery);
<|endoftext|>


<commit_before>YUI.add("biddingbox", function (Y) {

    var BiddingBox = Y.Base.create("biddingbox", Y.Widget, [], {

        renderUI: function () {
            this._renderPassBox();
            this._renderBidBox();
            this._renderAlertBox();
        },

        _renderPassBox: function () {
            this._passBox = new Y.Bridge.PassBox().render(this.get("contentBox"));
        },

        _renderBidBox: function () {
            this._bidBox = new Y.Bridge.BidBox().render(this.get("contentBox"));
        },

        _renderAlertBox: function () {
            this._alertBox = new Y.Bridge.AlertBox().render(this.get("contentBox"));
        },

        bindUI: function () {
            this._passBox.after("bid", this._afterBid, this);
            this._bidBox.after("bid", this._afterBid, this);
            this.after("contractChange", this._afterContractChange);
            this.after("oursChange", this._afterOursChange);
        },

        _afterBid: function (event, bid) {
            this._fireBidEvent(bid);
        },

        _afterContractChange: function (event) {
            this._syncContract(event.newVal);
        },

        _afterOursChange: function (event) {
            this._syncOurs(event.newVal);
        },

        syncUI: function () {
            this._syncContract(this.get("contract"));
            this._syncOurs(this.get("ours"));
        },

        _syncContract: function (contract) {
            this._bidBox.set("contract", contract);
            this._syncOurs(this.get("ours")); // FIXME: it's not nice
        },

        _syncOurs: function (ours) {
            var contract = this.get("contract"),
                mods = Y.Bridge.parseModifiers(contract);

            this._passBox.set("enabledButtons", {
                PASS: true,
                X: !ours && !mods && Y.Lang.isValue(contract),
                XX: ours && mods === "X"
            });
        },

        _fireBidEvent: function (bid) {
            var alertData = this._getAlert();

            this.fire("bid", {}, {
                bid: bid,
                alert: alertData.alert,
                alertMsg: alertData.alertMsg
            });
        },

        _getAlert: function () {
            return this._alertBox.getAlertAndResetUI();
        }

    }, {

        ATTRS: {

            ours: {
                validator: Y.Lang.isBoolean
            },

            contract: {
                setter: function (contract) {
                    return (Y.Lang.isValue(contract) && Y.Bridge.isContract(contract)) ? contract : undefined;
                }
            }

        }
    });

    Y.namespace("Bridge").BiddingBox = BiddingBox;

}, "0", { requires: ["passbox", "bidbox", "alertbox"] });
<commit_msg>BiddingBox undefined contract mods fix<commit_after>YUI.add("biddingbox", function (Y) {

    var BiddingBox = Y.Base.create("biddingbox", Y.Widget, [], {

        renderUI: function () {
            this._renderPassBox();
            this._renderBidBox();
            this._renderAlertBox();
        },

        _renderPassBox: function () {
            this._passBox = new Y.Bridge.PassBox().render(this.get("contentBox"));
        },

        _renderBidBox: function () {
            this._bidBox = new Y.Bridge.BidBox().render(this.get("contentBox"));
        },

        _renderAlertBox: function () {
            this._alertBox = new Y.Bridge.AlertBox().render(this.get("contentBox"));
        },

        bindUI: function () {
            this._passBox.after("bid", this._afterBid, this);
            this._bidBox.after("bid", this._afterBid, this);
            this.after("contractChange", this._afterContractChange);
            this.after("oursChange", this._afterOursChange);
        },

        _afterBid: function (event, bid) {
            this._fireBidEvent(bid);
        },

        _afterContractChange: function (event) {
            this._syncContract(event.newVal);
        },

        _afterOursChange: function (event) {
            this._syncOurs(event.newVal);
        },

        syncUI: function () {
            this._syncContract(this.get("contract"));
            this._syncOurs(this.get("ours"));
        },

        _syncContract: function (contract) {
            this._bidBox.set("contract", contract);
            this._syncOurs(this.get("ours")); // FIXME: it's not nice
        },

        _syncOurs: function (ours) {
            var contract = this.get("contract"),
                mods = contract ? Y.Bridge.parseModifiers(contract) : "";

            this._passBox.set("enabledButtons", {
                PASS: true,
                X: !ours && !mods && Y.Lang.isValue(contract),
                XX: ours && mods === "X"
            });
        },

        _fireBidEvent: function (bid) {
            var alertData = this._getAlert();

            this.fire("bid", {}, {
                bid: bid,
                alert: alertData.alert,
                alertMsg: alertData.alertMsg
            });
        },

        _getAlert: function () {
            return this._alertBox.getAlertAndResetUI();
        }

    }, {

        ATTRS: {

            ours: {
                validator: Y.Lang.isBoolean
            },

            contract: {
                setter: function (contract) {
                    return (Y.Lang.isValue(contract) && Y.Bridge.isContract(contract)) ? contract : undefined;
                }
            }

        }
    });

    Y.namespace("Bridge").BiddingBox = BiddingBox;

}, "0", { requires: ["passbox", "bidbox", "alertbox"] });
<|endoftext|>


<commit_before>'use strict';

define(["app"], function(app) {

app.controller('MediasController', [
  "$scope", "$rootScope", "ImagesUtils", "$timeout",
  function($scope, $rootScope, $imagesUtils, $timeout) {

    $scope.display = false;
    $scope.urlImage = $imagesUtils.defaultImage();
    $scope.images = [];
    $scope.loading = true;

    $rootScope.$on('displayMedias', function(evt, message) {
      console.log(message);

      var pictures;
      if(message.picturesMax && message.picturesMax.length > 0) {
        pictures = message.picturesMax;
      } else {
        pictures = message.picturesMin;
      }

      $scope.urlImage = $imagesUtils.checkExistingImage(pictures[0]);
      $scope.images = [];
      if(message.picturesMin.length > 1) {
        for (var i = 0; i < message.picturesMin.length; i++) {
          $scope.images.push($imagesUtils.checkExistingImage(message.picturesMin[i]));
        };
      }
      $scope.display = true;
      $scope.loading = true;
      $timeout(function() {
        $scope.loading = false;
      }, 3000);
    });

    $scope.selectImage = function(urlImage) {
      $scope.urlImage = urlImage;
      $scope.loading = true;
      $timeout(function() {
        $scope.loading = false;
      }, 2000);
    }

    $scope.close = function() {
      $scope.display = false;
    }

  }]);
});<commit_msg>comment log<commit_after>'use strict';

define(["app"], function(app) {

app.controller('MediasController', [
  "$scope", "$rootScope", "ImagesUtils", "$timeout",
  function($scope, $rootScope, $imagesUtils, $timeout) {

    $scope.display = false;
    $scope.urlImage = $imagesUtils.defaultImage();
    $scope.images = [];
    $scope.loading = true;

    $rootScope.$on('displayMedias', function(evt, message) {
      //console.log(message);

      var pictures;
      if(message.picturesMax && message.picturesMax.length > 0) {
        pictures = message.picturesMax;
      } else {
        pictures = message.picturesMin;
      }

      $scope.urlImage = $imagesUtils.checkExistingImage(pictures[0]);
      $scope.images = [];
      if(message.picturesMin.length > 1) {
        for (var i = 0; i < message.picturesMin.length; i++) {
          $scope.images.push($imagesUtils.checkExistingImage(message.picturesMin[i]));
        };
      }
      $scope.display = true;
      $scope.loading = true;
      $timeout(function() {
        $scope.loading = false;
      }, 3000);
    });

    $scope.selectImage = function(urlImage) {
      $scope.urlImage = urlImage;
      $scope.loading = true;
      $timeout(function() {
        $scope.loading = false;
      }, 2000);
    }

    $scope.close = function() {
      $scope.display = false;
    }

  }]);
});<|endoftext|>