<commit_before>exports.additional_staff_logins = [   'aarondruck',
                                      'chloeatplay',
                                      'christensenep',
                                      'cmcavoy',
                                      'dajbelshaw',
                                      'flukeout',
                                      'iamjessklein',
                                      'jdotpz',
                                      'Pomax',
                                      'ScottDowne',
                                      'sinker',
                                      'stenington',
                                      'threeqube',
                                      'zeejab' ];

exports.repos = {
  "github_organizations": [
    {
      "name" : "mozilla", // as appears in github url
        "teams" : [
          {
            "name" : "webmaker", // internal reference for reporting
            "repos" : [ // alphabetical keeps this easier to read
                "appmaker-components",
                "bucheron",
                "butter",
                "csp-logger",
                "eoy-fundraising",
                "events.webmaker.org",
                "friendlycode",
                "Gallery-Maker",
                "goggles.webmaker.org",
                "hookshot",
                "htmlsanitizer.org",
                "login.webmaker.org",
                "lumberyard",
                "make-valet",
                "make.mozilla.org",
                "makeapi-client",
                "makeapi-docs",
                "MakeAPI-Gallery",
                "MakeAPI",
                "makedrive",
                "makerstrap",
                "nav-global",
                "node-hubble",
                "node-rtltr",
                "node-webmaker-butler",
                "node-webmaker-i18n",
                "node-webmaker-loginapi",
                "node-webmaker-postalservice",
                "park-warden",
                "popcorn_maker",
                "popcorn-docs",
                "popcorn-js",
                "popcorn.webmaker.org",
                "popcornjs.org",
                "sawmill",
                "teach-appmaker",
                "thimble.webmaker.org",
                "togetherjs",
                "web-literacy-client",
                "webliteracystandard",
                "webmaker-analytics",
                "webmaker-auth-client",
                "webmaker-auth",
                "webmaker-code-of-conduct",
                "webmaker-download-locales",
                "webmaker-events-2",
                "webmaker-events-service",
                "webmaker-events",
                "webmaker-firehose",
                "webmaker-kits",
                "webmaker-kits-builder",
                "webmaker-language-picker",
                "webmaker-login-example",
                "webmaker-mediasync",
                "webmaker-profile-service",
                "webmaker-profile",
                "webmaker-profile-2",
                "Webmaker-Prototypes",
                "webmaker-suite",
                "webmaker-tests",
                "webmaker-translation-stats",
                "webmaker-ui",
                "webmaker.org"
            ]
          },
          {
            "name" : "openbadges",
            "repos" : [
              "badge-the-world",
              "badgekit-api",
              "badgekit-api-client",
              "badgeopolis",
              "badges.mozilla.org",
              "community.openbadges.org",
              "CSOL-site",
              "openbadger",
              "openbadger-client",
              "openbadges",
              "openbadges-backpack",
              "openbadges-badgekit",
              "openbadges-badges",
              "openbadges-badgestudio",
              "openbadges-bakery",
              "openbadges-bakery-service",
              "openbadges-cem",
              "openbadges-directory",
              "openbadges-discovery",
              "openbadges-discussion",
              "openbadges-specification",
              "openbadges-validator",
              "openbadges-validator-service",
              "openbadges.org"
            ]
          },
          {
            "name" : "opennews",
            "repos" : [
              "mozilla-opennews",
              "source"
            ]
          }
        ]
    },
    {
      "name" : "openNews",
        "teams" : [
          {
            "name" : "opennews",
            "repos" : [
              "amo",
              "NewsYourOwnAdventure",
              "nomo",
              "opennews.github.com",
              "spiders",
              "zeit-online-republica-tracker"
            ]
          }
      ]
    },
    {
      "name" : "mozilla-appmaker",
        "teams" : [
          {
            "name" : "appmaker",
            "repos" : [
              "appmaker",
              "ceci",
              "ceci-button",
              "ceci-fork-me",
              "ceci-support",
              "chefbot",
              "component-addform",
              "component-alternating-gate",
              "component-button",
              "component-button-with-confirmation",
              "component-camera-button",
              "component-chat-window",
              "component-counter",
              "component-dataview",
              "component-editform",
              "component-fireworks",
              "component-header",
              "component-image",
              "component-metronome",
              "component-paypal",
              "component-spacer",
              "component-splitter",
              "component-template",
              "component-text-input",
              "component-textbox",
              "dashboard",
              "haas",
              "mozilla-appmaker.github.io",
              "phonegap-appmaker-harness",
              "start-here",
              "tools",
              "views"
            ]
          }
      ]
    },
    {
      "name" : "swcarpentry",
        "teams" : [
          {
            "name" : "sciencelab",
            "repos" : [
              "site"
            ]
          }
      ]
    },
    {
      "name" : "mozillascience",
        "teams" : [
          {
            "name" : "sciencelab",
            "repos" : [
              "code-research-object"
            ]
          }
      ]
    },
    {
      "name" : "mozillafordevelopment",
        "teams" : [
          {
            "name" : "webmaker",
            "repos" : [
              "webmaker-app-publisher",
              "webmaker-app",
              "beaker",
              "webmaker-app-csvexport",
              "webmaker-app-guide",
              "Exploring-challenge",
              "player",
              "fieldresearch",
              "mozillafordevelopment.github.io"
            ]
          }
      ]
    }
  ]
};
<commit_msg>adding other new webmaker repos<commit_after>exports.additional_staff_logins = [   'aarondruck',
                                      'chloeatplay',
                                      'christensenep',
                                      'cmcavoy',
                                      'dajbelshaw',
                                      'flukeout',
                                      'iamjessklein',
                                      'jdotpz',
                                      'Pomax',
                                      'ScottDowne',
                                      'sinker',
                                      'stenington',
                                      'threeqube',
                                      'zeejab' ];

exports.repos = {
  "github_organizations": [
    {
      "name" : "mozilla", // as appears in github url
        "teams" : [
          {
            "name" : "webmaker", // internal reference for reporting
            "repos" : [ // alphabetical keeps this easier to read
                "appmaker-components",
                "bucheron",
                "butter",
                "csp-logger",
                "eoy-fundraising",
                "events.webmaker.org",
                "friendlycode",
                "Gallery-Maker",
                "goggles.webmaker.org",
                "hookshot",
                "htmlsanitizer.org",
                "login.webmaker.org",
                "lumberyard",
                "make-valet",
                "make.mozilla.org",
                "makeapi-client",
                "makeapi-docs",
                "MakeAPI-Gallery",
                "MakeAPI",
                "makedrive",
                "makerstrap",
                "nav-global",
                "nimble.webmaker.org",
                "node-hubble",
                "node-rtltr",
                "node-webmaker-butler",
                "node-webmaker-i18n",
                "node-webmaker-loginapi",
                "node-webmaker-postalservice",
                "park-warden",
                "popcorn_maker",
                "popcorn-docs",
                "popcorn-js",
                "popcorn.webmaker.org",
                "popcornjs.org",
                "sawmill",
                "teach-appmaker",
                "thimble.webmaker.org",
                "togetherjs",
                "web-literacy-client",
                "webliteracystandard",
                "webmaker-analytics",
                "webmaker-auth-client",
                "webmaker-auth",
                "webmaker-code-of-conduct",
                "webmaker-download-locales",
                "webmaker-events-2",
                "webmaker-events-service",
                "webmaker-events",
                "webmaker-events-2",
                "webmaker-firehose",
                "webmaker-kits",
                "webmaker-kits-builder",
                "webmaker-landing-pages",
                "webmaker-language-picker",
                "webmaker-login-example",
                "webmaker-locales-mapping-configuration",
                "webmaker-login-ux",
                "webmaker-mailroom",
                "webmaker-mediasync",
                "webmaker-personas",
                "webmaker-profile-service",
                "webmaker-profile",
                "webmaker-profile-2",
                "Webmaker-Prototypes",
                "webmaker-rid",
                "webmaker-suite",
                "webmaker-tests",
                "webmaker-translation-stats",
                "webmaker-user-client",
                "webmaker-ui",
                "webmaker.org"
            ]
          },
          {
            "name" : "openbadges",
            "repos" : [
              "badge-the-world",
              "badgekit-api",
              "badgekit-api-client",
              "badgeopolis",
              "badges.mozilla.org",
              "community.openbadges.org",
              "CSOL-site",
              "openbadger",
              "openbadger-client",
              "openbadges",
              "openbadges-backpack",
              "openbadges-badgekit",
              "openbadges-badges",
              "openbadges-badgestudio",
              "openbadges-bakery",
              "openbadges-bakery-service",
              "openbadges-cem",
              "openbadges-directory",
              "openbadges-discovery",
              "openbadges-discussion",
              "openbadges-specification",
              "openbadges-validator",
              "openbadges-validator-service",
              "openbadges.org"
            ]
          },
          {
            "name" : "opennews",
            "repos" : [
              "mozilla-opennews",
              "source"
            ]
          }
        ]
    },
    {
      "name" : "openNews",
        "teams" : [
          {
            "name" : "opennews",
            "repos" : [
              "amo",
              "NewsYourOwnAdventure",
              "nomo",
              "opennews.github.com",
              "spiders",
              "zeit-online-republica-tracker"
            ]
          }
      ]
    },
    {
      "name" : "mozilla-appmaker",
        "teams" : [
          {
            "name" : "appmaker",
            "repos" : [
              "appmaker",
              "ceci",
              "ceci-button",
              "ceci-fork-me",
              "ceci-support",
              "chefbot",
              "component-addform",
              "component-alternating-gate",
              "component-button",
              "component-button-with-confirmation",
              "component-camera-button",
              "component-chat-window",
              "component-counter",
              "component-dataview",
              "component-editform",
              "component-fireworks",
              "component-header",
              "component-image",
              "component-metronome",
              "component-paypal",
              "component-spacer",
              "component-splitter",
              "component-template",
              "component-text-input",
              "component-textbox",
              "dashboard",
              "haas",
              "mozilla-appmaker.github.io",
              "phonegap-appmaker-harness",
              "start-here",
              "tools",
              "views"
            ]
          }
      ]
    },
    {
      "name" : "swcarpentry",
        "teams" : [
          {
            "name" : "sciencelab",
            "repos" : [
              "site"
            ]
          }
      ]
    },
    {
      "name" : "mozillascience",
        "teams" : [
          {
            "name" : "sciencelab",
            "repos" : [
              "code-research-object"
            ]
          }
      ]
    },
    {
      "name" : "mozillafordevelopment",
        "teams" : [
          {
            "name" : "webmaker",
            "repos" : [
              "webmaker-app-publisher",
              "webmaker-app",
              "beaker",
              "webmaker-app-csvexport",
              "webmaker-app-guide",
              "Exploring-challenge",
              "player",
              "fieldresearch",
              "mozillafordevelopment.github.io"
            ]
          }
      ]
    }
  ]
};
<|endoftext|>


<commit_before>;( function( $, window, document, undefined ) {

    'use strict';

    var pluginName = 'topmodal',
        defaults = {
            topmodal:             '.js-topmodal',
            topmodalBtn:          '.js-topmodal-btn',
            topmodalBtnClose:     '.js-topmodal-btn-close',
            topmodalContainer:    '.js-topmodal-container',
            topmodalOverlay:      '.js-topmodal-overlay'
        };

    function Plugin ( element, options ) {
        this.element = element;
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    $.extend( Plugin.prototype, {
        init: function() {
            var _obj = this.settings;
            Plugin.prototype.handleOptions( _obj );
        },

        show: function( _obj ) {
            $( _obj.topmodal ).addClass( 'is-open' );
        },

        hide: function( _obj ) {
            $( _obj.topmodal ).removeClass( 'is-open' );
        },

        showContainer: function( _obj ) {
            $( _obj.topmodalContainer ).addClass( 'is-open' );
        },

        hideContainer: function( _obj ) {
            $( _obj.topmodalContainer ).removeClass( 'is-open' );
        },

        showOverlay: function( _obj ) {
            $( _obj.topmodalOverlay ).addClass( 'is-open' );
        },

        hideOverlay: function( _obj ) {
            $( _obj.topmodalOverlay ).removeClass( 'is-open' );
        },

        handleOptions: function( _obj ) {
            $( document ).on( 'click', _obj.topmodalBtn, function() {
                Plugin.prototype.show( _obj );
                Plugin.prototype.showContainer( _obj );
                Plugin.prototype.showOverlay( _obj );
            });

            $( document ).on( 'click', _obj.topmodalBtnClose, function() {
                Plugin.prototype.hide( _obj );
                Plugin.prototype.hideContainer( _obj );
                Plugin.prototype.hideOverlay( _obj );
            });

            $( document ).on( 'click', _obj.topmodalContainer, function() {
                Plugin.prototype.hide( _obj );
                Plugin.prototype.hideContainer( _obj );
                Plugin.prototype.hideOverlay( _obj );
            });

            $( document ).on( 'click', _obj.topmodal, function( event ) {
                event.stopPropagation();
            });
        }

    });

    $.fn[ pluginName ] = function( options ) {
        return this.each( function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" +
                    pluginName, new Plugin( this, options ) );
            }
        } );
    };

} )( jQuery, window, document );

// Init
// ToDo: Replace this shit

$('.js-topmodal--log').topmodal({
    topmodal:         '.js-topmodal--log',
    topmodalBtn:      '.js-topmodal-btn--log',
    topmodalBtnClose: '.js-topmodal-btn-closesss'
});

$('.js-topmodal--reg').topmodal({
    topmodal:          '.js-topmodal--reg',
    topmodalBtn:       '.js-topmodal-btn--reg'
});

$('.js-topmodal').topmodal();
<commit_msg>add Handler Methods<commit_after>;( function( $, window, document, undefined ) {

    'use strict';

    var pluginName = 'topmodal',
        defaults = {
            topmodal:             '.js-topmodal',
            topmodalBtn:          '.js-topmodal-btn',
            topmodalBtnClose:     '.js-topmodal-btn-close',
            topmodalContainer:    '.js-topmodal-container',
            topmodalOverlay:      '.js-topmodal-overlay'
        };

    function Plugin ( element, options ) {
        this.element = element;
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    $.extend( Plugin.prototype, {
        init: function() {
            var _obj = this.settings;
            Plugin.prototype.handlerMethods( _obj );
        },

        handlerMethods: function( _obj ) {
            $( document ).on( 'click', _obj.topmodalBtn, function() {
                Plugin.prototype.show( _obj );
                Plugin.prototype.showContainer( _obj );
                Plugin.prototype.showOverlay( _obj );
            });

            $( document ).on( 'click', _obj.topmodalBtnClose, function() {
                Plugin.prototype.hide( _obj );
                Plugin.prototype.hideContainer( _obj );
                Plugin.prototype.hideOverlay( _obj );
            });

            $( document ).on( 'click', _obj.topmodalContainer, function() {
                Plugin.prototype.hide( _obj );
                Plugin.prototype.hideContainer( _obj );
                Plugin.prototype.hideOverlay( _obj );
            });

            $( document ).on( 'click', _obj.topmodal, function( event ) {
                event.stopPropagation();
            });
        },

        show: function( _obj ) {
            $( _obj.topmodal ).addClass( 'is-open' );
        },

        hide: function( _obj ) {
            $( _obj.topmodal ).removeClass( 'is-open' );
        },

        showContainer: function( _obj ) {
            $( _obj.topmodalContainer ).addClass( 'is-open' );
        },

        hideContainer: function( _obj ) {
            $( _obj.topmodalContainer ).removeClass( 'is-open' );
        },

        showOverlay: function( _obj ) {
            $( _obj.topmodalOverlay ).addClass( 'is-open' );
        },

        hideOverlay: function( _obj ) {
            $( _obj.topmodalOverlay ).removeClass( 'is-open' );
        }
    });

    $.fn[ pluginName ] = function( options ) {
        return this.each( function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" +
                    pluginName, new Plugin( this, options ) );
            }
        } );
    };

} )( jQuery, window, document );

// Init
// ToDo: Replace this shit

$('.js-topmodal--log').topmodal({
    topmodal:         '.js-topmodal--log',
    topmodalBtn:      '.js-topmodal-btn--log',
    topmodalBtnClose: '.js-topmodal-btn-closesss'
});

$('.js-topmodal--reg').topmodal({
    topmodal:          '.js-topmodal--reg',
    topmodalBtn:       '.js-topmodal-btn--reg'
});

$('.js-topmodal').topmodal();
<|endoftext|>


<commit_before>"use strict";

const is = require("./lib/is");

function traverse(root, options) {
    options = options || {};
    const pre = options.pre;
    const post = options.post;

    function visit(node, parent) {
        if (!node || !is.string(node.type)) {
            return;
        }

        if (!is.in(node, "$parent")) {
            node.$parent = parent;
        }

        let res = undefined;
        if (pre) {
            res = pre(node);
        }

        if (res !== false) {
            const props = Object.keys(node).filter(function(prop) {
                return prop[0] !== "$";
            });

            props.forEach(function(prop) {
                var child = node[prop];

                if (Array.isArray(child)) {
                    child.forEach(function(child) {
                        visit(child, node);
                    });
                } else {
                    visit(child, node);
                }
            });
        }

        if (post) {
            post(node);
        }
    }

    visit(root, null);
};
module.exports = traverse;
<commit_msg>traverse: much faster by using plain for-loops<commit_after>"use strict";

const is = require("./lib/is");

function traverse(root, options) {
    options = options || {};
    const pre = options.pre;
    const post = options.post;

    function visit(node, parent) {
        if (!node || !is.string(node.type)) {
            return;
        }

        if (!is.in(node, "$parent")) {
            node.$parent = parent;
        }

        let res = undefined;
        if (pre) {
            res = pre(node);
        }

        if (res !== false) {
            for (let prop in node) {
                if (prop[0] === "$") {
                    continue;
                }

                var child = node[prop];

                if (Array.isArray(child)) {
                    for (let i = 0; i < child.length; i++) {
                        visit(child[i], node);
                    }
                } else {
                    visit(child, node);
                }
            }
        }

        if (post) {
            post(node);
        }
    }

    visit(root, null);
};
module.exports = traverse;
<|endoftext|>


<commit_before>/* eslint-env mocha */
/* eslint-disable func-names, prefer-arrow-callback  */

import { expect } from 'chai';
import request from 'supertest';

import app from '../../app';
import nconf from '../../config';
import {
  token,
  lowPermissionPrimaryToken,
  highPermissionOfficerToken,
  lowPermissionOfficerToken,
  highPermissionUserToken,
} from '../helpers';

describe('INTEGRATION TESTS: EVENTS', function () {
  describe('GET /', function () {
    it('Returns Events When Accepting JSON', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by an Existing Name', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by an Non-existent Name', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by an Existing Committee', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by an Non-existent Committee', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by an Existing Location', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by an Non-existent Location', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by Between', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by Before', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by After', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by Featured', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by Sort', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Returns a Calendar Event When Accepting ICS', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Does Not Accept Requests Not Accepting JSON or ICS', function (done) {
      expect(false).to.equal(true);
      done();
    });
  });

  describe('POST /', function () {
    it('Requires Authentication', function (done) {
      const expected = {
        error: 'No authorization token was found',
      };

      request(app)
        .post('/api/v2/events')
        .expect(401)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });

    it('Requires Expected Permissions', function (done) {
      // Need Low Permissions be an Officer or Primary Officer
      const expected = {
        error: 'User does not have permission: create events',
      };

      const eventInput = {
        name: 'A Cool Talk',
        committeeName: 'Talks',
        startDate: '2017-06-12T05:00:00.000Z',
        endDate: '2017-06-12T10:00:00.000Z',
        location: 'The Lab',
      };

      // Deny User w/ High Permission Token
      const userHigh = request(app)
        .post('/api/v2/events')
        .set('Authorization', `Bearer ${highPermissionUserToken}`)
        .expect(403)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
        });
      // Allow Primary Officer w/ Low Permission Token
      const primaryLow = request(app)
        .post('/api/v2/events')
        .set('Authorization', `Bearer ${lowPermissionPrimaryToken}`)
        .send(eventInput)
        .expect(201);
      // Allow Officer w/ Low Permission Token
      const officerLow = request(app)
        .post('/api/v2/events')
        .set('Authorization', `Bearer ${lowPermissionOfficerToken}`)
        .send(eventInput)
        .expect(201);

      Promise.all([
        userHigh,
        primaryLow,
        officerLow,
      ]).then(() => {
        done();
      });
    });

    it('Creates an Event', function (done) {
      const expected = {
        name: 'A Cool Talk',
        committeeName: 'Talks',
        startDate: '2017-06-12T05:00:00.000Z',
        endDate: '2017-06-12T10:00:00.000Z',
        location: 'The Lab',
      };

      request(app)
        .post('/api/v2/events')
        .set('Authorization', `Bearer ${token}`)
        .send(expected)
        .expect(201)
        .then((response) => {
          delete response.body.id;
          delete response.body.createdAt;
          delete response.body.updatedAt;
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });

    it('Requires Start Date to be Before End Date', function (done) {
      const expected = {
        error: 'Validation error: Start date must be before the end date',
      };

      request(app)
        .post('/api/v2/events')
        .set('Authorization', `Bearer ${token}`)
        .send({
          name: 'A Cool Talk',
          committeeName: 'Talks',
          startDate: '2017-07-12T05:00:00.000Z',
          endDate: '2017-06-12T10:00:00.000Z',
          location: 'The Lab',
        })
        .expect(422)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });

    it('Errors When Insufficient Fields Provided', function (done) {
      const expected = {
        error: 'notNull Violation: name cannot be null,\nnotNull Violation: startDate cannot be null,\nnotNull Violation: endDate cannot be null,\nnotNull Violation: location cannot be null',
      };

      request(app)
        .post('/api/v2/events')
        .set('Authorization', `Bearer ${token}`)
        .send({})
        .expect(422)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });
  });

  describe('GET /:id', function () {
    it('Gets a Specific Event', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Does Not Find a Non-existent Event', function (done) {
      expect(false).to.equal(true);
      done();
    });
  });

  describe('PUT /:id', function () {
    it('Requires Authentication', function (done) {
      const expected = {
        error: 'No authorization token was found',
      };

      request(app)
        .put('/api/v2/events/1')
        .expect(401)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });

    it('Requires Expected Permissions', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Updates a Specific Event', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Does Not Find and Update a Non-existent Event', function (done) {
      expect(false).to.equal(true);
      done();
    });
  });

  describe('DELETE /:id', function () {
    it('Requires Authentication', function (done) {
      const expected = {
        error: 'No authorization token was found',
      };

      request(app)
        .delete('/api/v2/events/1')
        .expect(401)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });

    it('Requires Expected Permissions', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Deletes a Specific Event', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Does Not Find and Delete a Non-existent Event', function (done) {
      expect(false).to.equal(true);
      done();
    });
  });
});
<commit_msg>Add More Events Tests<commit_after>/* eslint-env mocha */
/* eslint-disable func-names, prefer-arrow-callback  */

import { expect } from 'chai';
import request from 'supertest';

import app from '../../app';
import nconf from '../../config';
import {
  token,
  lowPermissionPrimaryToken,
  highPermissionOfficerToken,
  lowPermissionOfficerToken,
  highPermissionUserToken,
} from '../helpers';

describe('INTEGRATION TESTS: EVENTS', function () {
  describe('GET /', function () {
    it('Returns Events When Accepting JSON', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by an Existing Name', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by an Non-existent Name', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by an Existing Committee', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by an Non-existent Committee', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by an Existing Location', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by an Non-existent Location', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by Between', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by Before', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by After', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by Featured', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Filters by Sort', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Returns a Calendar Event When Accepting ICS', function (done) {
      expect(false).to.equal(true);
      done();
    });

    it('Does Not Accept Requests Not Accepting JSON or ICS', function (done) {
      expect(false).to.equal(true);
      done();
    });
  });

  describe('POST /', function () {
    it('Requires Authentication', function (done) {
      const expected = {
        error: 'No authorization token was found',
      };

      request(app)
        .post('/api/v2/events')
        .expect(401)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });

    it('Requires Expected Permissions', function (done) {
      // Need Low Permissions be an Officer or Primary Officer
      const expected = {
        error: 'User does not have permission: create events',
      };

      const eventInput = {
        name: 'A Cool Talk',
        committeeName: 'Talks',
        startDate: '2017-06-12T05:00:00.000Z',
        endDate: '2017-06-12T10:00:00.000Z',
        location: 'The Lab',
      };

      // Deny User w/ High Permission Token
      const userHigh = request(app)
        .post('/api/v2/events')
        .set('Authorization', `Bearer ${highPermissionUserToken}`)
        .expect(403)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
        });
      // Allow Primary Officer w/ Low Permission Token
      const primaryLow = request(app)
        .post('/api/v2/events')
        .set('Authorization', `Bearer ${lowPermissionPrimaryToken}`)
        .send(eventInput)
        .expect(201);
      // Allow Officer w/ Low Permission Token
      const officerLow = request(app)
        .post('/api/v2/events')
        .set('Authorization', `Bearer ${lowPermissionOfficerToken}`)
        .send(eventInput)
        .expect(201);

      Promise.all([
        userHigh,
        primaryLow,
        officerLow,
      ]).then(() => {
        done();
      });
    });

    it('Creates an Event', function (done) {
      const expected = {
        name: 'A Cool Talk',
        committeeName: 'Talks',
        startDate: '2017-06-12T05:00:00.000Z',
        endDate: '2017-06-12T10:00:00.000Z',
        location: 'The Lab',
      };

      request(app)
        .post('/api/v2/events')
        .set('Authorization', `Bearer ${token}`)
        .send(expected)
        .expect(201)
        .then((response) => {
          delete response.body.id;
          delete response.body.createdAt;
          delete response.body.updatedAt;
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });

    it('Requires Start Date to be Before End Date', function (done) {
      const expected = {
        error: 'Validation error: Start date must be before the end date',
      };

      request(app)
        .post('/api/v2/events')
        .set('Authorization', `Bearer ${token}`)
        .send({
          name: 'A Cool Talk',
          committeeName: 'Talks',
          startDate: '2017-07-12T05:00:00.000Z',
          endDate: '2017-06-12T10:00:00.000Z',
          location: 'The Lab',
        })
        .expect(422)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });

    it('Errors When Insufficient Fields Provided', function (done) {
      const expected = {
        error: 'notNull Violation: name cannot be null,\nnotNull Violation: startDate cannot be null,\nnotNull Violation: endDate cannot be null,\nnotNull Violation: location cannot be null',
      };

      request(app)
        .post('/api/v2/events')
        .set('Authorization', `Bearer ${token}`)
        .send({})
        .expect(422)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });
  });

  describe('GET /:id', function () {
    it('Gets a Specific Event', function (done) {
      const expected = {
        id: 1,
        name: 'Review Session',
        committeeName: 'Mentoring',
        startDate: '2017-10-12T05:00:00.000Z',
        endDate: '2017-10-12T05:00:00.000Z',
        location: 'GOL-1440',
        link: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
        image: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
        description: null,
      };

      request(app)
        .get('/api/v2/events/1')
        .set('Authorization', `Bearer ${token}`)
        .expect(200)
        .then((response) => {
          delete response.body.createdAt;
          delete response.body.updatedAt;
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });

    it('Does Not Find a Non-existent Event', function (done) {
      const expected = {
        error: 'Event not found',
      };

      request(app)
        .get('/api/v2/events/100')
        .set('Authorization', `Bearer ${token}`)
        .expect(404)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });
  });

  describe('PUT /:id', function () {
    it('Requires Authentication', function (done) {
      const expected = {
        error: 'No authorization token was found',
      };

      request(app)
        .put('/api/v2/events/1')
        .expect(401)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });

    it('Requires Expected Permissions', function (done) {
      // Need High Permissions be an Officer or Primary Officer
      const expected = {
        error: 'User does not have permission: update events',
      };

      const eventInput = {
        name: 'A Neat Talk',
      };

      // Deny Primary Officer w/ Low Permission Token
      const primaryLow = request(app)
        .put('/api/v2/events/2')
        .set('Authorization', `Bearer ${lowPermissionPrimaryToken}`)
        .expect(403)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
        });
      // Deny Officer w/ Low Permission Token
      const officerLow = request(app)
        .put('/api/v2/events/2')
        .set('Authorization', `Bearer ${lowPermissionOfficerToken}`)
        .expect(403)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
        });
      // Deny User w/ High Permission Token
      const userHigh = request(app)
        .put('/api/v2/events/2')
        .set('Authorization', `Bearer ${highPermissionUserToken}`)
        .expect(403)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
        });
      // Allow Primary Officer w/ High Permission Token
      const primaryHigh = request(app)
        .put('/api/v2/events/2')
        .set('Authorization', `Bearer ${token}`)
        .send(eventInput)
        .expect(200);
      // Allow Officer w/ High Permission Token
      const officerHigh = request(app)
        .put('/api/v2/events/2')
        .set('Authorization', `Bearer ${highPermissionOfficerToken}`)
        .send(eventInput)
        .expect(200);

      Promise.all([
        primaryLow,
        officerLow,
        userHigh,
        primaryHigh,
        officerHigh,
      ]).then(() => {
        done();
      });
    });

    it('Updates a Specific Event', function (done) {
      const expected = {
        id: 1,
        name: 'Lunch and Learn',
        committeeName: 'Mentoring',
        startDate: '2017-10-12T05:00:00.000Z',
        endDate: '2017-10-12T05:00:00.000Z',
        description: null,
        location: 'GOL-1440',
        link: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
        image: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
      };

      request(app)
        .put('/api/v2/events/1')
        .set('Authorization', `Bearer ${token}`)
        .send({
          name: 'Lunch and Learn',
        })
        .expect(200)
        .then((response) => {
          delete response.body.createdAt;
          delete response.body.updatedAt;
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });

    it('Does Not Find and Update a Non-existent Event', function (done) {
      const expected = {
        error: 'Event not found',
      };

      request(app)
        .put('/api/v2/events/100')
        .set('Authorization', `Bearer ${token}`)
        .expect(404)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });
  });

  describe('DELETE /:id', function () {
    it('Requires Authentication', function (done) {
      const expected = {
        error: 'No authorization token was found',
      };

      request(app)
        .delete('/api/v2/events/1')
        .expect(401)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });

    it('Requires Expected Permissions', function (done) {
      // Need High Permissions be an Officer or Primary Officer
      const expected = {
        error: 'User does not have permission: destroy events',
      };

      // Deny Primary Officer w/ Low Permission Token
      const primaryLow = request(app)
        .delete('/api/v2/events/2')
        .set('Authorization', `Bearer ${lowPermissionPrimaryToken}`)
        .expect(403)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
        });
      // Deny Officer w/ Low Permission Token
      const officerLow = request(app)
        .delete('/api/v2/events/2')
        .set('Authorization', `Bearer ${lowPermissionOfficerToken}`)
        .expect(403)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
        });
      // Deny User w/ High Permission Token
      const userHigh = request(app)
        .delete('/api/v2/events/2')
        .set('Authorization', `Bearer ${highPermissionUserToken}`)
        .expect(403)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
        });
      // Allow Primary Officer w/ High Permission Token
      const primaryHigh = request(app)
        .delete('/api/v2/events/2')
        .set('Authorization', `Bearer ${token}`)
        .expect(204);
      // Allow Officer w/ High Permission Token
      const officerHigh = request(app)
        .delete('/api/v2/events/2')
        .set('Authorization', `Bearer ${highPermissionOfficerToken}`)
        .expect(204);

      Promise.all([
        primaryLow,
        officerLow,
        userHigh,
        primaryHigh,
        officerHigh,
      ]).then(() => {
        done();
      });
    });

    it('Deletes a Specific Event', function (done) {
      request(app)
        .delete('/api/v2/events/1')
        .set('Authorization', `Bearer ${token}`)
        .expect(204)
        .then(() => {
          done();
        });
    });

    it('Does Not Find and Delete a Non-existent Event', function (done) {
      const expected = {
        error: 'Event not found',
      };

      request(app)
        .delete('/api/v2/events/100')
        .set('Authorization', `Bearer ${token}`)
        .expect(404)
        .then((response) => {
          expect(response.body).to.deep.equal(expected);
          done();
        });
    });
  });
});
<|endoftext|>


<commit_before>var path = require('path');

var gulp = require('gulp');
var jade = require('gulp-jade');
var swig = require('gulp-swig');
var less = require('gulp-less');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var copy = require('gulp-copy');
var uglify = require('gulp-uglify');
var useref = require('gulp-useref');
var filter = require('gulp-filter');
var rev = require('gulp-rev');
var revReplace = require('gulp-rev-replace');
var watch = require('gulp-watch');
var livereload = require('gulp-livereload');
var del = require('del');

var cfg = require('./config');

gulp.task('jade', function() {
    return gulp.src(cfg.src + '/' + cfg.views + '/**/*.jade')
        .pipe(jade())
        .pipe(gulp.dest('./dist/'))
})

gulp.task('swig', function() {
    return gulp.src(cfg.src + '/' + cfg.views + '/**/*.html')
        .pipe(swig())
        .pipe(gulp.dest('./dist/'))
})

gulp.task('js', function() {
    return gulp.src(cfg.src + '/' + cfg.scripts + '/**/*.js')
        .pipe(copy('./dist/js', { prefix: 2 }));
})

gulp.task('less', function() {
    return gulp.src(path.join(cfg.src, cfg.assets, cfg.less) + '/**/*.less')
        //.pipe(watch())
        .pipe(less())
        .pipe(gulp.dest('./dist/css'))
})

gulp.task('sass', function() {
    return gulp.src(path.join(cfg.src, cfg.assets, cfg.sass) + '/**/*')
        //.pipe(watch())
        .pipe(sass())
        .pipe(gulp.dest('./dist/css'))
})

// devide copy task(css, less, img...)
gulp.task('copy-assets', function() {
    gulp.src(cfg.src + '/' + cfg.assets + '/**/*')
        .pipe(copy('./dist', { prefix: 2 }))
})

gulp.task('ref', ['dist'], function() {
    var jsFilter = filter('**/*.js');
    var cssFilter = filter('**/*.css');

    var assets = useref.assets();
    gulp.src('./dist/**/*.html')
        .pipe(assets)
        .pipe(jsFilter)
        .pipe(uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe(minifyCss())
        .pipe(cssFilter.restore())
        .pipe(rev())
        .pipe(assets.restore())
        .pipe(useref())
        .pipe(revReplace())
        .pipe(gulp.dest('./dist/'))
})

gulp.task('server', function() {
    var app = require('./app');
    app.listen(process.env.PORT || cfg.port);
});

gulp.task('watch', function() {
    gulp.watch('src/assets/less/**/*.less', ['less']);

    gulp.watch('src/assets/sass/**/*', ['sass']);

    var server = livereload();
    server.changed();
    gulp.watch('src/**').on('change', function(file) {
        server.changed(file.path);
    });
})

gulp.task('clean', function(cb) {
    del([
        'dist/**'
    ], cb);
})

gulp.task('dist', [cfg.tplengine, 'copy-assets', 'jade', 'swig', 'js', 'less', 'sass'], function(done) {
    done()
});

gulp.task('build', ['ref'])

gulp.task('live', ['server', 'sass', 'less', 'watch'])

<commit_msg>chore(build): remove js, css files which have been combined<commit_after>var path = require('path');

var gulp = require('gulp');
var jade = require('gulp-jade');
var swig = require('gulp-swig');
var less = require('gulp-less');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var copy = require('gulp-copy');
var uglify = require('gulp-uglify');
var useref = require('gulp-useref');
var filter = require('gulp-filter');
var rev = require('gulp-rev');
var revReplace = require('gulp-rev-replace');
var watch = require('gulp-watch');
var livereload = require('gulp-livereload');
var del = require('del');

var cfg = require('./config');

gulp.task('jade', function() {
    return gulp.src(cfg.src + '/' + cfg.views + '/**/*.jade')
        .pipe(jade())
        .pipe(gulp.dest('./dist/'))
})

gulp.task('swig', function() {
    return gulp.src(cfg.src + '/' + cfg.views + '/**/*.html')
        .pipe(swig())
        .pipe(gulp.dest('./dist/'))
})

gulp.task('js', function() {
    return gulp.src(cfg.src + '/' + cfg.scripts + '/**/*.js')
        .pipe(copy('./dist/js', { prefix: 2 }));
})

gulp.task('less', function() {
    return gulp.src(path.join(cfg.src, cfg.assets, cfg.less) + '/**/*.less')
        //.pipe(watch())
        .pipe(less())
        .pipe(gulp.dest('./dist/css'))
})

gulp.task('sass', function() {
    return gulp.src(path.join(cfg.src, cfg.assets, cfg.sass) + '/**/*')
        //.pipe(watch())
        .pipe(sass())
        .pipe(gulp.dest('./dist/css'))
})

// devide copy task(css, less, img...)
gulp.task('copy-assets', function() {
    gulp.src(cfg.src + '/' + cfg.assets + '/**/*')
        .pipe(copy('./dist', { prefix: 2 }))
})

gulp.task('ref', ['dist'], function() {
    var jsFilter = filter('**/*.js');
    var cssFilter = filter('**/*.css');

    var assets = useref.assets();
    return gulp.src('./dist/**/*.html')
        .pipe(assets)
        .pipe(jsFilter)
        .pipe(uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe(minifyCss())
        .pipe(cssFilter.restore())
        .pipe(rev())
        .pipe(assets.restore())
        .pipe(useref())
        .pipe(revReplace())
        .pipe(gulp.dest('./dist/'))
})

gulp.task('server', function() {
    var app = require('./app');
    app.listen(process.env.PORT || cfg.port);
});

gulp.task('watch', function() {
    gulp.watch('src/assets/less/**/*.less', ['less']);

    gulp.watch('src/assets/sass/**/*', ['sass']);

    var server = livereload();
    server.changed();
    gulp.watch('src/**').on('change', function(file) {
        server.changed(file.path);
    });
})

gulp.task('clean', function(cb) {
    del([
        'dist/**'
    ], cb);
})

gulp.task('clean:js', ['ref'], function(cb) {
    del([ 'dist/js/**/*.js', '!dist/js/combined-*.js'], cb)
})

gulp.task('clean:css', ['ref'], function(cb) {
    del([ 'dist/css/**/*.css', '!dist/css/combined*'], cb)
})

gulp.task('dist', [cfg.tplengine, 'copy-assets', 'jade', 'swig', 'js', 'less', 'sass'], function(done) {
    done()
});

gulp.task('build', ['ref', 'clean:js', 'clean:css'])

gulp.task('live', ['server', 'sass', 'less', 'watch'])

<|endoftext|>


<commit_before>const { KafkaJSServerDoesNotSupportApiKey } = require('../../errors')
const { lookup } = require('./index')

const API_KEY_PRODUCE = 0
const API_KEY_FETCH = 1

describe('Protocol > Requests > lookup', () => {
  describe('when the client support more versions than the server', () => {
    it('returns the maximum version supported by the server', async () => {
      const apiKey = 1
      const protocol = jest.fn(() => true)

      // versions supported by the server
      const versions = { [apiKey]: { minVersion: 0, maxVersion: 1 } }

      // versions supported by the client
      const definition = { versions: [0, 1, 2], protocol }

      expect(lookup(versions)(apiKey, definition)).toEqual(true)
      expect(protocol).toHaveBeenCalledWith({ version: 1 })
    })
  })

  describe('when the server support more versions than the client', () => {
    it('returns the maximum version supported by the client', () => {
      const apiKey = 1
      const protocol = jest.fn(() => true)

      // versions supported by the server
      const versions = { [apiKey]: { minVersion: 1, maxVersion: 3 } }

      // versions supported by the client
      const definition = { versions: [0, 1, 2], protocol }

      expect(lookup(versions)(apiKey, definition)).toEqual(true)
      expect(protocol).toHaveBeenCalledWith({ version: 2 })
    })
  })

  describe('when the server does not support the requested version', () => {
    it('throws KafkaJSServerDoesNotSupportApiKey', () => {
      // versions supported by the server
      const versions = { 1: { minVersion: 1, maxVersion: 3 } }

      // versions supported by the client
      const protocol = jest.fn(() => true)
      const definition = { versions: [0, 1, 2], protocol }

      const apiKeyNotSupportedByTheServer = 34
      expect(() => lookup(versions)(apiKeyNotSupportedByTheServer, definition)).toThrow(
        KafkaJSServerDoesNotSupportApiKey
      )
    })
  })
})
<commit_msg>Remove unused variables<commit_after>const { KafkaJSServerDoesNotSupportApiKey } = require('../../errors')
const { lookup } = require('./index')

describe('Protocol > Requests > lookup', () => {
  describe('when the client support more versions than the server', () => {
    it('returns the maximum version supported by the server', async () => {
      const apiKey = 1
      const protocol = jest.fn(() => true)

      // versions supported by the server
      const versions = { [apiKey]: { minVersion: 0, maxVersion: 1 } }

      // versions supported by the client
      const definition = { versions: [0, 1, 2], protocol }

      expect(lookup(versions)(apiKey, definition)).toEqual(true)
      expect(protocol).toHaveBeenCalledWith({ version: 1 })
    })
  })

  describe('when the server support more versions than the client', () => {
    it('returns the maximum version supported by the client', () => {
      const apiKey = 1
      const protocol = jest.fn(() => true)

      // versions supported by the server
      const versions = { [apiKey]: { minVersion: 1, maxVersion: 3 } }

      // versions supported by the client
      const definition = { versions: [0, 1, 2], protocol }

      expect(lookup(versions)(apiKey, definition)).toEqual(true)
      expect(protocol).toHaveBeenCalledWith({ version: 2 })
    })
  })

  describe('when the server does not support the requested version', () => {
    it('throws KafkaJSServerDoesNotSupportApiKey', () => {
      // versions supported by the server
      const versions = { 1: { minVersion: 1, maxVersion: 3 } }

      // versions supported by the client
      const protocol = jest.fn(() => true)
      const definition = { versions: [0, 1, 2], protocol }

      const apiKeyNotSupportedByTheServer = 34
      expect(() => lookup(versions)(apiKeyNotSupportedByTheServer, definition)).toThrow(
        KafkaJSServerDoesNotSupportApiKey
      )
    })
  })
})
<|endoftext|>


<commit_before>var Promise = require('bluebird');
var blessed = require('blessed');
var _ = require('lazy.js');
var Point = require('text-buffer/lib/point');

var Slap = require('./Slap');

var util = require('../util');

function BaseWidget (opts) {
  var self = this;

  if (!(self instanceof blessed.Node)) return new BaseWidget(opts);

  opts = _(Slap.global.options.element).merge(opts || {}).toObject();
  if (!('slap' in opts)) opts.slap = Slap.global;
  if (!('parent' in opts)) opts.parent = opts.slap;
  if (self instanceof BaseWidget) blessed.Box.call(self, opts); // this should not be called if an element inherits from built-in blessed classes
  if (self.parent instanceof Pane) self.pane = self.parent;
  self.slap = opts.slap;
  self.focusable = opts.focusable;

  self.ready = Promise.delay(0)
    .then(function () { return self._initHandlers(); })
    .return(self);
}
BaseWidget.prototype.__proto__ = blessed.Box.prototype;

BaseWidget.prototype.walkDepthFirst = function (direction, after, fn) {
  if (arguments.length === 2) fn = after;
  var children = this.children.slice();
  if (direction === -1) children.reverse();
  if (after) children = children.slice(children.indexOf(after) + 1);
  return children.some(function (child) {
    return fn.apply(child, arguments) || BaseWidget.prototype.walkDepthFirst.call(child, direction, fn);
  });
};
BaseWidget.prototype.focusFirst = function (direction, after) {
  return this.walkDepthFirst(direction, after, function () {
    if (this.visible && this.focusable) {
      this.focus();
      return true;
    }
  });
};
BaseWidget.prototype._focusDirection = function (direction) {
  var self = this;
  var descendantParent;
  var descendant = self.screen.focused;
  while (descendant.hasAncestor(self)) {
    descendantParent = descendant.parent;
    if (BaseWidget.prototype.focusFirst.call(descendantParent, direction, descendant)) return self;
    descendant = descendantParent;
  }
  if (!self.focusFirst(direction)) throw new Error("no focusable descendant");
  return self;
};
BaseWidget.prototype.focusNext = function () {
  return this._focusDirection(1);
};
BaseWidget.prototype.focusPrev = function () {
  return this._focusDirection(-1);
};
BaseWidget.prototype.focus = function () {
  if (!this.hasFocus()) return blessed.Box.prototype.focus.apply(this, arguments);
  return this;
};
BaseWidget.prototype.isAttached = function () {
  return this.hasAncestor(this.screen);
};
BaseWidget.prototype.hasFocus = function (asChild) {
  var self = this;
  var focused = self.screen.focused;
  return focused.visible && (focused === self || focused.hasAncestor(self) || (asChild && self.hasAncestor(focused)));
};

BaseWidget.prototype.pos = function () {
  return new Point(this.atop + this.itop, this.aleft + this.ileft);
};
BaseWidget.prototype.size = function () {
  if (!this.isAttached()) return new Point(0, 0); // hack
  return new Point(this.height - this.iheight, this.width - this.iwidth);
};

BaseWidget.prototype.shrinkWidth = function () { return this.content.length + this.iwidth; };

BaseWidget.prototype._initHandlers = function () {
  var self = this;
  self.on('focus', function () {
    logger.debug('focus', util.typeOf(self));
    if (!self.focusable) self.focusNext();
  });
  self.on('blur', function () { logger.debug('blur', util.typeOf(self)); });
  self.on('show', function () { self.setFront(); });
  self.on('keypress', _.noop); // 'element keypress' doesn't work correctly without this
  self.on('element keypress', function (el, ch, key) {
    switch (util.getBinding(self.options.bindings, key)) {
      case 'hide': self.hide(); return false;
      case 'focusNext': self.focusNext(); return false;
      case 'focusPrev': self.focusPrev(); return false;
    }
  });
};

module.exports = BaseWidget;

var Pane = require('./Pane'); // circular import
<commit_msg>feat(init): should be self-contained now<commit_after>var Promise = require('bluebird');
var blessed = require('blessed');
var _ = require('lazy.js');
var Point = require('text-buffer/lib/point');

var util = require('slap-util');

function BaseWidget (opts) {
  var self = this;

  if (!(self instanceof blessed.Node)) return new BaseWidget(opts);

  opts = _(Slap.global.options.element).merge(opts || {}).toObject();
  if (!('screen' in opts)) opts.screen = blessed.Screen.global;
  if (!('parent' in opts)) opts.parent = opts.screen;
  if (self instanceof BaseWidget) blessed.Box.call(self, opts); // this should not be called if an element inherits from built-in blessed classes
  self.screen = opts.screen;
  self.focusable = opts.focusable;

  self.ready = Promise.delay(0)
    .then(function () { return self._initHandlers(); })
    .return(self);
}
BaseWidget.prototype.__proto__ = blessed.Box.prototype;

BaseWidget.prototype.walkDepthFirst = function (direction, after, fn) {
  if (arguments.length === 2) fn = after;
  var children = this.children.slice();
  if (direction === -1) children.reverse();
  if (after) children = children.slice(children.indexOf(after) + 1);
  return children.some(function (child) {
    return fn.apply(child, arguments) || BaseWidget.prototype.walkDepthFirst.call(child, direction, fn);
  });
};
BaseWidget.prototype.focusFirst = function (direction, after) {
  return this.walkDepthFirst(direction, after, function () {
    if (this.visible && this.focusable) {
      this.focus();
      return true;
    }
  });
};
BaseWidget.prototype._focusDirection = function (direction) {
  var self = this;
  var descendantParent;
  var descendant = self.screen.focused;
  while (descendant.hasAncestor(self)) {
    descendantParent = descendant.parent;
    if (BaseWidget.prototype.focusFirst.call(descendantParent, direction, descendant)) return self;
    descendant = descendantParent;
  }
  if (!self.focusFirst(direction)) throw new Error("no focusable descendant");
  return self;
};
BaseWidget.prototype.focusNext = function () {
  return this._focusDirection(1);
};
BaseWidget.prototype.focusPrev = function () {
  return this._focusDirection(-1);
};
BaseWidget.prototype.focus = function () {
  if (!this.hasFocus()) return blessed.Box.prototype.focus.apply(this, arguments);
  return this;
};
BaseWidget.prototype.isAttached = function () {
  return this.hasAncestor(this.screen);
};
BaseWidget.prototype.hasFocus = function (asChild) {
  var self = this;
  var focused = self.screen.focused;
  return focused.visible && (focused === self || focused.hasAncestor(self) || (asChild && self.hasAncestor(focused)));
};

BaseWidget.prototype.pos = function () {
  return new Point(this.atop + this.itop, this.aleft + this.ileft);
};
BaseWidget.prototype.size = function () {
  if (!this.isAttached()) return new Point(0, 0); // hack
  return new Point(this.height - this.iheight, this.width - this.iwidth);
};

BaseWidget.prototype.shrinkWidth = function () { return this.content.length + this.iwidth; };

BaseWidget.prototype._initHandlers = function () {
  var self = this;
  self.on('focus', function () {
    logger.debug('focus', util.typeOf(self));
    if (!self.focusable) self.focusNext();
  });
  self.on('blur', function () { logger.debug('blur', util.typeOf(self)); });
  self.on('show', function () { self.setFront(); });
  self.on('keypress', _.noop); // 'element keypress' doesn't work correctly without this
  self.on('element keypress', function (el, ch, key) {
    switch (util.getBinding(self.options.bindings, key)) {
      case 'hide': self.hide(); return false;
      case 'focusNext': self.focusNext(); return false;
      case 'focusPrev': self.focusPrev(); return false;
    }
  });
};

module.exports = BaseWidget;
<|endoftext|>


<commit_before>// Copyright (c) 2011, Centrum Cyfrowe
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of the Centrum Cyfrowe nor the names of its contributors
//     may be used to endorse or promote products derived from this software
//     without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var _tools = (function () {

//  P U B L I C   I N T E R F A C E
    var that = {};

    // TODO refactor this !!!!
    that.sort = function ( data, sett ) {
        var id = "idef";
        // TODO what is it for?!
        var new_table_data_object = {};
        _algorithms.prepare_sorting_setting( sett, id );
        _algorithms.sort( data, sett );
    };

    that.prepare_tools = function () {
        prepare_sorting_interface();
        prepare_filtering_interface();
        prepare_snapshot_interface();
    };

    that.get_full_parents = function ( id ) {
        var par_ids = [];

    };

    return that;

//  P R I V A T E   I N T E R F A C E

    function add_sort_key() {
        var i, key;
        var html = [];
        var schema = _store.basic_schema();
        var columns = schema
                        .filter( function ( e ) {
                            return e['processable'];
                        })
                        .map( function ( e ) {
                            return {
                                name: e['key'],
                                label: e['label']
                            };
                        });

        key = $('#sort-form > div').length;

        if( key === 2 ) {
            $('#add-sort-key' ).remove();
        }

        html.push( '
' );
        // columns select list
        html.push( '<select name="columns" class="key-', key, '">' );
        html.push( '<option value="null" class="key-', key, '" selected>' );
        html.push( 'Wybierz kolumnę</option>' );

        // TODO don't include already selected colmuns
        for( i = 0; i < columns.length; ++i ) {
            html.push( '<option value="', columns[i]['name'], '" class="key-', key, '">' );
            html.push( columns[i]['label'], '</option>' );
        }

        html.push( '</select>' );
        // ascending/descending radio buttons
        html.push( 'Rosnąco <input class="radio key-', key, '" type="radio" ' );
        html.push( 'name="key-', key, '-order" value="-1" checked />' );
        html.push( 'Malejąco <input class="radio key-', key, '" type="radio" ' );
        html.push( 'name="key-', key, '-order" value="1" />' );

        if( key === 0 ) {
            html.push( '
+
' );
            html.push( '<input type="submit" value="Sortuj" />' );
        }
        html.push( '
' );

        $('#sort-form').append( $( html.join('') ));

        if( key === 0 ) {
            $('#add-sort-key').click( function () {
                add_sort_key();
            });
        }
    }

    function add_filter_key() {
        var i, key;
        var html = [];
        var filter_part;
        var selected_column;
        var type;
        var schema = _store.basic_schema();
        var columns = schema
                        .filter( function ( e ) {
                            return e['processable'];
                        })
                        .map( function ( e ) {
                            return {
                                name: e['key'],
                                label: e['label']
                            };
                        });

        key = $('#filter-form > div').length;

        columns.unshift({
            name: 'null',
            label: 'Wybierz jedną z kolumn'
        });

        html.push( '<select id="filter-', key, '-columns"' );
        html.push( ' name="columns">');
        for ( i = 0; i < columns.length; i += 1 ) {
            html.push( '<option value="', columns[i]['key']);
            html.push( '" class="filter-', key, '" >"');
            html.push( columns[i]['label'], '</option>' );
        }
        html.push( '</select>' );

        html.push( '<select id="filter-', key, '-operations"' );
        html.push( ' name="null-operation">' );
        // not needed because column has not been selected yet

        html.push( '</select>' );

        html.push( '
' );

        if ( key === 0 ) {
            html.push( '
+
' );
            html.push( '<input type="submit" value="Filtruj" />' );
        }

        $('#filter-form').append( $( html.join('') ) );

        if( key === 0 ) {
            $('#add-filter-key').click( function () {
                add_filter_key();
            });
        }

        filter_part = $('filter-', key, '-columns');
        filter_part.change( function() {
            selected_column = $(this).val();
            // schema[0] is for empty column
            for ( i = 0; i < schema.length; i += 1 ) {
                if ( schema[i]['key'] === selected_column ) {
                    type = schema[i]['type'];
                    var filter_ops = $('#filter-', key, '-operations');
                    var filter_keys;

                    var new_select_type = type + '-operation';
                    filter_ops.attr('name', type);
                    if ( schema[i]['type'] === 'number' ) {
                        html = [ '<select>' ];
                        html.push( '<option value="null" class="filter-', key, '" selected>Wybierz operację</option>' );
                        html.push( '<option value="gt" class="filter-', key, '">></option>' );
                        html.push( '<option value="eq" class="filter-', key, '">=</option>' );
                        html.push( '<option value="lt" class="filter-', key, '"><</option>' );
                        html.push( '</select' );
                    } else {
                        html = [ '<select>' ];
                        html.push( '<option value="null" class="filter-', key, '" selected>Wybierz operację</option>' );
                        html.push( '<option value="cnt" class="filter-', key, '">></option>' );
                        html.push( '<option value="st" class="filter-', key, '">></option>' );
                        html.push( '<option value="ncnt" class="filter-', key, '">></option>' );
                        html.push( '<option value="nst" class="filter-', key, '">></option>' );
                        html.push( '</select>' );
                    }

                    html.push( '<input type="text" name="query" id="filter-', key, '-query" />' );
                }
            }
            //alert('Handler for .change() called.');
        });
    }

    /*for ( i = 0; i < schema.length; i += 1 ) {
            html.push( '<option value="', schema[i]['key']);
            html.push( '" class="filter-', m key, '" >"');
            html.push( schema[i]['label'], '</option>' );
        }*/
    // TODO don't include already selected colmuns
        /*for( i = 0; i < columns.length; ++i ) {
            html.push( '<option value="', columns[i]['name'], '" class="key-', key, '">' );
            html.push( columns[i]['label'], '</option>' );
        }*/

    function prepare_sorting_interface() {

        $('#sort-button')
            .click( function () {
                $('#filter-form').hide();
                $('#sort-form').html('').toggle();
                add_sort_key();
            });

        $('#sort-form')
            .submit( function () {

//                _utils.create_preloader('Sortowanie');

                var column, order;
                var settings = [];
                var i, len = $('#sort-form select').length;

                for( i = 0; i < len; i += 1 ) {
                    column = $( '.key-'+ i +' option:selected' ).val();
                    // TODO what does this condition mean?!
                    if( column === "null" ) {
                        if( i === 1 ) {
                            $(this).hide();
                            return false;
                        }
                        else {
                            break;
                        }
                    }
                    order = parseInt( $('.key-'+ i +':radio:checked').val() );

                    settings.push(
                        {
                            "pref": order,
                            "name": column
                        }
                    );
                }

                that.sort( _store.active_rows(), settings );

                _table.clean_table();
                _table.init_table();
                $(this).hide();

                // TODO why false?!
                return false;
            });

        var i;
        for( i = 1; i <= $('#sort-form select').length; ++i ) {
            if( i > 1 ) {
                $('#key-'+i).hide();
            }

            (function (i) {
                $('#sort-form select.key-'+i).change( function () {
                    if( $('.key-'+i+' option:selected').val() !== "null" ) {
                        $('#key-'+(i+1)).show();
                    }
                });
            })(i);
        }
    };

    function prepare_filtering_interface() {

        $('#filter-button')
            .click( function () {
                $('#filter-form').html('').toggle();
                $('#sort-form').hide();
                add_filter_key();
            });

        $('#filter-form')
            .submit( function () {

                var column, operation, query;
                var mask = [];
                var i, len = $('#filter-form select').length / 2;
                var tmp, type;
                var new_sheet;
                for( i = 1; i < len; ++i ) {
                    column = $('#filter-'+i+'-columns option:selected').val();
                    if( column === "null" ) {
                        if( i === 1 ) {
                            $(this).hide();
                            return false;
                        }
                        else {
                            break;
                        }
                    }

                    type = _store.active_columns().filter( function ( e ) {
                        return e['key'] === column;
                    })[0]['type'];

                    operation = $('#filter-'+i+'-operations option:selected').val();;
                    query = $('#filter-'+i+'-query').val();

                    tmp = parseInt( query, 10 );
                    // if the column if numeric - check if the query is so
                    if( type === 'number' ) {
                        // crazy way to check if tmp is a number!
                        if( !!tmp === true || tmp === 0 ) {
                            query = tmp;
                        }
                        else {
                            // characters for numeric column -- do nothing & quit
                            $(this).hide();
                            return false;
                        }
                    }

                    mask.push(
                        {
                           name: column,
                           pref: operation,
                           value: query
                        }
                    );
                }

                new_sheet = {};
                $.extend( true, new_sheet, _store.active_sheet() );
                new_sheet['rows'] = _algorithms.filter( new_sheet['rows'], mask );
                //new_sheet['filtered'] = true;

                _sheet.create_new_sheet( new_sheet, "Arkusz", true );

                _table.clean_table();
                _table.init_table( true );

                $(this).hide();

                return false;
           });
    };

    function prepare_snapshot_interface() {

        $('#save-snapshot')
            .click( function () {
                _sheet.create_new_sheet( _store.active_sheet(), "Arkusz" );
            });
    }

}) ();

<commit_msg>Bug fixes<commit_after>// Copyright (c) 2011, Centrum Cyfrowe
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of the Centrum Cyfrowe nor the names of its contributors
//     may be used to endorse or promote products derived from this software
//     without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var _tools = (function () {

//  P U B L I C   I N T E R F A C E
    var that = {};

    // TODO refactor this !!!!
    that.sort = function ( data, sett ) {
        var id = "idef";
        // TODO what is it for?!
        var new_table_data_object = {};
        _algorithms.prepare_sorting_setting( sett, id );
        _algorithms.sort( data, sett );
    };

    that.prepare_tools = function () {
        prepare_sorting_interface();
        prepare_filtering_interface();
        prepare_snapshot_interface();
    };

    that.get_full_parents = function ( id ) {
        var par_ids = [];

    };

    return that;

//  P R I V A T E   I N T E R F A C E

    function add_sort_key() {
        var i, key;
        var html = [];
        var schema = _store.basic_schema();
        var columns = schema
                        .filter( function ( e ) {
                            return e['processable'];
                        })
                        .map( function ( e ) {
                            return {
                                name: e['key'],
                                label: e['label']
                            };
                        });

        key = $('#sort-form > div').length;

        if( key === 2 ) {
            $('#add-sort-key' ).remove();
        }

        html.push( '
' );
        // columns select list
        html.push( '<select name="columns" class="key-', key, '">' );
        html.push( '<option value="null" class="key-', key, '" selected>' );
        html.push( 'Wybierz kolumnę</option>' );

        // TODO don't include already selected colmuns
        for( i = 0; i < columns.length; ++i ) {
            html.push( '<option value="', columns[i]['name'], '" class="key-', key, '">' );
            html.push( columns[i]['label'], '</option>' );
        }

        html.push( '</select>' );
        // ascending/descending radio buttons
        html.push( 'Rosnąco <input class="radio key-', key, '" type="radio" ' );
        html.push( 'name="key-', key, '-order" value="-1" checked />' );
        html.push( 'Malejąco <input class="radio key-', key, '" type="radio" ' );
        html.push( 'name="key-', key, '-order" value="1" />' );

        if( key === 0 ) {
            html.push( '
+
' );
            html.push( '<input type="submit" value="Sortuj" />' );
        }
        html.push( '
' );

        $('#sort-form').append( $( html.join('') ));

        if( key === 0 ) {
            $('#add-sort-key').click( function () {
                add_sort_key();
            });
        }
    }

    function add_filter_key() {
        var i, key;
        var html = [];
        var filter_part;
        var selected_column;
        var type;
        var schema = _store.basic_schema();
        var columns = schema
                        .filter( function ( e ) {
                            return e['processable'];
                        })
                        .map( function ( e ) {
                            return {
                                name: e['key'],
                                label: e['label']
                            };
                        });

        key = $('#filter-form > div').length;

        columns.unshift({
            name: 'null',
            label: 'Wybierz kolumnę'
        });

        html.push( '<select id="filter-', key, '-columns"' );
        html.push( ' name="columns">');
        for ( i = 0; i < columns.length; i += 1 ) {
            html.push( '<option value="', columns[i]['label']);
            html.push( '" class="filter-', key, '" >');
            html.push( columns[i]['label'], '</option>' );
        }
        html.push( '</select>' );

        html.push( '<select id="filter-', key, '-operations"' );
        html.push( ' name="null-operation">' );
        // not needed because column has not been selected yet

        html.push( '</select>' );

        html.push( '
' );

        if ( key === 0 ) {
            html.push( '
+
' );
            html.push( '<input type="submit" value="Filtruj" />' );
        }

        $('#filter-form').append( $( html.join('') ) );

        if( key === 0 ) {
            $('#add-filter-key').click( function () {
                add_filter_key();
            });
        }

        filter_part = $('filter-', key, '-columns');
        filter_part.change( function() {
            selected_column = $(this).val();
            // schema[0] is for empty column
            for ( i = 0; i < schema.length; i += 1 ) {
                if ( schema[i]['key'] === selected_column ) {
                    type = schema[i]['type'];
                    var filter_ops = $('#filter-', key, '-operations');
                    var filter_keys;

                    var new_select_type = type + '-operation';
                    filter_ops.attr('name', type);
                    if ( schema[i]['type'] === 'number' ) {
                        html = [ '<select>' ];
                        html.push( '<option value="null" class="filter-', key, '" selected>Wybierz operację</option>' );
                        html.push( '<option value="gt" class="filter-', key, '">></option>' );
                        html.push( '<option value="eq" class="filter-', key, '">=</option>' );
                        html.push( '<option value="lt" class="filter-', key, '"><</option>' );
                        html.push( '</select' );
                    } else {
                        html = [ '<select>' ];
                        html.push( '<option value="null" class="filter-', key, '" selected>Wybierz operację</option>' );
                        html.push( '<option value="cnt" class="filter-', key, '">></option>' );
                        html.push( '<option value="st" class="filter-', key, '">></option>' );
                        html.push( '<option value="ncnt" class="filter-', key, '">></option>' );
                        html.push( '<option value="nst" class="filter-', key, '">></option>' );
                        html.push( '</select>' );
                    }

                    html.push( '<input type="text" name="query" id="filter-', key, '-query" />' );
                }
            }
            //alert('Handler for .change() called.');
        });
    }

    /*for ( i = 0; i < schema.length; i += 1 ) {
            html.push( '<option value="', schema[i]['key']);
            html.push( '" class="filter-', m key, '" >"');
            html.push( schema[i]['label'], '</option>' );
        }*/
    // TODO don't include already selected colmuns
        /*for( i = 0; i < columns.length; ++i ) {
            html.push( '<option value="', columns[i]['name'], '" class="key-', key, '">' );
            html.push( columns[i]['label'], '</option>' );
        }*/

    function prepare_sorting_interface() {

        $('#sort-button')
            .click( function () {
                $('#filter-form').hide();
                $('#sort-form').html('').toggle();
                add_sort_key();
            });

        $('#sort-form')
            .submit( function () {

//                _utils.create_preloader('Sortowanie');

                var column, order;
                var settings = [];
                var i, len = $('#sort-form select').length;

                for( i = 0; i < len; i += 1 ) {
                    column = $( '.key-'+ i +' option:selected' ).val();
                    // TODO what does this condition mean?!
                    if( column === "null" ) {
                        if( i === 1 ) {
                            $(this).hide();
                            return false;
                        }
                        else {
                            break;
                        }
                    }
                    order = parseInt( $('.key-'+ i +':radio:checked').val() );

                    settings.push(
                        {
                            "pref": order,
                            "name": column
                        }
                    );
                }

                that.sort( _store.active_rows(), settings );

                _table.clean_table();
                _table.init_table();
                $(this).hide();

                // TODO why false?!
                return false;
            });

        var i;
        for( i = 1; i <= $('#sort-form select').length; ++i ) {
            if( i > 1 ) {
                $('#key-'+i).hide();
            }

            (function (i) {
                $('#sort-form select.key-'+i).change( function () {
                    if( $('.key-'+i+' option:selected').val() !== "null" ) {
                        $('#key-'+(i+1)).show();
                    }
                });
            })(i);
        }
    };

    function prepare_filtering_interface() {

        $('#filter-button')
            .click( function () {
                $('#filter-form').html('').toggle();
                $('#sort-form').hide();
                add_filter_key();
            });

        $('#filter-form')
            .submit( function () {

                var column, operation, query;
                var mask = [];
                var i, len = $('#filter-form select').length / 2;
                var tmp, type;
                var new_sheet;
                for( i = 1; i < len; ++i ) {
                    column = $('#filter-'+i+'-columns option:selected').val();
                    if( column === "null" ) {
                        if( i === 1 ) {
                            $(this).hide();
                            return false;
                        }
                        else {
                            break;
                        }
                    }

                    type = _store.active_columns().filter( function ( e ) {
                        return e['key'] === column;
                    })[0]['type'];

                    operation = $('#filter-'+i+'-operations option:selected').val();;
                    query = $('#filter-'+i+'-query').val();

                    tmp = parseInt( query, 10 );
                    // if the column if numeric - check if the query is so
                    if( type === 'number' ) {
                        // crazy way to check if tmp is a number!
                        if( !!tmp === true || tmp === 0 ) {
                            query = tmp;
                        }
                        else {
                            // characters for numeric column -- do nothing & quit
                            $(this).hide();
                            return false;
                        }
                    }

                    mask.push(
                        {
                           name: column,
                           pref: operation,
                           value: query
                        }
                    );
                }

                new_sheet = {};
                $.extend( true, new_sheet, _store.active_sheet() );
                new_sheet['rows'] = _algorithms.filter( new_sheet['rows'], mask );
                //new_sheet['filtered'] = true;

                _sheet.create_new_sheet( new_sheet, "Arkusz", true );

                _table.clean_table();
                _table.init_table( true );

                $(this).hide();

                return false;
           });
    };

    function prepare_snapshot_interface() {

        $('#save-snapshot')
            .click( function () {
                _sheet.create_new_sheet( _store.active_sheet(), "Arkusz" );
            });
    }

}) ();

<|endoftext|>


<commit_before>/**
 * 模块别名，模块名到具体的路径，模块名不能有重复
 * 使用thinkRequire记在模块时有效
 * @type {Object}
 */
module.exports = {
    Controller: THINK_LIB_PATH + "/Core/Controller.js",
    App: THINK_LIB_PATH + "/Core/App.js",
    Behavior: THINK_LIB_PATH + "/Core/Behavior.js",
    Cache: THINK_LIB_PATH + "/Core/Cache.js",
    Db: THINK_LIB_PATH + "/Core/Db.js",
    Dispatcher: THINK_LIB_PATH + "/Core/Dispatcher.js",
    Filter: THINK_LIB_PATH + "/Core/Filter.js",
    Http: THINK_LIB_PATH + "/Core/Http.js",
    Log: THINK_LIB_PATH + "/Core/Log.js",
    Model: THINK_LIB_PATH + "/Core/Model.js",
    Session: THINK_LIB_PATH + "/Core/Session.js",
    Think: THINK_LIB_PATH + "/Core/Think.js",
    Valid: THINK_LIB_PATH + "/Core/Valid.js",
    View: THINK_LIB_PATH + "/Core/View.js",
}<commit_msg>update<commit_after>/**
 * 模块别名，模块名到具体的路径，模块名不能有重复
 * 使用thinkRequire加载模块时有效
 * @type {Object}
 */
module.exports = {
    Controller: THINK_LIB_PATH + "/Core/Controller.js",
    App: THINK_LIB_PATH + "/Core/App.js",
    Behavior: THINK_LIB_PATH + "/Core/Behavior.js",
    Cache: THINK_LIB_PATH + "/Core/Cache.js",
    Db: THINK_LIB_PATH + "/Core/Db.js",
    Dispatcher: THINK_LIB_PATH + "/Core/Dispatcher.js",
    Filter: THINK_LIB_PATH + "/Core/Filter.js",
    Http: THINK_LIB_PATH + "/Core/Http.js",
    Log: THINK_LIB_PATH + "/Core/Log.js",
    Model: THINK_LIB_PATH + "/Core/Model.js",
    Session: THINK_LIB_PATH + "/Core/Session.js",
    Think: THINK_LIB_PATH + "/Core/Think.js",
    Valid: THINK_LIB_PATH + "/Core/Valid.js",
    View: THINK_LIB_PATH + "/Core/View.js",
}<|endoftext|>