<commit_before>var HOST = 'localhost';
var PORT = 1337;

var request = require('request');
var url = require('url');

var express = require('express');
var app = express();

var Twig = require('twig');
app.set('views', __dirname);
app.set('view engine', 'twig');

var router = require('../lib/index.js');
router(app, {
    host: HOST,
    port: PORT,
    baseDir: __dirname,
    file: './routing/main_routing.json'
});

/**
 * @func
 * @param {string} path
 * @returns {string} Absolute URI to path
 */
function getAbsoluteURL(path) {
    return url.format({
        protocol: 'http',
        hostname: HOST,
        port: PORT,
        pathname: (path || '')
    });
}

var counter = (function () {
    var count = 0;

    return function () {
        return count++;
    };
}())

describe('Response from', function () {
    // Start server before each test
    beforeEach(function () {
        this.server = app.listen(PORT, function () {
            this._id = counter();
            console.log('[' + this._id + '] expressjs server listening on port ' + PORT + '.');
        });
    });

    // Stop server after each test
    afterEach(function (done) {
        this.server.close(function () {
            console.log('[' + this._id + '] expressjs server on port ' + PORT + ' was stopped!');
            done();
        });
    });

    describe('non-existing URL', function () {
        it('returns status code 404', function (done) {
            request.get(getAbsoluteURL('/non-existent-page/'), function (error, response) {
                expect(response.statusCode).toBe(404);
                done();
            });
        });
    });

    describe('route without requirement attribute "defaults._controller"', function () {
        it('returns status code 500', function (done) {
            request.get(getAbsoluteURL('/route-without-controller/'), function (error, response) {
                expect(response.statusCode).toBe(500);
                done();
            });
        });

        it('returns error message', function (done) {
            request.get(getAbsoluteURL('/route-without-controller/'), function (error, response, body) {
                expect(body).toMatch(/Could not load controller "" for route "route_without_controller"./i);
                done();
            });
        });
    });

    describe('simple route with requirement attributes only', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/route-simple/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/route-simple/'), function (error, response, body) {
                expect(JSON.parse(body)).toEqual({
                    data: {}
                });
                done();
            });
        });
    });

    describe('route for HTML but without template', function () {
        it('returns status code 500', function (done) {
            request.get(getAbsoluteURL('/route-for-html-without-template/'), function (error, response) {
                expect(response.statusCode).toBe(500);
                done();
            });
        });

        it('returns error message', function (done) {
            request.get(getAbsoluteURL('/route-for-html-without-template/'), function (error, response, body) {
                expect(body).toMatch(/Template for route "route_for_html_without_template" is not defined./i);
                done();
            });
        });
    });

    describe('route with template', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/route-with-template-without-format/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Hello, World!"', function (done) {
            request.get(getAbsoluteURL('/route-with-template-without-format/'), function (error, response, body) {
                expect(body).toBe('Hello, World!');
                done();
            });
        });
    });

    describe('route for JSON with template', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/route-with-template-for-json/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/route-with-template-for-json/'), function (error, response) {
                expect(response.headers['content-type']).toMatch('application/json');
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/route-with-template-for-json/'), function (error, response, body) {
                // expect(JSON.parse(body)).toEqual({
                //     data: {}
                // });
                done();
            });
        });
    });

    describe('route with param', function () {
        it('returns status code 404 for not matched "val3"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val3/'), function (error, response) {
                expect(response.statusCode).toBe(404);
                done();
            });
        });

        it('returns status code 200 for matched "val1"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val1/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Parameter from URL is \'val1\'"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val1/'), function (error, response, body) {
                expect(body).toBe('Parameter from URL is \'val1\'');
                done();
            });
        });

        it('returns status code 200 for matched "val2"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val2/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Parameter from URL is \'val2\'"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val2/'), function (error, response, body) {
                expect(body).toBe('Parameter from URL is \'val2\'');
                done();
            });
        });
    });

    describe('route Only POST method is allowed', function () {
        it('returns status code 405 for GET', function (done) {
            request.get(getAbsoluteURL('/only-post-method-allowing/'), function (error, response) {
                expect(response.statusCode).toBe(405);
                done();
            });
        });

        it('returns status code 200 for POST', function (done) {
            request.get(getAbsoluteURL('/only-post-method-allowing/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });
    });

    // Routes from external_routing.json
    describe('simple external route with requirement attributes only', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/external-route-simple/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/external-route-simple/'), function (error, response, body) {
                expect(JSON.parse(body)).toEqual({
                    data: {}
                });
                done();
            });
        });
    });

    describe('external route with param', function () {
        it('returns status code 200 for matched "val1"', function (done) {
            request.get(getAbsoluteURL('/external-route-with-param/val1/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Parameter from URL is \'val1\'"', function (done) {
            request.get(getAbsoluteURL('/external-route-with-param/val1/'), function (error, response, body) {
                expect(body).toBe('Parameter from URL is \'val1\'');
                done();
            });
        });
    });
});
<commit_msg>jsDocs for tests were update<commit_after>var HOST = 'localhost';
var PORT = 1337;

var request = require('request');
var url = require('url');

var express = require('express');
var app = express();

var Twig = require('twig');
app.set('views', __dirname);
app.set('view engine', 'twig');

var router = require('../lib/index.js');
router(app, {
    host: HOST,
    port: PORT,
    baseDir: __dirname,
    file: './routing/main_routing.json'
});

/**
 * @func
 * @param {string} path
 * @returns {string} Absolute URI to path
 */
function getAbsoluteURL(path) {
    return url.format({
        protocol: 'http',
        hostname: HOST,
        port: PORT,
        pathname: (path || '')
    });
}

/**
 * @returns {function}
 */
var counter = (function () {
    var count = 0;

    return function () {
        return count++;
    };
}())

describe('Response from', function () {
    beforeEach(function () {
        // Start server before each test
        this.server = app.listen(PORT, function () {
            this._id = counter();
            console.log('\n[' + this._id + '] expressjs server listening on port ' + PORT + '.');
        });
    });

    afterEach(function (done) {
        // Stop server after each test
        this.server.close(function () {
            console.log('[' + this._id + '] expressjs server on port ' + PORT + ' was stopped!');
            done();
        });
    });

    describe('non-existing URL', function () {
        it('returns status code 404', function (done) {
            request.get(getAbsoluteURL('/non-existent-page/'), function (error, response) {
                expect(response.statusCode).toBe(404);
                done();
            });
        });
    });

    describe('route without requirement attribute "defaults._controller"', function () {
        it('returns status code 500', function (done) {
            request.get(getAbsoluteURL('/route-without-controller/'), function (error, response) {
                expect(response.statusCode).toBe(500);
                done();
            });
        });

        it('returns error message', function (done) {
            request.get(getAbsoluteURL('/route-without-controller/'), function (error, response, body) {
                expect(body).toMatch(/Could not load controller "" for route "route_without_controller"./i);
                done();
            });
        });
    });

    describe('simple route with requirement attributes only', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/route-simple/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/route-simple/'), function (error, response, body) {
                expect(JSON.parse(body)).toEqual({
                    data: {}
                });
                done();
            });
        });
    });

    describe('route for HTML but without template', function () {
        it('returns status code 500', function (done) {
            request.get(getAbsoluteURL('/route-for-html-without-template/'), function (error, response) {
                expect(response.statusCode).toBe(500);
                done();
            });
        });

        it('returns error message', function (done) {
            request.get(getAbsoluteURL('/route-for-html-without-template/'), function (error, response, body) {
                expect(body).toMatch(/Template for route "route_for_html_without_template" is not defined./i);
                done();
            });
        });
    });

    describe('route with template', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/route-with-template-without-format/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Hello, World!"', function (done) {
            request.get(getAbsoluteURL('/route-with-template-without-format/'), function (error, response, body) {
                expect(body).toBe('Hello, World!');
                done();
            });
        });
    });

    describe('route for JSON with template', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/route-with-template-for-json/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/route-with-template-for-json/'), function (error, response) {
                expect(response.headers['content-type']).toMatch('application/json');
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/route-with-template-for-json/'), function (error, response, body) {
                // expect(JSON.parse(body)).toEqual({
                //     data: {}
                // });
                done();
            });
        });
    });

    describe('route with param', function () {
        it('returns status code 404 for not matched "val3"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val3/'), function (error, response) {
                expect(response.statusCode).toBe(404);
                done();
            });
        });

        it('returns status code 200 for matched "val1"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val1/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Parameter from URL is \'val1\'"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val1/'), function (error, response, body) {
                expect(body).toBe('Parameter from URL is \'val1\'');
                done();
            });
        });

        it('returns status code 200 for matched "val2"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val2/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Parameter from URL is \'val2\'"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val2/'), function (error, response, body) {
                expect(body).toBe('Parameter from URL is \'val2\'');
                done();
            });
        });
    });

    describe('route Only POST method is allowed', function () {
        it('returns status code 405 for GET', function (done) {
            request.get(getAbsoluteURL('/only-post-method-allowing/'), function (error, response) {
                expect(response.statusCode).toBe(405);
                done();
            });
        });

        it('returns status code 200 for POST', function (done) {
            request.get(getAbsoluteURL('/only-post-method-allowing/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });
    });

    // Routes from external_routing.json
    describe('simple external route with requirement attributes only', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/external-route-simple/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/external-route-simple/'), function (error, response, body) {
                expect(JSON.parse(body)).toEqual({
                    data: {}
                });
                done();
            });
        });
    });

    describe('external route with param', function () {
        it('returns status code 200 for matched "val1"', function (done) {
            request.get(getAbsoluteURL('/external-route-with-param/val1/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Parameter from URL is \'val1\'"', function (done) {
            request.get(getAbsoluteURL('/external-route-with-param/val1/'), function (error, response, body) {
                expect(body).toBe('Parameter from URL is \'val1\'');
                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>var Page = require('sitepage').Page
var Color = require('csscolor').Color
var ConfSite = require('../../../_models/classes/ConfSite.class.js')

/**
 * A set of static members used for the Conf style guide.
 * Similar to a utility class.
 * @type {ConfDocs}
 */
module.exports = (function () {
  // CONSTRUCTOR
  function ConfDocs() {}

  // METHODS

  // STATIC MEMBERS
  /**
   * The style guide site for this project.
   * @type {StyleGuide}
   */
  ConfDocs.DOCS = (function () {
    var docs = new Page({ name: 'ASCE Conferences Style Guide', url: '/docs/' })
    .title('ASCE Conferences Style Guide')
    .description('Pattern Library for conference microsites.')
    ;(function (self) {
      self
        .add(new Page({ name: self.name(), url: 'index.html' })
          .description(self.description())
        )
        .add(new Page({ name: 'Visual Design', url: 'visual.html' })
          .description('Color and font schemes, look-and-feel, overall voice and tone.')
          .add(new Page({ name: 'Fonts' , url: 'visual.html#fonts' }))
          .add(new Page({ name: 'Colors', url: 'visual.html#colors' })
            .add(new Page({ name: 'Derivation of Color Palettes', url: 'visual.html#derivation-color-palettes' }))
            .add(new Page({ name: 'Site Colors', url: 'visual.html#site-colors' }))
          )
        )
        .add(new Page({ name: 'Base Typography', url: 'base.html' })
          .description('Bare, unstyled HTML elements. No classes.')
          .add(new Page({ name: 'Grouping Elements', url: 'base.html#grouping-elements' })
            .add(new Page({ name: 'Headings & Paragraphs', url: 'base.html#headings-paragraphs' }))
            .add(new Page({ name: 'Lists'                , url: 'base.html#lists' }))
            .add(new Page({ name: 'Tables'               , url: 'base.html#tables' }))
          )
          .add(new Page({ name: 'Text-Level Elements', url: 'base.html#text-level-elements' })
            .add(new Page({ name: 'Links'        , url: 'base.html#links' }))
            .add(new Page({ name: 'Stress'       , url: 'base.html#stress' }))
            .add(new Page({ name: 'Documentation', url: 'base.html#documentation' }))
            .add(new Page({ name: 'Data'         , url: 'base.html#data' }))
          )
          .add(new Page({ name: 'Forms'               , url: 'base.html#forms' }))
          .add(new Page({ name: 'Embedded Elements'   , url: 'base.html#embedded-elements' }))
          .add(new Page({ name: 'Interactive Elements', url: 'base.html#interactive-elements' }))
        )
        .add(new Page({ name: 'Objects', url: 'obj.html' })
          .description('Patterns of structure that can be reused many times for many different purposes.')
          .add(new Page({ name: 'The Float Grid'   , url: 'obj.html#float-grid' }))
          .add(new Page({ name: 'The Runner Object', url: 'obj.html#runner-object' }))
          .add(new Page({ name: 'Constrain'        , url: 'obj.html#constrain' }))
          .add(new Page({ name: 'The Action List'  , url: 'obj.html#action-list' }))
          .add(new Page({ name: 'The Stacked List' , url: 'obj.html#stacked-list' }))
          .add(new Page({ name: 'The Drawer Object', url: 'obj.html#drawer-object' }))
        )
        .add(new Page({ name: 'Components', url: 'comp.html' })
          .description('Patterns of look-and-feel that are each only used for one purpose.')
          .add(new Page({ name: 'The Mast Component'   , url: 'comp.html#mast-component' }))
          .add(new Page({ name: 'The Banner Component' , url: 'comp.html#banner-component' }))
          .add(new Page({ name: 'The Site Title'       , url: 'comp.html#site-title' }))
          .add(new Page({ name: 'The Mobile Menu'      , url: 'comp.html#mobile-menu' }))
          .add(new Page({ name: 'The Menu Bar'         , url: 'comp.html#menu-bar' }))
          .add(new Page({ name: 'The Sitemap Component', url: 'comp.html#sitemap-component' }))
          .add(new Page({ name: 'The Page Title'       , url: 'comp.html#page-title' }))
          .add(new Page({ name: 'The Conference Header', url: 'comp.html#conference-header' }))
          .add(new Page({ name: 'The Supporter Block'  , url: 'comp.html#supporter-block' }))
          .add(new Page({ name: 'The Date Block'       , url: 'comp.html#date-block' }))
          .add(new Page({ name: 'The Pass Component'   , url: 'comp.html#pass-component' }))
          .add(new Page({ name: 'The Program Component', url: 'comp.html#program-component' }))
          .add(new Page({ name: 'The Time Block'       , url: 'comp.html#time-block' }))
          .add(new Page({ name: 'The Speaker Component', url: 'comp.html#speaker-component' }))
          .add(new Page({ name: 'The Social List'      , url: 'comp.html#social-list' }))
          .add(new Page({ name: 'The Callout Component', url: 'comp.html#callout-component' }))
          .add(new Page({ name: 'Buttons'              , url: 'comp.html#buttons' }))
          .add(new Page({ name: 'The Toggle Button'    , url: 'comp.html#toggle-button' }))
          .add(new Page({ name: 'The Camo Link'        , url: 'comp.html#camo-link' }))
          .add(new Page({ name: 'The Caps Link'        , url: 'comp.html#caps-link' }))
        )
        .add(new Page({ name: 'Aggregates', url: 'agg.html' })
          .description('Compositions of Objects and Components that act as a single organism.')
          .add(new Page({ name: 'Site Header', url: 'agg.html#site-header' }))
          .add(new Page({ name: 'Page Header', url: 'agg.html#page-header' }))
          .add(new Page({ name: 'Highlighted Content Block', url: 'agg.html#highlighted-content-block' }))
          .add(new Page({ name: 'Hero Image', url: 'agg.html#hero-image' }))
          .add(new Page({ name: 'Other Year Callout', url: 'agg.html#other-year-callout' }))
          .add(new Page({ name: 'The Program Carousel', url: 'agg.html#program-carousel' }))
          .add(new Page({ name: 'Speaker', url: 'agg.html#speaker' }))
          .add(new Page({ name: 'Important Dates', url: 'agg.html#important-dates' }))
          .add(new Page({ name: 'Person', url: 'agg.html#person' }))
          .add(new Page({ name: 'Place', url: 'agg.html#place' }))
        )
        .add(new Page({ name: 'Helpers', url: 'help.html' })
          .description('Somewhat explicit classes used for enhancing default styles.')
        )
        .add(new Page({ name: 'Atoms', url: 'atom.html' })
          .description('Very specific classes used for creating anomalies or fixing broken styles.')
        )
    })(docs)
    return docs
  })()

  ConfDocs.COLORS = ConfSite.colorStyles(Color.fromString('#660000'), Color.fromString('#ff6600'))

  ConfDocs.COLOR_NAMES = [
    { name: 'Primary s2'   , suffix: '-primary-shade2' }
  , { name: 'Primary s1'   , suffix: '-primary-shade1' }
  , { name: 'Primary'      , suffix: '-primary' }
  , { name: 'Primary t1'   , suffix: '-primary-tint1' }
  , { name: 'Primary t2'   , suffix: '-primary-tint2' }
  , { name: 'Secondary s2' , suffix: '-secondary-shade2' }
  , { name: 'Secondary s1' , suffix: '-secondary-shade1' }
  , { name: 'Secondary'    , suffix: '-secondary' }
  , { name: 'Secondary t1' , suffix: '-secondary-tint1' }
  , { name: 'Secondary t2' , suffix: '-secondary-tint2' }
  , { name: 'Dark Gray s2' , suffix: '-gray_dk-shade2' }
  , { name: 'Dark Gray s1' , suffix: '-gray_dk-shade1' }
  , { name: 'Dark Gray'    , suffix: '-gray_dk' }
  , { name: 'Dark Gray t1' , suffix: '-gray_dk-tint1' }
  , { name: 'Dark Gray t2' , suffix: '-gray_dk-tint2' }
  , { name: 'Light Gray s2', suffix: '-gray_lt-shade2' }
  , { name: 'Light Gray s1', suffix: '-gray_lt-shade1' }
  , { name: 'Light Gray'   , suffix: '-gray_lt' }
  , { name: 'Light Gray t1', suffix: '-gray_lt-tint1' }
  , { name: 'Light Gray t2', suffix: '-gray_lt-tint2' }
  ]

  return ConfDocs
})()
<commit_msg>simplify docs object<commit_after>var Page = require('sitepage').Page
var Color = require('csscolor').Color
var ConfSite = require('../../../_models/classes/ConfSite.class.js')

/**
 * A set of static members used for the Conf style guide.
 * Similar to a utility class.
 * @type {ConfDocs}
 */
module.exports = (function () {
  // CONSTRUCTOR
  function ConfDocs() {}

  // METHODS

  // STATIC MEMBERS
  /**
   * The style guide site for this project.
   * @type {Page}
   */
  ConfDocs.DOCS = (function () {
    var docs = new Page({ name: 'ASCE Conferences Style Guide', url: '/docs/' })
      .title('ASCE Conferences Style Guide')
      .description('Pattern Library for conference microsites.')
    docs
      .add(new Page({ name: docs.name(), url: 'index.html' }).description(docs.description()))
      .add(new Page({ name: 'Visual Design', url: 'visual.html' })
        .description('Color and font schemes, look-and-feel, overall voice and tone.')
        .add(new Page({ name: 'Fonts' , url: 'visual.html#fonts' }))
        .add(new Page({ name: 'Colors', url: 'visual.html#colors' })
          .add(new Page({ name: 'Derivation of Color Palettes', url: 'visual.html#derivation-color-palettes' }))
          .add(new Page({ name: 'Site Colors', url: 'visual.html#site-colors' }))
        )
      )
      .add(new Page({ name: 'Base Typography', url: 'base.html' })
        .description('Bare, unstyled HTML elements. No classes.')
        .add(new Page({ name: 'Grouping Elements', url: 'base.html#grouping-elements' })
          .add(new Page({ name: 'Headings & Paragraphs', url: 'base.html#headings-paragraphs' }))
          .add(new Page({ name: 'Lists'                , url: 'base.html#lists' }))
          .add(new Page({ name: 'Tables'               , url: 'base.html#tables' }))
        )
        .add(new Page({ name: 'Text-Level Elements', url: 'base.html#text-level-elements' })
          .add(new Page({ name: 'Links'        , url: 'base.html#links' }))
          .add(new Page({ name: 'Stress'       , url: 'base.html#stress' }))
          .add(new Page({ name: 'Documentation', url: 'base.html#documentation' }))
          .add(new Page({ name: 'Data'         , url: 'base.html#data' }))
        )
        .add(new Page({ name: 'Forms'               , url: 'base.html#forms' }))
        .add(new Page({ name: 'Embedded Elements'   , url: 'base.html#embedded-elements' }))
        .add(new Page({ name: 'Interactive Elements', url: 'base.html#interactive-elements' }))
      )
      .add(new Page({ name: 'Objects', url: 'obj.html' })
        .description('Patterns of structure that can be reused many times for many different purposes.')
        .add(new Page({ name: 'The Float Grid'   , url: 'obj.html#float-grid' }))
        .add(new Page({ name: 'The Runner Object', url: 'obj.html#runner-object' }))
        .add(new Page({ name: 'Constrain'        , url: 'obj.html#constrain' }))
        .add(new Page({ name: 'The Action List'  , url: 'obj.html#action-list' }))
        .add(new Page({ name: 'The Stacked List' , url: 'obj.html#stacked-list' }))
        .add(new Page({ name: 'The Drawer Object', url: 'obj.html#drawer-object' }))
      )
      .add(new Page({ name: 'Components', url: 'comp.html' })
        .description('Patterns of look-and-feel that are each only used for one purpose.')
        .add(new Page({ name: 'The Mast Component'   , url: 'comp.html#mast-component' }))
        .add(new Page({ name: 'The Banner Component' , url: 'comp.html#banner-component' }))
        .add(new Page({ name: 'The Site Title'       , url: 'comp.html#site-title' }))
        .add(new Page({ name: 'The Mobile Menu'      , url: 'comp.html#mobile-menu' }))
        .add(new Page({ name: 'The Menu Bar'         , url: 'comp.html#menu-bar' }))
        .add(new Page({ name: 'The Sitemap Component', url: 'comp.html#sitemap-component' }))
        .add(new Page({ name: 'The Page Title'       , url: 'comp.html#page-title' }))
        .add(new Page({ name: 'The Conference Header', url: 'comp.html#conference-header' }))
        .add(new Page({ name: 'The Supporter Block'  , url: 'comp.html#supporter-block' }))
        .add(new Page({ name: 'The Date Block'       , url: 'comp.html#date-block' }))
        .add(new Page({ name: 'The Pass Component'   , url: 'comp.html#pass-component' }))
        .add(new Page({ name: 'The Program Component', url: 'comp.html#program-component' }))
        .add(new Page({ name: 'The Time Block'       , url: 'comp.html#time-block' }))
        .add(new Page({ name: 'The Speaker Component', url: 'comp.html#speaker-component' }))
        .add(new Page({ name: 'The Social List'      , url: 'comp.html#social-list' }))
        .add(new Page({ name: 'The Callout Component', url: 'comp.html#callout-component' }))
        .add(new Page({ name: 'Buttons'              , url: 'comp.html#buttons' }))
        .add(new Page({ name: 'The Toggle Button'    , url: 'comp.html#toggle-button' }))
        .add(new Page({ name: 'The Camo Link'        , url: 'comp.html#camo-link' }))
        .add(new Page({ name: 'The Caps Link'        , url: 'comp.html#caps-link' }))
      )
      .add(new Page({ name: 'Aggregates', url: 'agg.html' })
        .description('Compositions of Objects and Components that act as a single organism.')
        .add(new Page({ name: 'Site Header', url: 'agg.html#site-header' }))
        .add(new Page({ name: 'Page Header', url: 'agg.html#page-header' }))
        .add(new Page({ name: 'Highlighted Content Block', url: 'agg.html#highlighted-content-block' }))
        .add(new Page({ name: 'Hero Image', url: 'agg.html#hero-image' }))
        .add(new Page({ name: 'Other Year Callout', url: 'agg.html#other-year-callout' }))
        .add(new Page({ name: 'The Program Carousel', url: 'agg.html#program-carousel' }))
        .add(new Page({ name: 'Speaker', url: 'agg.html#speaker' }))
        .add(new Page({ name: 'Important Dates', url: 'agg.html#important-dates' }))
        .add(new Page({ name: 'Person', url: 'agg.html#person' }))
        .add(new Page({ name: 'Place', url: 'agg.html#place' }))
      )
      .add(new Page({ name: 'Helpers', url: 'help.html' })
        .description('Somewhat explicit classes used for enhancing default styles.')
      )
      .add(new Page({ name: 'Atoms', url: 'atom.html' })
        .description('Very specific classes used for creating anomalies or fixing broken styles.')
      )
    return docs
  })()

  ConfDocs.COLORS = ConfSite.colorStyles(Color.fromString('#660000'), Color.fromString('#ff6600'))

  ConfDocs.COLOR_NAMES = [
    { name: 'Primary s2'   , suffix: '-primary-shade2' }
  , { name: 'Primary s1'   , suffix: '-primary-shade1' }
  , { name: 'Primary'      , suffix: '-primary' }
  , { name: 'Primary t1'   , suffix: '-primary-tint1' }
  , { name: 'Primary t2'   , suffix: '-primary-tint2' }
  , { name: 'Secondary s2' , suffix: '-secondary-shade2' }
  , { name: 'Secondary s1' , suffix: '-secondary-shade1' }
  , { name: 'Secondary'    , suffix: '-secondary' }
  , { name: 'Secondary t1' , suffix: '-secondary-tint1' }
  , { name: 'Secondary t2' , suffix: '-secondary-tint2' }
  , { name: 'Dark Gray s2' , suffix: '-gray_dk-shade2' }
  , { name: 'Dark Gray s1' , suffix: '-gray_dk-shade1' }
  , { name: 'Dark Gray'    , suffix: '-gray_dk' }
  , { name: 'Dark Gray t1' , suffix: '-gray_dk-tint1' }
  , { name: 'Dark Gray t2' , suffix: '-gray_dk-tint2' }
  , { name: 'Light Gray s2', suffix: '-gray_lt-shade2' }
  , { name: 'Light Gray s1', suffix: '-gray_lt-shade1' }
  , { name: 'Light Gray'   , suffix: '-gray_lt' }
  , { name: 'Light Gray t1', suffix: '-gray_lt-tint1' }
  , { name: 'Light Gray t2', suffix: '-gray_lt-tint2' }
  ]

  return ConfDocs
})()
<|endoftext|>


<commit_before>define(function() {
    describe('Minionette.Region', function() {
        var RegionView = Minionette.View.extend({
            template: _.template('
test
<%= view("region") %>
test
')
        });
        function addInnerView(name, parentView) {
            var v = new Minionette.View({tagName: 'p'});
            v.template = _.template("test");
            v.render();
            parentView.addRegion(name, v);
            parentView.render();
            return v;
        }
        beforeEach(function() {
            this.view = new RegionView();
            this.region = new Minionette.Region({view: this.view});
        });

        describe("#_configure()", function() {
            it("picks view out of initialization options", function() {
                expect(this.region.view).to.equal(this.view);
            });
        });

        describe("#_ensureView()", function() {
            it("sets #view to a #_view if one is not passed in", function() {
                var region = new Minionette.Region();

                expect(region.view).to.equal(region._view);
            });

            it("sets #view to #_view if passed in view isn't an instanceof Backbone.View", function() {
                var region = new Minionette.Region({view: 'view?'});

                expect(region.view).to.equal(region._view);
            });
        });

        describe("#render()", function() {
            it("calls #view#render()", function() {
                var spy = this.sinon.spy(this.view, 'render');

                this.region.render();

                expect(this.spy).to.have.been.called;
            });

            it("returns #view#render()", function() {
                var expected = _.uniqueId();
                this.view.render = function() {
                    return expected;
                };

                var ret = this.region.render();

                expect(ret).to.equal(expected);
            });
        });

        describe("#attach()", function() {
            beforeEach(function() {
                this.newView = new Minionette.View();
            });

            it("replaces current view#el with newView#el (the same index in parent)", function() {
                var v = addInnerView('region', this.view),
                    expectedIndex = v.$el.index();

                this.view.region.attach(this.newView);

                expect(this.newView.$el.index()).to.equal(expectedIndex);
            });

            it("calls #view#remove()", function() {
                var spy = this.sinon.spy(this.view, 'remove');

                this.region.attach(this.newView);

                expect(spy).to.have.been.called;
            });

            it("sets #view to newView", function() {
                this.region.attach(this.newView);

                expect(this.region.view).to.equal(this.newView);
            });

            it("returns newView", function() {
                var ret = this.region.attach(this.newView);

                expect(ret).to.equal(this.newView);
            });
        });

        describe("#detach()", function() {
            it("sets #_detachedView to the old #view", function() {
                var oldView = this.region.view;

                this.region.detach();

                expect(this.region._detachedView).to.equal(oldView);
            });

            it("sets #view to #_view", function() {
                this.region.detach();

                expect(this.region.view).to.equal(this.region._view);
            });

            it("replaces current view#el with _view#el (the same index in parent)", function() {
                var v = addInnerView('region', this.view),
                    expectedIndex = v.$el.index();

                this.view.region.detach();

                expect(this.view.region._view.$el.index()).to.equal(expectedIndex);
            });

            it("calls #view#$el#detach()", function() {
                var spy = this.sinon.spy();
                this.view.on('click', spy);

                this.region.detach();
                this.view.trigger('click');

                expect(spy).to.have.been.called;
            });

            it("returns this for chaining", function() {
                var ret = this.region.detach();

                expect(ret).to.equal(this.region);
            });
        });

        describe("#reattach()", function() {
            beforeEach(function() {
                this.region.detach();
            });

            it("scopes #reattach() to _parent", function() {
                this.view.remove(); // Make sure view isn't in the document.body
                var v = addInnerView('region', this.view);
                this.view.region.detach();

                var expectedIndex = this.view.region.view.$el.index();

                this.view.region.reattach();

                expect(v.$el.index()).to.equal(expectedIndex);
            });

            it("replaces view#el with _detachedView#el", function() {
                var v = addInnerView('region', this.view);
                this.view.region.detach();

                var expectedIndex = this.view.region.view.$el.index();

                this.view.region.reattach();

                expect(v.$el.index()).to.equal(expectedIndex);
            });

            it("deletes #_detachedView so it can't be re#attach()ed", function() {
                this.region.reattach();

                expect(this.region._detachedView).to.not.exist;
            });
        });

        describe("#remove()", function() {
            it("calls #view#remove()", function() {
                var spy = this.sinon.spy(this.view, 'remove');

                this.region.remove();

                expect(spy).to.have.been.called;
            });

            it("replaces view#el with _view#el", function() {
                var v = addInnerView('region', this.view),
                    expectedIndex = v.$el.index();

                this.view.region.remove();

                expect(this.view.region._view.$el.index()).to.equal(expectedIndex);
            });

            it("returns removedView", function() {
                var removedView = this.region.remove();

                expect(removedView).to.equal(this.view);
            });
        });

        describe("#reset()", function() {
            it("replaces view#el with _view#el", function() {
                var v = addInnerView('region', this.view),
                    expectedIndex = v.$el.index();

                this.view.region.reset();

                expect(this.view.region._view.$el.index()).to.equal(expectedIndex);
            });

            it("doesn't call #remove on old #view", function() {
                var spy = this.sinon.spy(this.view, 'remove');

                this.region.reset();

                expect(spy).to.not.have.been.called;
            });
        });

        describe("#_removeView()", function() {
            it("sets #view to #_view", function() {
                this.region._removeView(this.view);

                expect(this.region.view).to.equal(this.region._view);
            });

            it("replaces view#el with _view#el", function() {
                var v = addInnerView('region', this.view),
                    expectedIndex = v.$el.index();

                this.view.region.reset();

                expect(this.view.region._view.$el.index()).to.equal(expectedIndex);
            });

            it("doesn't call #remove on old #view", function() {
                var spy = this.sinon.spy(this.view, 'remove');

                this.region._removeView(this.view);

                expect(spy).to.not.have.been.called;
            });

            it("only resets if #view equals passed in view", function() {
                var v = new Minionette.View();

                this.region._removeView(v);

                expect(this.region.view).to.equal(this.view);
            });
        });
    });
});
<commit_msg>Fix incorrect test<commit_after>define(function() {
    describe('Minionette.Region', function() {
        var RegionView = Minionette.View.extend({
            template: _.template('
test
<%= view("region") %>
test
')
        });
        function addInnerView(name, parentView) {
            var v = new Minionette.View({tagName: 'p'});
            v.template = _.template("test");
            v.render();
            parentView.addRegion(name, v);
            parentView.render();
            return v;
        }
        beforeEach(function() {
            this.view = new RegionView();
            this.region = new Minionette.Region({view: this.view});
        });

        describe("#_configure()", function() {
            it("picks view out of initialization options", function() {
                expect(this.region.view).to.equal(this.view);
            });
        });

        describe("#_ensureView()", function() {
            it("sets #view to a #_view if one is not passed in", function() {
                var region = new Minionette.Region();

                expect(region.view).to.equal(region._view);
            });

            it("sets #view to #_view if passed in view isn't an instanceof Backbone.View", function() {
                var region = new Minionette.Region({view: 'view?'});

                expect(region.view).to.equal(region._view);
            });
        });

        describe("#render()", function() {
            it("calls #view#render()", function() {
                var spy = this.sinon.spy(this.view, 'render');

                this.region.render();

                expect(spy).to.have.been.called;
            });

            it("returns #view#render()", function() {
                var expected = _.uniqueId();
                this.view.render = function() {
                    return expected;
                };

                var ret = this.region.render();

                expect(ret).to.equal(expected);
            });
        });

        describe("#attach()", function() {
            beforeEach(function() {
                this.newView = new Minionette.View();
            });

            it("replaces current view#el with newView#el (the same index in parent)", function() {
                var v = addInnerView('region', this.view),
                    expectedIndex = v.$el.index();

                this.view.region.attach(this.newView);

                expect(this.newView.$el.index()).to.equal(expectedIndex);
            });

            it("calls #view#remove()", function() {
                var spy = this.sinon.spy(this.view, 'remove');

                this.region.attach(this.newView);

                expect(spy).to.have.been.called;
            });

            it("sets #view to newView", function() {
                this.region.attach(this.newView);

                expect(this.region.view).to.equal(this.newView);
            });

            it("returns newView", function() {
                var ret = this.region.attach(this.newView);

                expect(ret).to.equal(this.newView);
            });
        });

        describe("#detach()", function() {
            it("sets #_detachedView to the old #view", function() {
                var oldView = this.region.view;

                this.region.detach();

                expect(this.region._detachedView).to.equal(oldView);
            });

            it("sets #view to #_view", function() {
                this.region.detach();

                expect(this.region.view).to.equal(this.region._view);
            });

            it("replaces current view#el with _view#el (the same index in parent)", function() {
                var v = addInnerView('region', this.view),
                    expectedIndex = v.$el.index();

                this.view.region.detach();

                expect(this.view.region._view.$el.index()).to.equal(expectedIndex);
            });

            it("calls #view#$el#detach()", function() {
                var spy = this.sinon.spy();
                this.view.on('click', spy);

                this.region.detach();
                this.view.trigger('click');

                expect(spy).to.have.been.called;
            });

            it("returns this for chaining", function() {
                var ret = this.region.detach();

                expect(ret).to.equal(this.region);
            });
        });

        describe("#reattach()", function() {
            beforeEach(function() {
                this.region.detach();
            });

            it("scopes #reattach() to _parent", function() {
                this.view.remove(); // Make sure view isn't in the document.body
                var v = addInnerView('region', this.view);
                this.view.region.detach();

                var expectedIndex = this.view.region.view.$el.index();

                this.view.region.reattach();

                expect(v.$el.index()).to.equal(expectedIndex);
            });

            it("replaces view#el with _detachedView#el", function() {
                var v = addInnerView('region', this.view);
                this.view.region.detach();

                var expectedIndex = this.view.region.view.$el.index();

                this.view.region.reattach();

                expect(v.$el.index()).to.equal(expectedIndex);
            });

            it("deletes #_detachedView so it can't be re#attach()ed", function() {
                this.region.reattach();

                expect(this.region._detachedView).to.not.exist;
            });
        });

        describe("#remove()", function() {
            it("calls #view#remove()", function() {
                var spy = this.sinon.spy(this.view, 'remove');

                this.region.remove();

                expect(spy).to.have.been.called;
            });

            it("replaces view#el with _view#el", function() {
                var v = addInnerView('region', this.view),
                    expectedIndex = v.$el.index();

                this.view.region.remove();

                expect(this.view.region._view.$el.index()).to.equal(expectedIndex);
            });

            it("returns removedView", function() {
                var removedView = this.region.remove();

                expect(removedView).to.equal(this.view);
            });
        });

        describe("#reset()", function() {
            it("replaces view#el with _view#el", function() {
                var v = addInnerView('region', this.view),
                    expectedIndex = v.$el.index();

                this.view.region.reset();

                expect(this.view.region._view.$el.index()).to.equal(expectedIndex);
            });

            it("doesn't call #remove on old #view", function() {
                var spy = this.sinon.spy(this.view, 'remove');

                this.region.reset();

                expect(spy).to.not.have.been.called;
            });
        });

        describe("#_removeView()", function() {
            it("sets #view to #_view", function() {
                this.region._removeView(this.view);

                expect(this.region.view).to.equal(this.region._view);
            });

            it("replaces view#el with _view#el", function() {
                var v = addInnerView('region', this.view),
                    expectedIndex = v.$el.index();

                this.view.region.reset();

                expect(this.view.region._view.$el.index()).to.equal(expectedIndex);
            });

            it("doesn't call #remove on old #view", function() {
                var spy = this.sinon.spy(this.view, 'remove');

                this.region._removeView(this.view);

                expect(spy).to.not.have.been.called;
            });

            it("only resets if #view equals passed in view", function() {
                var v = new Minionette.View();

                this.region._removeView(v);

                expect(this.region.view).to.equal(this.view);
            });
        });
    });
});
<|endoftext|>


<commit_before>define(["sprd/data/SprdModel", "sprd/model/BasketItem", "js/data/Collection", "sprd/model/Currency", "js/data/Entity", "sprd/entity/Price", "sprd/model/DiscountScale", "sprd/model/Language"], function (SprdModel, BasketItem, Collection, Currency, Entity, Price, DiscountScale, Language) {

    var Discount = Entity.inherit('sprd.entity.BasketDiscount', {
        schema: {
            discountScale: DiscountScale
        }
    });

    return SprdModel.inherit("sprd.model.Basket", {

        schema: {
            basketItems: Collection.of(BasketItem),
            priceItems: Price,
            priceTotal: Price,
            shop: "sprd/model/Shop",
            currency: Currency,
            language: Language,
            discounts: [Discount]
        },

        ctor: function () {
            this.callBase();

            this.bind('basketItems', 'change', this._triggerFunctions, this);
            this.bind('basketItems', 'add', this._triggerFunctions, this);
            this.bind('basketItems', 'remove', this._triggerFunctions, this);
        },

        addElement: function (element, quantity) {
            quantity = quantity || 1;

            var basketItem = this.getBasketItemForElement(element);
            if (basketItem) {
                basketItem.increaseQuantity(quantity);
            } else {
                basketItem = this.$.basketItems.createItem();
                basketItem.set({
                    element: element,
                    quantity: quantity
                });
                this.$.basketItems.add(basketItem);
            }

            return basketItem;
        },

        mergeBasketItem: function (basketItem) {
            var old, nItem;
            nItem = this.$.basketItems.find(function (item) {
                return (!nItem && item.$.element !== basketItem.$.element && item.$.element.isEqual(basketItem.$.element));
            });

            if (nItem) {
                this.$.basketItems.each(function (item) {
                    if (!old && item.$.element === basketItem.$.element) {
                        old = item;
                    }
                });
                nItem.increaseQuantity(old.$.quantity);
                this.$.basketItems.remove(old);
            }
        },

        getBasketItemForElement: function (element) {
            var basketItems = this.getCollection('basketItems');
            for (var i = 0; i < basketItems.$items.length; i++) {
                var basketItem = basketItems.$items[i];
                if (basketItem.$.element.isEqual(element)) {
                    return basketItem;
                }
            }
            return null;
        },

        _triggerFunctions: function () {
            this.trigger('change', {});
        },

        totalItemsCount: function () {
            var total = 0;
            if (this.$.basketItems) {
                this.$.basketItems.each(function (item) {
                    total += item.$.quantity;
                });
            }
            return total;
        }.on('change'),

        vatIncluded: function () {
            var total = 0;
            if (this.$.basketItems) {
                this.$.basketItems.each(function (item) {
                    total += item.totalVatIncluded();
                });
            }
            return total;
        }.on('change'),

        orderValue: function () {
            var total = 0;
            if (this.$.basketItems) {
                this.$.basketItems.each(function (item) {
                    total += item.orderValue();
                });
            }
            return total;
        }.on('change'),

        totalVat: function () {
            var total = 0;
            total = (this.vatIncluded() - this.vatExcluded());

            return total;
        }.on('change'),

        vatExcluded: function () {
            var total = 0;
            if (this.$.basketItems) {
                this.$.basketItems.each(function (item) {
                    total += item.totalVatExcluded();
                });
            }
            return total;
        }.on('change'),

        discountVatIncluded: function () {
            if (this.$.discounts && this.$.discounts.size()) {
                return this.$.discounts.at(0).get('price.vatIncluded');
            }

            return 0;
        }.onChange("discounts"),

        totalVatIncluded: function () {
            if (this.$.priceTotal) {
                return this.$.priceTotal.$.vatIncluded;
            }
            return null;
        }.onChange('priceTotal'),

        totalPriceItemsVatIncluded: function () {
            if (this.$.priceItems) {
                return this.$.priceItems.$.vatIncluded - this.discountVatIncluded();
            }
            return null;
        }.onChange('priceItems', 'discounts'),

        platformCheckoutLink: function () {
            if (this.$.links) {
                return this.$.links[2].href;
            }
            return null;
        }.onChange('links'),

        shopCheckoutLink: function () {
            if (this.$.links) {
                return this.$.links[1].href;
            }
            return null;
        }.onChange('links')

    });
});
<commit_msg>DEV-71368 - Displayed VAT is wrong in MiniBasket * correct vat is now used<commit_after>define(["sprd/data/SprdModel", "sprd/model/BasketItem", "js/data/Collection", "sprd/model/Currency", "js/data/Entity", "sprd/entity/Price", "sprd/model/DiscountScale", "sprd/model/Language"], function (SprdModel, BasketItem, Collection, Currency, Entity, Price, DiscountScale, Language) {

    var Discount = Entity.inherit('sprd.entity.BasketDiscount', {
        schema: {
            discountScale: DiscountScale
        }
    });

    return SprdModel.inherit("sprd.model.Basket", {

        schema: {
            basketItems: Collection.of(BasketItem),
            priceItems: Price,
            priceTotal: Price,
            shop: "sprd/model/Shop",
            currency: Currency,
            language: Language,
            discounts: [Discount]
        },

        ctor: function () {
            this.callBase();

            this.bind('basketItems', 'change', this._triggerFunctions, this);
            this.bind('basketItems', 'add', this._triggerFunctions, this);
            this.bind('basketItems', 'remove', this._triggerFunctions, this);
        },

        addElement: function (element, quantity) {
            quantity = quantity || 1;

            var basketItem = this.getBasketItemForElement(element);
            if (basketItem) {
                basketItem.increaseQuantity(quantity);
            } else {
                basketItem = this.$.basketItems.createItem();
                basketItem.set({
                    element: element,
                    quantity: quantity
                });
                this.$.basketItems.add(basketItem);
            }

            return basketItem;
        },

        mergeBasketItem: function (basketItem) {
            var old, nItem;
            nItem = this.$.basketItems.find(function (item) {
                return (!nItem && item.$.element !== basketItem.$.element && item.$.element.isEqual(basketItem.$.element));
            });

            if (nItem) {
                this.$.basketItems.each(function (item) {
                    if (!old && item.$.element === basketItem.$.element) {
                        old = item;
                    }
                });
                nItem.increaseQuantity(old.$.quantity);
                this.$.basketItems.remove(old);
            }
        },

        getBasketItemForElement: function (element) {
            var basketItems = this.getCollection('basketItems');
            for (var i = 0; i < basketItems.$items.length; i++) {
                var basketItem = basketItems.$items[i];
                if (basketItem.$.element.isEqual(element)) {
                    return basketItem;
                }
            }
            return null;
        },

        _triggerFunctions: function () {
            this.trigger('change', {});
        },

        totalItemsCount: function () {
            var total = 0;
            if (this.$.basketItems) {
                this.$.basketItems.each(function (item) {
                    total += item.$.quantity;
                });
            }
            return total;
        }.on('change'),

        vatIncluded: function () {
            var total = 0;
            if (this.$.basketItems) {
                this.$.basketItems.each(function (item) {
                    total += item.totalVatIncluded();
                });
            }
            return total;
        }.on('change'),

        orderValue: function () {
            var total = 0;
            if (this.$.basketItems) {
                this.$.basketItems.each(function (item) {
                    total += item.orderValue();
                });
            }
            return total;
        }.on('change'),

        totalVat: function () {
            var total = 0;
            total = (this.totalVatIncluded() - this.totalVatExcluded());

            return total;
        }.on('change'),

        vatExcluded: function () {
            var total = 0;
            if (this.$.basketItems) {
                this.$.basketItems.each(function (item) {
                    total += item.totalVatExcluded();
                });
            }
            return total;
        }.on('change'),

        discountVatIncluded: function () {
            if (this.$.discounts && this.$.discounts.size()) {
                return this.$.discounts.at(0).get('price.vatIncluded');
            }

            return 0;
        }.onChange("discounts"),

        totalVatIncluded: function () {
            if (this.$.priceTotal) {
                return this.$.priceTotal.$.vatIncluded;
            }
            return null;
        }.onChange('priceTotal'),

        totalVatExcluded: function () {
            if (this.$.priceTotal) {
                return this.$.priceTotal.$.vatExcluded;
            }
            return null;
        }.onChange('priceTotal'),

        totalPriceItemsVatIncluded: function () {
            if (this.$.priceItems) {
                return this.$.priceItems.$.vatIncluded - this.discountVatIncluded();
            }
            return null;
        }.onChange('priceItems', 'discounts'),

        platformCheckoutLink: function () {
            if (this.$.links) {
                return this.$.links[2].href;
            }
            return null;
        }.onChange('links'),

        shopCheckoutLink: function () {
            if (this.$.links) {
                return this.$.links[1].href;
            }
            return null;
        }.onChange('links')

    });
});
<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var produceMineField = function(s) {
    return s === '*' ? '*' : '0';
};

describe('mine field', function() {
    it('works for a single mine', function() {
	assert.equal('*', produceMineField('*'));
    });

    it('works for an empty field', function() {
	assert.equal('0', produceMineField('.'));
    });
});
<commit_msg>fail for bigger mines<commit_after>"use strict";

var assert = require('assert');

var produceMineField = function(s) {
    return s === '*' ? '*' : '0';
};

describe('mine field', function() {
    it('works for a single mine', function() {
	assert.equal('*', produceMineField('*'));
    });

    it('works for an empty field', function() {
	assert.equal('0', produceMineField('.'));
    });

    it('works for a 2x2 empty field', function() {
	assert.equal('00\n00\n', produceMineField('..\n..'));
    });
});
<|endoftext|>


<commit_before>import domvm from '../node_modules/domvm/dist/nano/domvm.nano.min.js';

import {Store} from './store.es6';

var startTime;
var lastMeasure;
var startMeasure = function(name) {
	startTime = performance.now();
	lastMeasure = name;
}
var stopMeasure = function() {
	var last = lastMeasure;
	if (lastMeasure) {
		window.setTimeout(function () {
			lastMeasure = null;
			var stop = performance.now();
			var duration = 0;
			console.log(last+" took "+(stop-startTime));
		}, 0);
	}
}

var h  = (tag, arg1, arg2) => domvm.defineElement(tag, arg1, arg2, domvm.FIXED_BODY);

let store = new Store();

let vm = domvm.createView(View, store).mount(document.body);

function View(vm, store) {
	let wrapMeasure = name => e => {
		startMeasure(name);
		store[name]();
		vm.redraw(true);
		stopMeasure(name);
	};

	let run			= wrapMeasure("run");
	let runLots		= wrapMeasure("runLots");
	let add			= wrapMeasure("add");
	let update		= wrapMeasure("update");
	let clear		= wrapMeasure("clear");
	let swapRows	= wrapMeasure("swapRows");

	let select = (e, node) => {
		startMeasure("select");
		while (node.data == null)
			node = node.parent;
		store.select(node.data);
		vm.redraw(true);		// sync redraw
		stopMeasure("select");
		return false;
	};

	let remove = (e, node) => {
		startMeasure("delete");
		while (node.data == null)
			node = node.parent;
		store.delete(node.data);
		vm.redraw(true);
		stopMeasure("delete");
		return false;
	};

	// delegated handler
	let tableClick = {
		".remove, .remove *": remove,
		".lbl": select,
	};

	return _ =>
	h("#main", [
		h(".container", [
			h(".jumbotron", [
				h(".row", [
					h(".col-md-6", [
						h("h1", "domvm v2.0.3 (non-keyed)")
					]),
					h(".col-md-6", [
						h(".row", [
							h(".col-sm-6.smallpad", [
								h("button.btn.btn-primary.btn-block#run", {type: "button", onclick: run}, "Create 1,000 rows")
							]),
							h(".col-sm-6.smallpad", [
								h("button.btn.btn-primary.btn-block#runlots", {type: "button", onclick: runLots}, "Create 10,000 rows")
							]),
							h(".col-sm-6.smallpad", [
								h("button.btn.btn-primary.btn-block#add", {type: "button", onclick: add}, "Append 1,000 rows")
							]),
							h(".col-sm-6.smallpad", [
								h("button.btn.btn-primary.btn-block#update", {type: "button", onclick: update}, "Update every 10th row")
							]),
							h(".col-sm-6.smallpad", [
								h("button.btn.btn-primary.btn-block#clear", {type: "button", onclick: clear}, "Clear")
							]),
							h(".col-sm-6.smallpad", [
								h("button.btn.btn-primary.btn-block#swaprows", {type: "button", onclick: swapRows}, "Swap Rows")
							])
						])
					])
				])
			]),
			h("table.table.table-hover.table-striped.test-data", {onclick: tableClick}, [
				h("tbody", store.data.map(item =>
					h("tr", {_data: item.id, class: item.id === store.selected ? 'danger' : null}, [
						h("td.col-md-1", item.id),
						h("td.col-md-4", [
							h("a.lbl", item.label)
						]),
						h("td.col-md-1", [
							h("a.remove", [
								h("span.glyphicon.glyphicon-remove", {"aria-hidden": ""})
							])
						]),
						h("td.col-md-6")
					])
				))
			]),
			h("span.preloadicon.glyphicon.glyphicon-remove", {"aria-hidden": ""})
		])
	])
}<commit_msg>fix domvm non-keyed impl bustage<commit_after>import domvm from '../node_modules/domvm/dist/nano/domvm.nano.min.js';

import {Store} from './store.es6';

var startTime;
var lastMeasure;
var startMeasure = function(name) {
	startTime = performance.now();
	lastMeasure = name;
}
var stopMeasure = function() {
	var last = lastMeasure;
	if (lastMeasure) {
		window.setTimeout(function () {
			lastMeasure = null;
			var stop = performance.now();
			var duration = 0;
			console.log(last+" took "+(stop-startTime));
		}, 0);
	}
}

var el = domvm.defineElement;
var h = (tag, arg1, arg2) => el(tag, arg1, arg2, domvm.FIXED_BODY);

let store = new Store();

let vm = domvm.createView(View, store).mount(document.body);

function View(vm, store) {
	let wrapMeasure = name => e => {
		startMeasure(name);
		store[name]();
		vm.redraw(true);
		stopMeasure(name);
	};

	let run			= wrapMeasure("run");
	let runLots		= wrapMeasure("runLots");
	let add			= wrapMeasure("add");
	let update		= wrapMeasure("update");
	let clear		= wrapMeasure("clear");
	let swapRows	= wrapMeasure("swapRows");

	let select = (e, node) => {
		startMeasure("select");
		while (node.data == null)
			node = node.parent;
		store.select(node.data);
		vm.redraw(true);		// sync redraw
		stopMeasure("select");
		return false;
	};

	let remove = (e, node) => {
		startMeasure("delete");
		while (node.data == null)
			node = node.parent;
		store.delete(node.data);
		vm.redraw(true);
		stopMeasure("delete");
		return false;
	};

	// delegated handler
	let tableClick = {
		".remove, .remove *": remove,
		".lbl": select,
	};

	return _ =>
	h("#main", [
		h(".container", [
			h(".jumbotron", [
				h(".row", [
					h(".col-md-6", [
						h("h1", "domvm v2.0.3 (non-keyed)")
					]),
					h(".col-md-6", [
						h(".row", [
							h(".col-sm-6.smallpad", [
								h("button.btn.btn-primary.btn-block#run", {type: "button", onclick: run}, "Create 1,000 rows")
							]),
							h(".col-sm-6.smallpad", [
								h("button.btn.btn-primary.btn-block#runlots", {type: "button", onclick: runLots}, "Create 10,000 rows")
							]),
							h(".col-sm-6.smallpad", [
								h("button.btn.btn-primary.btn-block#add", {type: "button", onclick: add}, "Append 1,000 rows")
							]),
							h(".col-sm-6.smallpad", [
								h("button.btn.btn-primary.btn-block#update", {type: "button", onclick: update}, "Update every 10th row")
							]),
							h(".col-sm-6.smallpad", [
								h("button.btn.btn-primary.btn-block#clear", {type: "button", onclick: clear}, "Clear")
							]),
							h(".col-sm-6.smallpad", [
								h("button.btn.btn-primary.btn-block#swaprows", {type: "button", onclick: swapRows}, "Swap Rows")
							])
						])
					])
				])
			]),
			h("table.table.table-hover.table-striped.test-data", {onclick: tableClick}, [
				el("tbody", store.data.map(item =>
					h("tr", {_data: item.id, class: item.id === store.selected ? 'danger' : null}, [
						h("td.col-md-1", item.id),
						h("td.col-md-4", [
							h("a.lbl", item.label)
						]),
						h("td.col-md-1", [
							h("a.remove", [
								h("span.glyphicon.glyphicon-remove", {"aria-hidden": ""})
							])
						]),
						h("td.col-md-6")
					])
				))
			]),
			h("span.preloadicon.glyphicon.glyphicon-remove", {"aria-hidden": ""})
		])
	])
}<|endoftext|>


<commit_before>module.exports = {
  config: {
    // default font size in pixels for all tabs
    fontSize: 13,

    // font family with optional fallbacks
    fontFamily: 'Menlo, "DejaVu Sans Mono", "Lucida Console", monospace',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █
    cursorShape: 'BLOCK',

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    backgroundColor: '#000',

    // border color (window, tabs)
    borderColor: '#333',

    // custom css to embed in the main window
    css: '',

    // custom css to embed in the terminal window
    termCSS: '',

    // custom padding (css format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#ff0000',
      green: '#33ff00',
      yellow: '#ffff00',
      blue: '#0066ff',
      magenta: '#cc00ff',
      cyan: '#00ffff',
      white: '#d0d0d0',
      lightBlack: '#808080',
      lightRed: '#ff0000',
      lightGreen: '#33ff00',
      lightYellow: '#ffff00',
      lightBlue: '#0066ff',
      lightMagenta: '#cc00ff',
      lightCyan: '#00ffff',
      lightWhite: '#ffffff'
    },

    // hyperterm-visor: customizable dropdown/hotkey overlay window
    visor: {
      hotkey: 'Option+Space',
      position: 'top', // or left, right, bottom
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    shell: 'bash',

    // for setting shell arguments (i.e. for using interactive shellArgs: ['-i'])
    // by default ['--login'] will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to false for no bell
    bell: 'SOUND',

    // if true, selected text will automatically be copied to the clipboard
    copyOnSelect: false

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [
    "hypercwd",
    "hyperline",
    "hyperlinks",
    "hyperterm-tabs",
    "hyperterm-bold-tab",
    "hyperterm-close-on-left",
    "hyperterm-visor",
    "hyperterm-cursor",
    "hyperterm-blink",
    "hyperterm-paste",
    "hyperseti"    // Seti theme
  ],
  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: []
};
<commit_msg>hyper - add directories to tabs<commit_after>module.exports = {
  config: {
    // default font size in pixels for all tabs
    fontSize: 13,

    // font family with optional fallbacks
    fontFamily: 'Menlo, "DejaVu Sans Mono", "Lucida Console", monospace',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █
    cursorShape: 'BLOCK',

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    backgroundColor: '#000',

    // border color (window, tabs)
    borderColor: '#333',

    // custom css to embed in the main window
    css: '',

    // custom css to embed in the terminal window
    termCSS: '',

    // custom padding (css format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#ff0000',
      green: '#33ff00',
      yellow: '#ffff00',
      blue: '#0066ff',
      magenta: '#cc00ff',
      cyan: '#00ffff',
      white: '#d0d0d0',
      lightBlack: '#808080',
      lightRed: '#ff0000',
      lightGreen: '#33ff00',
      lightYellow: '#ffff00',
      lightBlue: '#0066ff',
      lightMagenta: '#cc00ff',
      lightCyan: '#00ffff',
      lightWhite: '#ffffff'
    },

    // hyperterm-visor: customizable dropdown/hotkey overlay window
    visor: {
      hotkey: 'Option+Space',
      position: 'top', // or left, right, bottom
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    shell: 'bash',

    // for setting shell arguments (i.e. for using interactive shellArgs: ['-i'])
    // by default ['--login'] will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to false for no bell
    bell: 'SOUND',

    // if true, selected text will automatically be copied to the clipboard
    copyOnSelect: false

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [
    "hypercwd",
    "hyperline",
    "hyperlinks",
    "hyperterm-tabs",
    "hyperterm-tab-cwd",
    "hyperterm-bold-tab",
    "hyperterm-close-on-left",
    "hyperterm-visor",
    "hyperterm-cursor",
    "hyperterm-blink",
    "hyperterm-paste",
    "hyperseti"    // Seti theme
  ],
  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: []
};
<|endoftext|>


<commit_before>
"use strict";

var BBM = require("./BBM.js");
var __ = BBM.__;
var AST = BBM.ENUM;
var XHTML = [AST.HR, AST.LINK_IMG];
var INLINES =
[
  AST.DEL
, AST.INS
, AST.U
, AST.SUB
, AST.SUP
, AST.EM
, AST.BOLD
, AST.CODE
, AST.LINK_IMG
, AST.LINK_INT
, AST.LINK_WIKI
, AST.LINK_EXT
];

var MAP_HTML =
{
  P : "p"
, BLOCKQUOTE : "blockquote"
, PRE : "pre"
, DIV : "div"
, LI : "li"
, UL : "ul"
, OL : "ol"
, HEADER : "h"
, DT : "dt"
, DD : "dd"
, DL : "dl"
, TH : "th"
, TD : "td"
, HR : "hr"
, TR : "tr"
, TABLE : "table"
, LINK_INT : "a"
, LINK_EXT : "a"
, LINK_IMG : "img"
, LINK_WIKI : "a"
, DEL : "del"
, U : "u"
, SUB : "sub"
, SUP : "sup"
, EM : "em"
, BOLD : "strong"
, CODE : "code"
};

function hasEndTag(node)
{
 return XHTML.indexOf(node.type()) === -1;
}

function printXHTML(node, opts)
{
 return (opts.XHTML && XHTML.indexOf(node.type()) > -1) ? " /" : "";
}

function printIndent(node, opts)
{
 return INLINES.indexOf(node.type()) === -1
 ? __.repeatString(" ", opts.depth)
 : "";
}

function printBlockEnd(node)
{
 return INLINES.indexOf(node.type()) === -1 ? "\n" : "";
}

function printHeader(node, opts)
{
 var lvl = Math.abs(parseInt(node.level, 10) || 1);
 return "h" + Math.min(lvl + opts.headerOffset, 6);
}

function printAttr(node, opts)
{
 var res = "";
 var attr = node.attr();

 for (var key in attr)
 {
  if (__.has(attr, key))
  {
   res += __.escapeATTR(key).substring(0, opts.maxAttrChars)
   + "=\""
   + ((node.type() === AST.LINK_INT && key === "href") ? "#" : "")
   + __.escapeATTR(attr[key]).substring(0, opts.maxAttrChars)
   + "\" ";
  }
 }
 return res.length === 0 ? "" : " " + res.trim();
}

function printTagName(node, opts)
{
 var tagName = node.type() === AST.HEADER
 ? printHeader(node, opts)
 : MAP_HTML[node.type()];

 return __.escapeATTR(tagName || "");
}

function printTagOpen(node, opts)
{
 var tagName = printTagName(node, opts);
 if (tagName)
 {
  return printIndent(node, opts)
  + "<"
  + tagName
  + printAttr(node, opts)
  + printXHTML(node, opts)
  + ">"
  + printBlockEnd(node, opts);
 }
 return "";
}

function printTagClose(node, opts)
{
 var tagName = printTagName(node, opts);
 if (tagName && hasEndTag(node, opts))
 {
  return printBlockEnd(node, opts)
  + printIndent(node, opts)
  + "</"
  + tagName
  + ">"
  + (node.isLastChild()
    ? printIndent(node, opts)
    : printBlockEnd(node, opts));
 }
 return "";
}

function printComment(node, opts)
{
 var indent = printIndent(node, opts);
 return indent
 + "<!--\n"
 + node.children().map(printHTML, opts).join("")
 + indent
 + "-->"
 + (node.isLastChild() ? printIndent(node, opts) : printBlockEnd(node, opts));
}

function printText(node, opts)
{
 return __.escapeHTML(opts.rmNL ? __.rmNL(node.text()) : node.text());
}

function printHTML(node)
{
 var str = "";
 var opts = this;

 opts.depth += 1;
 str = node.text().length > 0
 ? printText(node, opts)
 : node.type() === AST.COMMENT
 ? printComment(node, opts)
 : printTagOpen(node, opts)
   + node.children().map(printHTML, opts).join("")
   + printTagClose(node, opts);
 opts.depth -= 1;
 return str;
}

BBM.fn.toHTML = function (options)
{
 var opts = __.extend({}, options);
 opts.depth = (parseInt(opts.depth, 10) || 0) + (printTagName(this) ? -1 : -2);
 opts.maxAttrChars = Math.abs(parseInt(opts.maxAttrChars, 10) || 2048);
 opts.headerOffset = Math.abs(parseInt(opts.headerOffset, 10) || 0);
 opts.XHTML = !!opts.XHTML;
 opts.rmNL = !!opts.rmNL;
 return printHTML.call(opts, this);
};

module.exports = BBM;

<commit_msg>Suppress HTML comment output by default.<commit_after>
"use strict";

var BBM = require("./BBM.js");
var __ = BBM.__;
var AST = BBM.ENUM;
var XHTML = [AST.HR, AST.LINK_IMG];
var INLINES =
[
  AST.DEL
, AST.INS
, AST.U
, AST.SUB
, AST.SUP
, AST.EM
, AST.BOLD
, AST.CODE
, AST.LINK_IMG
, AST.LINK_INT
, AST.LINK_WIKI
, AST.LINK_EXT
];

var MAP_HTML =
{
  P : "p"
, BLOCKQUOTE : "blockquote"
, PRE : "pre"
, DIV : "div"
, LI : "li"
, UL : "ul"
, OL : "ol"
, HEADER : "h"
, DT : "dt"
, DD : "dd"
, DL : "dl"
, TH : "th"
, TD : "td"
, HR : "hr"
, TR : "tr"
, TABLE : "table"
, LINK_INT : "a"
, LINK_EXT : "a"
, LINK_IMG : "img"
, LINK_WIKI : "a"
, DEL : "del"
, U : "u"
, SUB : "sub"
, SUP : "sup"
, EM : "em"
, BOLD : "strong"
, CODE : "code"
};

function hasEndTag(node)
{
 return XHTML.indexOf(node.type()) === -1;
}

function printXHTML(node, opts)
{
 return (opts.XHTML && XHTML.indexOf(node.type()) > -1) ? " /" : "";
}

function printIndent(node, opts)
{
 return INLINES.indexOf(node.type()) === -1
 ? __.repeatString(" ", opts.depth)
 : "";
}

function printBlockEnd(node)
{
 return INLINES.indexOf(node.type()) === -1 ? "\n" : "";
}

function printHeader(node, opts)
{
 var lvl = Math.abs(parseInt(node.level, 10) || 1);
 return "h" + Math.min(lvl + opts.headerOffset, 6);
}

function printAttr(node, opts)
{
 var res = "";
 var attr = node.attr();

 for (var key in attr)
 {
  if (__.has(attr, key))
  {
   res += __.escapeATTR(key).substring(0, opts.maxAttrChars)
   + "=\""
   + ((node.type() === AST.LINK_INT && key === "href") ? "#" : "")
   + __.escapeATTR(attr[key]).substring(0, opts.maxAttrChars)
   + "\" ";
  }
 }
 return res.length === 0 ? "" : " " + res.trim();
}

function printTagName(node, opts)
{
 var tagName = node.type() === AST.HEADER
 ? printHeader(node, opts)
 : MAP_HTML[node.type()];

 return __.escapeATTR(tagName || "");
}

function printTagOpen(node, opts)
{
 var tagName = printTagName(node, opts);
 if (tagName)
 {
  return printIndent(node, opts)
  + "<"
  + tagName
  + printAttr(node, opts)
  + printXHTML(node, opts)
  + ">"
  + printBlockEnd(node, opts);
 }
 return "";
}

function printTagClose(node, opts)
{
 var tagName = printTagName(node, opts);
 if (tagName && hasEndTag(node, opts))
 {
  return printBlockEnd(node, opts)
  + printIndent(node, opts)
  + "</"
  + tagName
  + ">"
  + (node.isLastChild()
    ? printIndent(node, opts)
    : printBlockEnd(node, opts));
 }
 return "";
}

function printComment(node, opts)
{
 var indent = printIndent(node, opts);
 return indent
 + "<!--\n"
 + node.children().map(printHTML, opts).join("")
 + indent
 + "-->"
 + (node.isLastChild() ? printIndent(node, opts) : printBlockEnd(node, opts));
}

function printText(node, opts)
{
 return __.escapeHTML(opts.rmNL ? __.rmNL(node.text()) : node.text());
}

function printHTML(node)
{
 var str = "";
 var opts = this;

 opts.depth += 1;
 str = node.text().length > 0
 ? printText(node, opts)
 : node.type() === AST.COMMENT
 ? (opts.comment ? printComment(node, opts) : "")
 : printTagOpen(node, opts)
   + node.children().map(printHTML, opts).join("")
   + printTagClose(node, opts);
 opts.depth -= 1;
 return str;
}

BBM.fn.toHTML = function (options)
{
 var opts = __.extend({}, options);
 opts.depth = (parseInt(opts.depth, 10) || 0) + (printTagName(this) ? -1 : -2);
 opts.maxAttrChars = Math.abs(parseInt(opts.maxAttrChars, 10) || 2048);
 opts.headerOffset = Math.abs(parseInt(opts.headerOffset, 10) || 0);
 opts.XHTML = !!opts.XHTML;
 opts.comment = !!opts.comment;
 opts.rmNL = !!opts.rmNL;
 return printHTML.call(opts, this);
};

module.exports = BBM;

<|endoftext|>


<commit_before>p=function(){
  t.innerHTML+='[guest@molarmanful.github.io]$ '
  i.focus()
}
p()

onkeydown=function(e){
  e.which==13&&(
    e.preventDefault(),
    I=i.innerHTML,
    t.removeChild(i),
    t.innerHTML+=I+'\n',
    I.match(/^ *$/)?
      0
    :I.match(/^ *clear($| )/)?
      (t.innerHTML='')
    :I.match(/^ *info($| )/)?
      (t.innerHTML+=h.innerHTML+'\n')
    :I.match(/^ *whoami($| )/)?
      (t.innerHTML+=a.innerHTML+'\n')
    :(t.innerHTML+="Command not found. Type 'info' for a list of commands.\n"),
    p()
  )
}
<commit_msg>change prompt<commit_after>prompt='[guest@molarmanful.github.io]$ '
p=function(){
  t.innerHTML+=prompt+''
  i.focus()
}
p()

onkeypress=function(e){
  e.which==13&&(
    e.preventDefault(),
    I=i.innerHTML,
    t.removeChild(i),
    t.innerHTML+=I+'\n',
    I.match(/^ *$/)?
      0
    :I.match(/^ *clear($| )/)?
      (t.innerHTML='')
    :I.match(/^ *info($| )/)?
      (t.innerHTML+=h.innerHTML+'\n')
    :I.match(/^ *whoami($| )/)?
      (t.innerHTML+=a.innerHTML+'\n')
    :(t.innerHTML+="Command not found. Type 'info' for a list of commands.\n"),
    p()
  )
}
<|endoftext|>


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

if (typeof Object.assign != 'function') {
  Object.assign = function(target) {
    'use strict';
    if (target == null) {
      throw new TypeError('Cannot convert undefined or null to object');
    }

    target = Object(target);
    for (var index = 1; index < arguments.length; index++) {
      var source = arguments[index];
      if (source != null) {
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
    }
    return target;
  };
}

var _rawCookie = {};
var _res = undefined;

function _isResWritable() {
  if(!_res)
    return false
  if(_res.headersSent === true)
    return false
  return true
}

function load(name, doNotParse) {
  var cookies = (typeof document === 'undefined') ? _rawCookie : cookie.parse(document.cookie);
  var cookieVal = cookies && cookies[name];

  if (!doNotParse) {
    try {
      cookieVal = JSON.parse(cookieVal);
    } catch(e) {
      // Not serialized object
    }
  }

  return cookieVal;
}

function select(regex) {
  var cookies = (typeof document === 'undefined') ? _rawCookie : cookie.parse(document.cookie);
  if(!cookies)
    return {}
  return Object.keys(cookies)
    .reduce(function(accumulator, name) {
      if(regex && !regex.test(name))
        return accumulator
      var newCookie = {}
      newCookie[name] = cookies[name]
      return Object.assign({}, accumulator, newCookie)
    }, {})
}

function save(name, val, opt) {
  _rawCookie[name] = val;

  // allow you to work with cookies as objects.
  if (typeof val === 'object') {
    _rawCookie[name] = JSON.stringify(val);
  }

  // Cookies only work in the browser
  if (typeof document !== 'undefined') {
    document.cookie = cookie.serialize(name, _rawCookie[name], opt);
  }

  if (_isResWritable() && _res.cookie) {
    _res.cookie(name, val, opt);
  }
}

function remove(name, opt) {
  delete _rawCookie[name];

  if (typeof opt === 'undefined') {
    opt = {};
  } else if (typeof opt === 'string') {
    // Will be deprecated in future versions
    opt = { path: opt };
  }

  if (typeof document !== 'undefined') {
    opt.expires = new Date(1970, 1, 1, 0, 0, 1);
    document.cookie = cookie.serialize(name, '', opt);
  }

  if (_isResWritable() && _res.clearCookie) {
    _res.clearCookie(name, opt);
  }
}

function setRawCookie(rawCookie) {
  if (rawCookie) {
    _rawCookie = cookie.parse(rawCookie);
  } else {
    _rawCookie = {};
  }
}

function plugToRequest(req, res) {
  if (req.cookie) {
    _rawCookie = req.cookie;
  } else if (req.cookies) {
    _rawCookie = req.cookies;
  } else if (req.headers && req.headers.cookie) {
    setRawCookie(req.headers.cookie);
  } else {
    _rawCookie = {};
  }

  _res = res;
  return function unplug() {
    _res = null;
    _rawCookie = {};
  }
}

var reactCookie = {
  load: load,
  select: select,
  save: save,
  remove: remove,
  setRawCookie: setRawCookie,
  plugToRequest: plugToRequest
};

if (typeof window !== 'undefined') {
  window['reactCookie'] = reactCookie;
}

module.exports = reactCookie;
<commit_msg>made select more performant if regex is omitted<commit_after>var cookie = require('cookie');

if (typeof Object.assign != 'function') {
  Object.assign = function(target) {
    'use strict';
    if (target == null) {
      throw new TypeError('Cannot convert undefined or null to object');
    }

    target = Object(target);
    for (var index = 1; index < arguments.length; index++) {
      var source = arguments[index];
      if (source != null) {
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
    }
    return target;
  };
}

var _rawCookie = {};
var _res = undefined;

function _isResWritable() {
  if(!_res)
    return false
  if(_res.headersSent === true)
    return false
  return true
}

function load(name, doNotParse) {
  var cookies = (typeof document === 'undefined') ? _rawCookie : cookie.parse(document.cookie);
  var cookieVal = cookies && cookies[name];

  if (!doNotParse) {
    try {
      cookieVal = JSON.parse(cookieVal);
    } catch(e) {
      // Not serialized object
    }
  }

  return cookieVal;
}

function select(regex) {
  var cookies = (typeof document === 'undefined') ? _rawCookie : cookie.parse(document.cookie);
  if(!cookies)
    return {}
  if(!regex)
    return cookies
  return Object.keys(cookies)
    .reduce(function(accumulator, name) {
      if(!regex.test(name))
        return accumulator
      var newCookie = {}
      newCookie[name] = cookies[name]
      return Object.assign({}, accumulator, newCookie)
    }, {})
}

function save(name, val, opt) {
  _rawCookie[name] = val;

  // allow you to work with cookies as objects.
  if (typeof val === 'object') {
    _rawCookie[name] = JSON.stringify(val);
  }

  // Cookies only work in the browser
  if (typeof document !== 'undefined') {
    document.cookie = cookie.serialize(name, _rawCookie[name], opt);
  }

  if (_isResWritable() && _res.cookie) {
    _res.cookie(name, val, opt);
  }
}

function remove(name, opt) {
  delete _rawCookie[name];

  if (typeof opt === 'undefined') {
    opt = {};
  } else if (typeof opt === 'string') {
    // Will be deprecated in future versions
    opt = { path: opt };
  }

  if (typeof document !== 'undefined') {
    opt.expires = new Date(1970, 1, 1, 0, 0, 1);
    document.cookie = cookie.serialize(name, '', opt);
  }

  if (_isResWritable() && _res.clearCookie) {
    _res.clearCookie(name, opt);
  }
}

function setRawCookie(rawCookie) {
  if (rawCookie) {
    _rawCookie = cookie.parse(rawCookie);
  } else {
    _rawCookie = {};
  }
}

function plugToRequest(req, res) {
  if (req.cookie) {
    _rawCookie = req.cookie;
  } else if (req.cookies) {
    _rawCookie = req.cookies;
  } else if (req.headers && req.headers.cookie) {
    setRawCookie(req.headers.cookie);
  } else {
    _rawCookie = {};
  }

  _res = res;
  return function unplug() {
    _res = null;
    _rawCookie = {};
  }
}

var reactCookie = {
  load: load,
  select: select,
  save: save,
  remove: remove,
  setRawCookie: setRawCookie,
  plugToRequest: plugToRequest
};

if (typeof window !== 'undefined') {
  window['reactCookie'] = reactCookie;
}

module.exports = reactCookie;
<|endoftext|>