<commit_before>'use strict';

var jf = require('../../'),
    expect    = require('chai').expect,
    fs = require('fs'),
    http = require('http');

const testFilePath = './' + Math.random() + '.json';
const testFile2Path = './' + Math.random() + '.json';
const testFile3Path = './' + Math.random() + '.json';
const testFile4Path = './' + Math.random() + '.json';

const collectedToFilePath = './' + Math.random() + '.json';

const testValue = { msg: 'hello world' };

let server = http.createServer( (request, response) => {
  response.writeHead(200, {'Content-Type': 'application/json'});
  response.end( JSON.stringify( testValue ) );
}).listen(8080);

describe('Roots executer ', function () {
  it('should work without error', function (done) {

    jf.roots(
      [ jf.filed( testFilePath ),
        jf.filed( testFile2Path ),
        jf.newFile( testFile3Path ),
        jf.download( 'http://localhost:8080/', testFile4Path) ],
      ( err ) => { console.log( err ) }
    )
    .io( (obj,filePath) => {

      if( filePath == testFile4Path ) {
        expect( obj ).to.be.eql( testValue );
      }

      return { file: filePath }

    } )
    .collect( obj => {
      expect( obj.length ).to.be.equal(4);
      done();
    },
    collectedToFilePath )
    .exec();
  });
});
<commit_msg>Test nested roots executer<commit_after>'use strict';

var jf = require('../../'),
    expect    = require('chai').expect,
    fs = require('fs'),
    http = require('http');

const testFilePath = './' + Math.random() + '.json';
const testFile2Path = './' + Math.random() + '.json';
const testFile3Path = './' + Math.random() + '.json';
const testFile4Path = './' + Math.random() + '.json';

const collectedToFilePath = './' + Math.random() + '.json';

const testValue = { msg: 'hello world' };

let server = http.createServer( (request, response) => {
  response.writeHead(200, {'Content-Type': 'application/json'});
  response.end( JSON.stringify( testValue ) );
}).listen(8080);

describe('Roots executer ', function () {
  it('should work without error', function (done) {

    jf.roots(
      [ jf.filed( testFilePath ),
        jf.roots(
          [ jf.filed( testFile2Path ),
            jf.newFile( testFile3Path ) ] ),
        jf.download( 'http://localhost:8080/', testFile4Path) ],
      ( err ) => { console.log( err ) }
    )
    .io( (obj,filePath) => {

      if( filePath == testFile4Path ) {
        expect( obj ).to.be.eql( testValue );
      }

      return { file: filePath }

    } )
    .collect( obj => {
      expect( obj.length ).to.be.equal(4);
      done();
    },
    collectedToFilePath )
    .exec();
  });
});
<|endoftext|>


<commit_before>/*
 @see /templates/system/modules/pwa/themes/base/js/sw-register.js

 TODO: Implement the Service Worker to cache some static data, html pages, images, etc.
 More info: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers

 🚀 Feel free to fork the project: https://github.com/pH7Software/pH7-Social-Dating-CMS
 Commit your changes, then open a Pull Request for submitting your awesome changes 🎉
 */

const STATIC_CACHE_NAME = 'sta_homepage';
const DYNAMIC_CACHE_NAME = 'dyn_homepage';

const CACHED_FILES = [
    '/',
    // TODO: Add more URLs to be cached here
];

self.addEventListener('install', async event => {
    const cache = await caches.open(STATIC_CACHE_NAME);
    cache.addAll(CACHED_FILES);
});

self.addEventListener('fetch', event => {
    const {request} = event;
    const url = new URL(request.url);

    if (url.origin === location.origin) {
        event.respondWith(cacheData(request));
    } else {
        event.respondWith(networkFirst(request));
    }
});

async function cacheData(request) {
    const cachedResponse = await caches.match(request);
    return cachedResponse || fetch(request);
}

async function networkFirst(request) {
    const cache = await caches.open(DYNAMIC_CACHE_NAME);

    try {
        const response = await fetch(request);
        cache.put(request, response.clone());
        return response;
    } catch (error) {
        return await cache.match(request);
    }
}

// Add to Home Screen
self.addEventListener('fetch', event => {
    // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=823392
    if (event.request.cache == 'only-if-cached' && event.request.mode != 'same-origin') {
        return;
    }
    event.respondWith(
        //  Try to find response in cache...
        caches.match(event.request)
            .then((resp) => {
                // If response is found in cache, then return it, otherwise fetch it
                return resp || fetch(event.request);
            })
            .catch((err) => {
                // Something went wrong
                console.log("Service worker Fetch: ", err);
            })
    );
});

<commit_msg>[PWA:service-worker.js] Use strict comparison<commit_after>/*
 @see /templates/system/modules/pwa/themes/base/js/sw-register.js

 TODO: Implement the Service Worker to cache some static data, html pages, images, etc.
 More info: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers

 🚀 Feel free to fork the project: https://github.com/pH7Software/pH7-Social-Dating-CMS
 Commit your changes, then open a Pull Request for submitting your awesome changes 🎉
 */

const STATIC_CACHE_NAME = 'sta_homepage';
const DYNAMIC_CACHE_NAME = 'dyn_homepage';

const CACHED_FILES = [
    '/',
    // TODO: Add more URLs to be cached here
];

self.addEventListener('install', async event => {
    const cache = await caches.open(STATIC_CACHE_NAME);
    cache.addAll(CACHED_FILES);
});

self.addEventListener('fetch', event => {
    const {request} = event;
    const url = new URL(request.url);

    if (url.origin === location.origin) {
        event.respondWith(cacheData(request));
    } else {
        event.respondWith(networkFirst(request));
    }
});

async function cacheData(request) {
    const cachedResponse = await caches.match(request);
    return cachedResponse || fetch(request);
}

async function networkFirst(request) {
    const cache = await caches.open(DYNAMIC_CACHE_NAME);

    try {
        const response = await fetch(request);
        cache.put(request, response.clone());
        return response;
    } catch (error) {
        return await cache.match(request);
    }
}

// Add to Home Screen
self.addEventListener('fetch', event => {
    // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=823392
    if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
        return;
    }
    event.respondWith(
        //  Try to find response in cache...
        caches.match(event.request)
            .then((resp) => {
                // If response is found in cache, then return it, otherwise fetch it
                return resp || fetch(event.request);
            })
            .catch((err) => {
                // Something went wrong
                console.log("Service worker Fetch: ", err);
            })
    );
});
<|endoftext|>


<commit_before>'use strict';

var jf = require('../../'),
    expect    = require('chai').expect,
    fs = require('fs');

describe('bFiled( obj ).io(function(){}).exec', function () {
    it('should be a function', function () {
        expect(jf.filed("file").io(function(){}).exec).to.be.a('function');
    });
});

const testFilePath = './' + Math.random() + '.bson';
describe('The initialValue', function () {
  it('should be equal to defined in json.filed.', function (done) {
    jf.filed( testFilePath ).io( function( obj ) {
        expect(obj).to.eql(jf.initialValue());
        done();
    }).exec();
  });
});

const testFile2Path = './' + Math.random() + '.bson';
var updatedValue = { msg: 'updated' };
describe('The updated value', function () {
  it('should be read again as updated.', function (done) {
    jf.filed( testFile2Path ).io( function( obj ) {
      return updatedValue;
    }).exec();

    setTimeout(
      function(){
        jf.filed( testFile2Path ).io( function( obj ) {
          expect(obj).to.eql(updatedValue);
          done();
        }).exec();
      },
      100);
    })

});

const testFile3Path = './' + Math.random() + '.bson';
var initialValue = { msg: 'initial' };
describe('The value function does not return ', function () {
  it('should not be written.', function (done) {
    jf.filed( testFile3Path).io( function( obj ) {
      return initialValue;
    })
    .io( function( obj ) {
          expect(obj).to.eql(initialValue);
          obj.msg = "this value is not written."
          //return obj
    })
    .pass( (obj) => {
      expect(obj).to.eql(initialValue);
      done();
    })
    .exec();

  });
});

const testFile4Path = './' + Math.random() + '.bson';
describe('Function return null', function () {
  it('does not make json to be written.', function (done) {
    jf.filed( testFile4Path).io( function( obj ) {
      return initialValue;
    })
    .io( function( obj ) {
        expect(obj).to.eql(initialValue);
        obj.msg = "this value is not written also."
        return null;
    })
    .io(function( obj ) {
          expect(obj).to.eql(initialValue);
          done();
        }
    ).exec();

  });
});

const testFile8Path = './' + Math.random() + '.BSON';

describe('Upper case file extension ', function () {
  it('should not affect result.', function (done) {
    jf.filed( testFile8Path ).io(
        function( obj, filePath ) {
          return { path: testFile8Path };
        }
      )
      .pass(
        function(){
          jf.filed( testFile8Path ).io( function( obj, filePath ) {
            expect( obj.path ).to.eql( testFile8Path );
            done();
          }).exec();
        }
      ).exec();
    });
});

const serializedFunctionFilePath = './serializedFunction.' + Math.random() + '.bson';
const hello = 'hello';

describe('Serialized function ', function () {
  it('can be executed.', function (done) {
    jf.filed( serializedFunctionFilePath )
    .io(
        function( obj, filePath ) {
          return { say: function( greeting ){ return greeting; } };
        }
      )
    .pass(
      function(){
        jf.filed( serializedFunctionFilePath )
        .io( function( obj ) {
          expect( obj.say( hello ) ).to.eql( hello );
          done();
        }).exec();
    }).exec();
  });

});
<commit_msg>Revmoe setTimeout from test<commit_after>'use strict';

var jf = require('../../'),
    expect    = require('chai').expect,
    fs = require('fs');

describe('bFiled( obj ).io(function(){}).exec', function () {
    it('should be a function', function () {
        expect(jf.filed("file").io(function(){}).exec).to.be.a('function');
    });
});

const testFilePath = './' + Math.random() + '.bson';
describe('The initialValue', function () {
  it('should be equal to defined in json.filed.', function (done) {
    jf.filed( testFilePath ).io( function( obj ) {
        expect(obj).to.eql(jf.initialValue());
        done();
    }).exec();
  });
});

const testFile2Path = './' + Math.random() + '.bson';
var updatedValue = { msg: 'updated' };
describe('The updated value', function () {
  it('should be read again as updated.', function (done) {
    jf.filed( testFile2Path ).io( function( obj ) {
      return updatedValue;
    })
    .pass(
      function( obj ) {
        expect(obj).to.eql(updatedValue);
        done();
    }).exec();
  });
});

const testFile3Path = './' + Math.random() + '.bson';
var initialValue = { msg: 'initial' };
describe('The value function does not return ', function () {
  it('should not be written.', function (done) {
    jf.filed( testFile3Path).io( function( obj ) {
      return initialValue;
    })
    .io( function( obj ) {
          expect(obj).to.eql(initialValue);
          obj.msg = "this value is not written."
          //return obj
    })
    .pass( (obj) => {
      expect(obj).to.eql(initialValue);
      done();
    })
    .exec();

  });
});

const testFile4Path = './' + Math.random() + '.bson';
describe('Function return null', function () {
  it('does not make json to be written.', function (done) {
    jf.filed( testFile4Path).io( function( obj ) {
      return initialValue;
    })
    .io( function( obj ) {
        expect(obj).to.eql(initialValue);
        obj.msg = "this value is not written also."
        return null;
    })
    .io(function( obj ) {
          expect(obj).to.eql(initialValue);
          done();
        }
    ).exec();

  });
});

const testFile8Path = './' + Math.random() + '.BSON';

describe('Upper case file extension ', function () {
  it('should not affect result.', function (done) {
    jf.filed( testFile8Path ).io(
        function( obj, filePath ) {
          return { path: testFile8Path };
        }
      )
      .pass(
        function(){
          jf.filed( testFile8Path ).io( function( obj, filePath ) {
            expect( obj.path ).to.eql( testFile8Path );
            done();
          }).exec();
        }
      ).exec();
    });
});

const serializedFunctionFilePath = './serializedFunction.' + Math.random() + '.bson';
const hello = 'hello';

describe('Serialized function ', function () {
  it('can be executed.', function (done) {
    jf.filed( serializedFunctionFilePath )
    .io(
        function( obj, filePath ) {
          return { say: function( greeting ){ return greeting; } };
        }
      )
    .pass(
      function(){
        jf.filed( serializedFunctionFilePath )
        .io( function( obj ) {
          expect( obj.say( hello ) ).to.eql( hello );
          done();
        }).exec();
    }).exec();
  });

});
<|endoftext|>


<commit_before>/*global describe, beforeEach, it*/
'use strict';

var path    = require('path');
var yeoman  = require('yeoman-generator');
var helpers = yeoman.test;
var assert  = yeoman.assert;
var createAppGenerator = require('../helpers/create-generator').createAppGenerator;

describe('Yeogurt generator using Server', function () {
    beforeEach(function (done) {
        helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
            if (err) {
                return done(err);
            }

            this.app = createAppGenerator();

            done();
        }.bind(this));
    });
    describe('With Defaults', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'grunt/config/util/open.js',
                'grunt/config/server/express.js',
                'grunt/config/server/env.js',
                'server/controllers/main.js',
                'server/config/express.js',
                'server/config/env',
                'server/config/env/default.js',
                'server/config/env/development.js',
                'server/config/env/production.js',
                'server/routes.js',
                'server.js'
            ];

            helpers.mockPrompt(this.app, {
                useServer: true,
                dbOption: 'none'
            });
            this.app.run([], function () {
                assert.file(expected);
                done();
            });
        });
    });
    describe('With MongoDB Database', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'server/config/database.js'
            ];
            var fileContentToTest = [
                ['server/config/database.js', /mongoose/i]
            ];

            helpers.mockPrompt(this.app, {
                dbOption: 'mongodb',
            });
            this.app.run([], function () {
                assert.file(expected);
                assert.fileContent(fileContentToTest);
                done();
            });
        });
    });
    describe('With MySQL Database', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'server/config/database.js'
            ];
            var fileContentToTest = [
                ['server/config/database.js', /sequelize/i],
                ['server/config/express.js', /sequelize/i]
            ];

            helpers.mockPrompt(this.app, {
                dbOption: 'mysql',
            });
            this.app.run([], function () {
                assert.file(expected);
                assert.fileContent(fileContentToTest);
                done();
            });
        });
    });
    describe('With Static Jade', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'server/templates/layouts/base.jade',
                'server/templates/index.jade',
            ];

            helpers.mockPrompt(this.app, {
                useSinglePageApplication: false,
                htmlOption: 'jade',
                useServer: true
            });
            this.app.run([], function () {
                assert.file(expected);
                done();
            });
        });
    });
    describe('With Static Swig', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'server/templates/layouts/base.swig',
                'server/templates/index.swig',
            ];

            helpers.mockPrompt(this.app, {
                useSinglePageApplication: false,
                htmlOption: 'swig',
                useServer: true
            });
            this.app.run([], function () {
                assert.file(expected);
                done();
            });
        });
    });
    describe('With Single Page Application', function () {
        describe('With Defaults', function () {
            it('Creates expected files', function (done) {
                var expected = [
                    'server/templates/index.html'
                ];

                helpers.mockPrompt(this.app, {
                    useSinglePageApplication: true,
                    useServer: true
                });
                this.app.run([], function () {
                    assert.file(expected);
                    done();
                });
            });
        });
        describe('With React', function () {
            it('Creates expected files', function (done) {
                var expected = [
                    'server/modules/reactRender.js',
                    'server/modules'
                ];

                helpers.mockPrompt(this.app, {
                    useSinglePageApplication: true,
                    useServer: true,
                    useServerTemplates: true,
                    jsFramework: 'react'
                });
                this.app.run([], function () {
                    assert.file(expected);
                    done();
                });
            });
        });
        describe('With Server templates', function () {
            it('Creates expected files', function (done) {
                var fileContentToTest = [
                    ['server/templates/index.html', /<\%\- body \%\>/i],
                    ['server/controllers/main.js', /reactRender/i]
                ];

                helpers.mockPrompt(this.app, {
                    useSinglePageApplication: true,
                    useServer: true,
                    useServerTemplates: true,
                    jsFramework: 'react'
                });
                this.app.run([], function () {
                    assert.fileContent(fileContentToTest);
                    done();
                });
            });
        });
        describe('Without Server templates', function () {
            it('Creates expected files', function (done) {
                var expectedContent = [
                    ['server/routes.js', /app\.get\('\*'/i]
                ];
                var fileContentToTest = [
                    ['server/templates/index.html', /<\%\- body \%\>/i],
                    ['server/controllers/main.js', /reactRender/i]
                ];

                helpers.mockPrompt(this.app, {
                    useSinglePageApplication: true,
                    useServer: true,
                    useServerTemplates: false,
                    jsFramework: 'react'
                });
                this.app.run([], function () {
                    assert.noFileContent(fileContentToTest);
                    assert.fileContent(expectedContent);
                    done();
                });
            });
        });
    });
    describe('With Paypal\'s Lucsa Security Module', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'server/config/security.js'
            ];
            var fileContentToTest = [
                ['server/config/express.js', /lusca/i],
                ['server/config/env/default.js', /security/i]
            ];

            helpers.mockPrompt(this.app, {
                useServer: true,
                useSecurity: true
            });
            this.app.run([], function () {
                assert.file(expected);
                assert.fileContent(fileContentToTest);
                done();
            });
        });
    });
    describe('With Cookie Sessions', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'server/config/secrets.js'
            ];
            var fileContentToTest = [
                ['server/config/express.js', /app.use\(session\(\{/i],
            ];

            helpers.mockPrompt(this.app, {
                useServer: true,
                useSession: true
            });
            this.app.run([], function () {
                assert.file(expected);
                assert.fileContent(fileContentToTest);
                done();
            });
        });
    });
});
<commit_msg>added new test to handle server route testing for static sites<commit_after>/*global describe, beforeEach, it*/
'use strict';

var path    = require('path');
var yeoman  = require('yeoman-generator');
var helpers = yeoman.test;
var assert  = yeoman.assert;
var createAppGenerator = require('../helpers/create-generator').createAppGenerator;

describe('Yeogurt generator using Server', function () {
    beforeEach(function (done) {
        helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
            if (err) {
                return done(err);
            }

            this.app = createAppGenerator();

            done();
        }.bind(this));
    });
    describe('With Defaults', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'grunt/config/util/open.js',
                'grunt/config/server/express.js',
                'grunt/config/server/env.js',
                'server/controllers/main.js',
                'server/config/express.js',
                'server/config/env',
                'server/config/env/default.js',
                'server/config/env/development.js',
                'server/config/env/production.js',
                'server/routes.js',
                'server.js'
            ];

            helpers.mockPrompt(this.app, {
                useServer: true,
                dbOption: 'none'
            });
            this.app.run([], function () {
                assert.file(expected);
                done();
            });
        });
    });
    describe('With MongoDB Database', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'server/config/database.js'
            ];
            var fileContentToTest = [
                ['server/config/database.js', /mongoose/i]
            ];

            helpers.mockPrompt(this.app, {
                dbOption: 'mongodb',
            });
            this.app.run([], function () {
                assert.file(expected);
                assert.fileContent(fileContentToTest);
                done();
            });
        });
    });
    describe('With MySQL Database', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'server/config/database.js'
            ];
            var fileContentToTest = [
                ['server/config/database.js', /sequelize/i],
                ['server/config/express.js', /sequelize/i]
            ];

            helpers.mockPrompt(this.app, {
                dbOption: 'mysql',
            });
            this.app.run([], function () {
                assert.file(expected);
                assert.fileContent(fileContentToTest);
                done();
            });
        });
    });
    describe('With Static Jade', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'server/templates/layouts/base.jade',
                'server/templates/index.jade',
            ];
            var expectedContent = [
                ['server/routes.js', /app\.get\('\/'/i]
            ];

            helpers.mockPrompt(this.app, {
                useSinglePageApplication: false,
                htmlOption: 'jade',
                useServer: true
            });
            this.app.run([], function () {
                assert.file(expected);
                assert.fileContent(expectedContent);
                done();
            });
        });
    });
    describe('With Static Swig', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'server/templates/layouts/base.swig',
                'server/templates/index.swig',
            ];
            var expectedContent = [
                ['server/routes.js', /app\.get\('\/'/i]
            ];

            helpers.mockPrompt(this.app, {
                useSinglePageApplication: false,
                htmlOption: 'swig',
                useServer: true
            });
            this.app.run([], function () {
                assert.file(expected);
                assert.fileContent(expectedContent);
                done();
            });
        });
    });
    describe('With Single Page Application', function () {
        describe('With Defaults', function () {
            it('Creates expected files', function (done) {
                var expected = [
                    'server/templates/index.html'
                ];

                helpers.mockPrompt(this.app, {
                    useSinglePageApplication: true,
                    useServer: true
                });
                this.app.run([], function () {
                    assert.file(expected);
                    done();
                });
            });
        });
        describe('With React', function () {
            it('Creates expected files', function (done) {
                var expected = [
                    'server/modules/reactRender.js',
                    'server/modules'
                ];

                helpers.mockPrompt(this.app, {
                    useSinglePageApplication: true,
                    useServer: true,
                    useServerTemplates: true,
                    jsFramework: 'react'
                });
                this.app.run([], function () {
                    assert.file(expected);
                    done();
                });
            });
        });
        describe('With Server templates', function () {
            it('Creates expected files', function (done) {
                var fileContentToTest = [
                    ['server/templates/index.html', /<\%\- body \%\>/i],
                    ['server/controllers/main.js', /reactRender/i]
                ];

                helpers.mockPrompt(this.app, {
                    useSinglePageApplication: true,
                    useServer: true,
                    useServerTemplates: true,
                    jsFramework: 'react'
                });
                this.app.run([], function () {
                    assert.fileContent(fileContentToTest);
                    done();
                });
            });
        });
        describe('Without Server templates', function () {
            it('Creates expected files', function (done) {
                var expectedContent = [
                    ['server/routes.js', /app\.get\('\*'/i]
                ];
                var fileContentToTest = [
                    ['server/templates/index.html', /<\%\- body \%\>/i],
                    ['server/controllers/main.js', /reactRender/i]
                ];

                helpers.mockPrompt(this.app, {
                    useSinglePageApplication: true,
                    useServer: true,
                    useServerTemplates: false,
                    jsFramework: 'react'
                });
                this.app.run([], function () {
                    assert.noFileContent(fileContentToTest);
                    assert.fileContent(expectedContent);
                    done();
                });
            });
        });
    });
    describe('With Paypal\'s Lucsa Security Module', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'server/config/security.js'
            ];
            var fileContentToTest = [
                ['server/config/express.js', /lusca/i],
                ['server/config/env/default.js', /security/i]
            ];

            helpers.mockPrompt(this.app, {
                useServer: true,
                useSecurity: true
            });
            this.app.run([], function () {
                assert.file(expected);
                assert.fileContent(fileContentToTest);
                done();
            });
        });
    });
    describe('With Cookie Sessions', function () {
        it('Creates expected files', function (done) {
            var expected = [
                'server/config/secrets.js'
            ];
            var fileContentToTest = [
                ['server/config/express.js', /app.use\(session\(\{/i],
            ];

            helpers.mockPrompt(this.app, {
                useServer: true,
                useSession: true
            });
            this.app.run([], function () {
                assert.file(expected);
                assert.fileContent(fileContentToTest);
                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>/**
 * Test dependencies.
 */

var tape = require('tape')
var vomit = require('..')

tape('should create element with attributes', (test) => {
  test.plan(1)
  var btn = vomit`<button id="btn" class="test">hello</button>`
  test.equal(btn.outerHTML, '<button id="btn" class="test">hello</button>')
})

tape('should interpolate strings', (test) => {
  test.plan(1)
  var name = 'olivier'
  var btn = vomit`<button id="${name}" class="${name}">hello</button>`
  test.equal(btn.outerHTML, '<button id="olivier" class="olivier">hello</button>')
})

tape('should interpolate booleans', (test) => {
  test.plan(1)
  var bool = true
  var btn = vomit`<button hidden="${bool}">hello</button>`
  test.equal(btn.outerHTML, '<button hidden="true">hello</button>')
})<commit_msg>should interpolate array in attributes<commit_after>/**
 * Test dependencies.
 */

var tape = require('tape')
var vomit = require('..')

tape('should create element with attributes', (test) => {
  test.plan(1)
  var btn = vomit`<button id="btn" class="test">hello</button>`
  test.equal(btn.outerHTML, '<button id="btn" class="test">hello</button>')
})

tape('should interpolate strings', (test) => {
  test.plan(1)
  var name = 'olivier'
  var btn = vomit`<button id="${name}" class="${name}">hello</button>`
  test.equal(btn.outerHTML, '<button id="olivier" class="olivier">hello</button>')
})

tape('should interpolate booleans', (test) => {
  test.plan(1)
  var bool = true
  var btn = vomit`<button hidden="${bool}">hello</button>`
  test.equal(btn.outerHTML, '<button hidden="true">hello</button>')
})

tape('should interpolate arrays', (test) => {
  test.plan(1)
  var classes = ['hello', 'world']
  var btn = vomit`<button class="${classes}">hello</button>`
  test.equal(btn.outerHTML, '<button class="hello world">hello</button>')
})<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const sinon = require('sinon');
const tap = require('tap');

const utilities = require('../commands/utilities');

let mockCwd;
let mockResolve;

tap.test('.paths', (suite) => {
    suite.beforeEach((done) => {
        mockCwd = sinon.stub(process, 'cwd');
        mockCwd.returns('root');

        mockResolve = sinon.stub(path, 'resolve');
        mockResolve.callsFake(function() {
            return Array.from(arguments).join('/');
        });

        done();
    });

    suite.afterEach((done) => {
        mockCwd.restore();
        mockResolve.restore();
    });

    suite.test('.create should return a method', (test) => {
        test.plan(2);

        const method = utilities.paths.create('make', 'pizza');

        test.equal(typeof method, 'function');
        test.equal(method('large', 'pepperoni'), 'root/make/pizza/large/pepperoni');

        test.end();
    });

    suite.test('.root should return the root path plus any other arguments', (test) => {
        test.plan(1);

        test.equal(
            utilities.paths.root('burger', 'cheese'),
            'root/burger/cheese'
        );

        test.end();
    });

    suite.end();
});

tap.test('#checkIsDashFormat', (suite) => {
    const check = utilities.checkIsDashFormat;

    suite.test('should return false if no value is provided', (test) => {
        test.plan(4);

        test.notOk(check());
        test.notOk(check(null));
        test.notOk(check(0));
        test.notOk(check(false));

        test.end();
    });

    suite.test('should return false if the value is not a string', (test) => {
        test.plan(3);

        test.notOk(check(1));
        test.notOk(check(true));
        test.notOk(check(function() {}));

        test.end();
    });

    suite.test('should return false if the string has no characters', (test) => {
        test.plan(1);

        test.notOk(check(''));

        test.end();
    });

    suite.test('should return false if it is not dash format (no special characters)', (test) => {
        test.plan(4);

        test.notOk(check('        '));
        test.notOk(check('cant-end-in-a-'));
        test.notOk(check('no-!?$-chars'));
        test.notOk(check('123-cant-start-with-number'));

        test.end();
    });

    suite.test('should return true if it is dash format', (test) => {
        test.plan(2);

        test.ok(check('this-is-good'));
        test.ok(check('numbers-12-3-4-work'));

        test.end();
    });

    suite.end();
});

tap.test('#testIsDashFormat', (suite) => {
    const check = utilities.testIsDashFormat;

    suite.test('should return the value if it is dash format', (test) => {
        test.plan(2);

        test.equal(check('this-is-good'), 'this-is-good');
        test.equal(check('this-15-good'), 'this-15-good');

        test.end();
    });

    suite.test('should return null if the value is not dash format', (test) => {
        test.plan(12);

        test.equal(check(), null);
        test.equal(check(null), null);
        test.equal(check(0), null);
        test.equal(check(false), null);
        test.equal(check(1), null);
        test.equal(check(true), null);
        test.equal(check(function() {}), null);
        test.equal(check(''), null);
        test.equal(check('        '), null);
        test.equal(check('cant-end-in-a-'), null);
        test.equal(check('no-!?$-chars'), null);
        test.equal(check('123-cant-start-with-number'), null);

        test.end();
    });

    suite.end();
});<commit_msg>#7 Tests for .checkIsForExamples<commit_after>'use strict';

const path = require('path');
const sinon = require('sinon');
const tap = require('tap');

const utilities = require('../commands/utilities');

let mockCwd;
let mockResolve;

tap.test('.paths', (suite) => {
    suite.beforeEach((done) => {
        mockCwd = sinon.stub(process, 'cwd');
        mockCwd.returns('root');

        mockResolve = sinon.stub(path, 'resolve');
        mockResolve.callsFake(function() {
            return Array.from(arguments).join('/');
        });

        done();
    });

    suite.afterEach((done) => {
        mockCwd.restore();
        mockResolve.restore();
    });

    suite.test('.create should return a method', (test) => {
        test.plan(2);

        const method = utilities.paths.create('make', 'pizza');

        test.equal(typeof method, 'function');
        test.equal(method('large', 'pepperoni'), 'root/make/pizza/large/pepperoni');

        test.end();
    });

    suite.test('.root should return the root path plus any other arguments', (test) => {
        test.plan(1);

        test.equal(
            utilities.paths.root('burger', 'cheese'),
            'root/burger/cheese'
        );

        test.end();
    });

    suite.end();
});

tap.test('#checkIsDashFormat', (suite) => {
    const check = utilities.checkIsDashFormat;

    suite.test('should return false if no value is provided', (test) => {
        test.plan(4);

        test.notOk(check());
        test.notOk(check(null));
        test.notOk(check(0));
        test.notOk(check(false));

        test.end();
    });

    suite.test('should return false if the value is not a string', (test) => {
        test.plan(3);

        test.notOk(check(1));
        test.notOk(check(true));
        test.notOk(check(function() {}));

        test.end();
    });

    suite.test('should return false if the string has no characters', (test) => {
        test.plan(1);

        test.notOk(check(''));

        test.end();
    });

    suite.test('should return false if it is not dash format (no special characters)', (test) => {
        test.plan(4);

        test.notOk(check('        '));
        test.notOk(check('cant-end-in-a-'));
        test.notOk(check('no-!?$-chars'));
        test.notOk(check('123-cant-start-with-number'));

        test.end();
    });

    suite.test('should return true if it is dash format', (test) => {
        test.plan(2);

        test.ok(check('this-is-good'));
        test.ok(check('numbers-12-3-4-work'));

        test.end();
    });

    suite.end();
});

tap.test('#testIsDashFormat', (suite) => {
    const check = utilities.testIsDashFormat;

    suite.test('should return the value if it is dash format', (test) => {
        test.plan(2);

        test.equal(check('this-is-good'), 'this-is-good');
        test.equal(check('this-15-good'), 'this-15-good');

        test.end();
    });

    suite.test('should return null if the value is not dash format', (test) => {
        test.plan(12);

        test.equal(check(), null);
        test.equal(check(null), null);
        test.equal(check(0), null);
        test.equal(check(false), null);
        test.equal(check(1), null);
        test.equal(check(true), null);
        test.equal(check(function() {}), null);
        test.equal(check(''), null);
        test.equal(check('        '), null);
        test.equal(check('cant-end-in-a-'), null);
        test.equal(check('no-!?$-chars'), null);
        test.equal(check('123-cant-start-with-number'), null);

        test.end();
    });

    suite.end();
});

tap.test('#checkIsForExamples', (test) => {
    const check = utilities.checkIsForExamples;

    test.plan(5);

    test.notOk(check({ apple: [], broccoli: [] }));
    test.ok({ example: [] });
    test.ok({ examples: [] });
    test.ok({ x: [] });
    test.ok(check({ apple: [], examples: [] }));

    test.end();
});<|endoftext|>


<commit_before><commit_msg>Updating to IAM<commit_after><|endoftext|>


<commit_before>var React = require('react');
var RouteHandler = require('react-router').RouteHandler;
var CurrentLocation = require('./CurrentLocation');
var SearchBox = require('./SearchBox');
var RouteWindow = require('./Route');

require('leafletCss');
require('ratchet');
require('./css/main.css');

var RouteButton = React.createClass({
  route : function(){
    this.props.setMapMode("route");
  },
  render : function(){
    return(

    );
  }
});

var Main = React.createClass({

  getInitialState: function(){
    return{
      // markerLyaer is being mutated, not the way react recommends
      currentPoint : {
        //hard coded! what will be the best?
        name : "Current location",
        lat: 40.758,
        lon: -73.9174
      },
      startPoint : {
        name : "Choose start location.",
        lat :  40.7410605,
        lon : -73.9896986
      },
      destMarker : {
        name : "Choose destination.",
        lat :  40.7410605,
        lon : -73.9896986
      },
      poiMarkers:[],
      currentLayer : L.layerGroup(),
      markerLayer : L.layerGroup([L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.')]),
      routeLayer : L.layerGroup(),
      mode : "search"
    }

  },
  setStartPoint: function(mrkr){
    this.setState({startPoint:mrkr},function(){
    });
  },

  setCurrentPoint: function(pos){

    var newCurrentLocation = {
      name : "Current location",
      lat: pos.coords.latitude,
      lon: pos.coords.longitude
    }

    this.setState({
      currentPoint : newCurrentLocation,
      startPoint : newCurrentLocation
    },function(){
      var center = L.latLng(pos.coords.latitude,pos.coords.longitude);
      this.state.currentLayer.clearLayers();
      this.state.currentLayer.addLayer(L.circleMarker(center), 3, {
        color: '#00f',
        opacity:1,
        fillColor: '#00f',
        fillOpacity: 0.8,

      });
      this.map.setView(center,14);
      this.setState({
        bbox : this.map.getBounds().toBBoxString()
      });
    });

  },

  addMarker: function(mrkr){

    this.state.markerLayer.clearLayers();
    var marker = L.marker([mrkr.lat,mrkr.lon]);
    //replace not to mutate state directly
    this.state.markerLayer.addLayer(marker);

    this.map.setView(marker.getLatLng(),14);
    this.setState({
      destMarker: mrkr,
      bbox : this.map.getBounds().toBBoxString()
    });
  },
  addPOIMarkers: function(mrkrs){
    //this.state.markerLayer.clearLayers();
    var i;
    var minLat = mrkrs[0].lat;
    var minLon = mrkrs[0].lon;
    var maxLat = mrkrs[0].lat;
    var maxLon = mrkrs[0].lat;

    for(i =0; i<mrkrs.length; i++){
      var marker = new L.marker([mrkrs[i].lat,mrkrs[i].lon]);

      if(mrkrs[i].lat < minLat) minLat = mrkrs[i].lat;
      else maxLat = mrkrs[i].lat;

      if(mrkrs[i].lon < minLon) minLon = mrkrs[i].lon;
      else maxLon = mrkrs[i].lon;
      this.state.markerLayer.addLayer(marker);
    }
    this.map.fitBounds([[minLat,minLon],[maxLat,maxLon]]);
    this.setState({
      bbox : this.map.getBounds().toBBoxString()
    });
  },
  clearMap : function(){
    this.state.markerLayer.clearLayers();
    this.state.currentLayer.clearLayers();
    this.state.routeLayer.clearLayers();
    this.setState({
      startPoint:{},
      destPoint:{}
    });
  },
  addRouteLayer : function(routes){
    this.state.routeLayer.clearLayers();
    var polylineRoute = L.polyline(routes, {color:'red'});
    this.state.routeLayer.addLayer(polylineRoute);
    this.map.fitBounds(polylineRoute.getBounds());
    this.render();
  },
  setMapMode : function(mapMode){
    this.setState({mode:mapMode});
  },
  createMap: function (element) {
    //React.render(<Map lat="40.758" lon="-73.9174" zoom="4" />,document.body);
    var map = L.map(element,{
      zoomControl:false
    });

    // var layer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    //   attribution: '© OpenStreetMap contributors'
    // }).addTo(map);

    //loading scene yaml
     var layer = Tangram.leafletLayer({
         scene: 'https://cdn.rawgit.com/tangrams/carousel/gh-pages/traditional.yaml',//sceneYaml,
         attribution: 'Tangram | © OSM contributors | Mapzen'
     });
    layer.addTo(map);
    return map;
    },

    setupMap: function () {
      this.map.setView([40.758, -73.9174], 12);
      this.setState({
        bbox : this.map.getBounds().toBBoxString()
      });
      this.setMapMode("search");
    },

    componentDidMount: function () {
        if (this.props.createMap) {
            this.map = this.props.createMap(this.getDOMNode());
        } else {
            this.map = this.createMap(document.getElementById('map'));
        }
        this.setupMap();
        this.state.markerLayer.addTo(this.map);
        this.state.currentLayer.addTo(this.map);
        this.state.routeLayer.addTo(this.map);
    },

    render: function () {
      if(this.state.mode == "search"){
      return (

          <SearchBox
            addMarker = {this.addMarker}
            addPOIMarkers = {this.addPOIMarkers}
            bbox = {this.bbox}
            currentPoint = {this.state.currentPoint}/>

          <RouteButton
          destMarker= {this.state.destMarker}
          addRouteLayer = {this.addRouteLayer}
          setMapMode = {this.setMapMode}
          mode = {this.state.mode}/>
          <CurrentLocation
            setCurrentLocation = {this.setCurrentPoint} />
          <RouteHandler />

      );
    }else{
        return(

          <RouteWindow
            startPoint = {this.state.startPoint}
            destPoint = {this.state.destMarker}
            clearMap = {this.clearMap}
            addMarker = {this.addMarker}
            setStartPoint = {this.setStartPoint}
            addRouteLayer = {this.addRouteLayer}
            setMapMode = {this.setMapMode}/>

        );
      }
    }
});

module.exports = Main;
<commit_msg>changed default nyc coord<commit_after>var React = require('react');
var RouteHandler = require('react-router').RouteHandler;
var CurrentLocation = require('./CurrentLocation');
var SearchBox = require('./SearchBox');
var RouteWindow = require('./Route');

require('leafletCss');
require('ratchet');
require('./css/main.css');

var RouteButton = React.createClass({
  route : function(){
    this.props.setMapMode("route");
  },
  render : function(){
    return(

    );
  }
});

var Main = React.createClass({

  getInitialState: function(){
    return{
      // markerLyaer is being mutated, not the way react recommends
      currentPoint : {
        //hard coded! what will be the best?
        name : "Current location",
        lat: 40.728,
        lon: -73.99
      },
      startPoint : {
        name : "Choose start location.",
        lat :  40.7410605,
        lon : -73.9896986
      },
      destMarker : {
        name : "Choose destination.",
        lat :  40.7410605,
        lon : -73.9896986
      },
      poiMarkers:[],
      currentLayer : L.layerGroup(),
      markerLayer : L.layerGroup([L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.')]),
      routeLayer : L.layerGroup(),
      mode : "search"
    }

  },
  setStartPoint: function(mrkr){
    this.setState({startPoint:mrkr},function(){
    });
  },

  setCurrentPoint: function(pos){

    var newCurrentLocation = {
      name : "Current location",
      lat: pos.coords.latitude,
      lon: pos.coords.longitude
    }

    this.setState({
      currentPoint : newCurrentLocation,
      startPoint : newCurrentLocation
    },function(){
      var center = L.latLng(pos.coords.latitude,pos.coords.longitude);
      this.state.currentLayer.clearLayers();
      this.state.currentLayer.addLayer(L.circleMarker(center), 3, {
        color: '#00f',
        opacity:1,
        fillColor: '#00f',
        fillOpacity: 0.8,

      });
      this.map.setView(center,14);
      this.setState({
        bbox : this.map.getBounds().toBBoxString()
      });
    });

  },

  addMarker: function(mrkr){

    this.state.markerLayer.clearLayers();
    var marker = L.marker([mrkr.lat,mrkr.lon]);
    //replace not to mutate state directly
    this.state.markerLayer.addLayer(marker);

    this.map.setView(marker.getLatLng(),14);
    this.setState({
      destMarker: mrkr,
      bbox : this.map.getBounds().toBBoxString()
    });
  },
  addPOIMarkers: function(mrkrs){
    //this.state.markerLayer.clearLayers();
    var i;
    var minLat = mrkrs[0].lat;
    var minLon = mrkrs[0].lon;
    var maxLat = mrkrs[0].lat;
    var maxLon = mrkrs[0].lat;

    for(i =0; i<mrkrs.length; i++){
      var marker = new L.marker([mrkrs[i].lat,mrkrs[i].lon]);

      if(mrkrs[i].lat < minLat) minLat = mrkrs[i].lat;
      else maxLat = mrkrs[i].lat;

      if(mrkrs[i].lon < minLon) minLon = mrkrs[i].lon;
      else maxLon = mrkrs[i].lon;
      this.state.markerLayer.addLayer(marker);
    }
    this.map.fitBounds([[minLat,minLon],[maxLat,maxLon]]);
    this.setState({
      bbox : this.map.getBounds().toBBoxString()
    });
  },
  clearMap : function(){
    this.state.markerLayer.clearLayers();
    this.state.currentLayer.clearLayers();
    this.state.routeLayer.clearLayers();
    this.setState({
      startPoint:{},
      destPoint:{}
    });
  },
  addRouteLayer : function(routes){
    this.state.routeLayer.clearLayers();
    var polylineRoute = L.polyline(routes, {color:'red'});
    this.state.routeLayer.addLayer(polylineRoute);
    this.map.fitBounds(polylineRoute.getBounds());
    this.render();
  },
  setMapMode : function(mapMode){
    this.setState({mode:mapMode});
  },
  createMap: function (element) {
    //React.render(<Map lat="40.758" lon="-73.9174" zoom="4" />,document.body);
    var map = L.map(element,{
      zoomControl:false
    });

    // var layer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    //   attribution: '© OpenStreetMap contributors'
    // }).addTo(map);

    //loading scene yaml
     var layer = Tangram.leafletLayer({
         scene: 'https://cdn.rawgit.com/tangrams/carousel/gh-pages/traditional.yaml',//sceneYaml,
         attribution: 'Tangram | © OSM contributors | Mapzen'
     });
    layer.addTo(map);
    return map;
    },

    setupMap: function () {
      this.map.setView([40.728, -73.99], 12);
      this.setState({
        bbox : this.map.getBounds().toBBoxString()
      });
      this.setMapMode("search");
    },

    componentDidMount: function () {
        if (this.props.createMap) {
            this.map = this.props.createMap(this.getDOMNode());
        } else {
            this.map = this.createMap(document.getElementById('map'));
        }
        this.setupMap();
        this.state.markerLayer.addTo(this.map);
        this.state.currentLayer.addTo(this.map);
        this.state.routeLayer.addTo(this.map);
    },

    render: function () {
      if(this.state.mode == "search"){
      return (

          <SearchBox
            addMarker = {this.addMarker}
            addPOIMarkers = {this.addPOIMarkers}
            bbox = {this.bbox}
            currentPoint = {this.state.currentPoint}/>

          <RouteButton
          destMarker= {this.state.destMarker}
          addRouteLayer = {this.addRouteLayer}
          setMapMode = {this.setMapMode}
          mode = {this.state.mode}/>
          <CurrentLocation
            setCurrentLocation = {this.setCurrentPoint} />
          <RouteHandler />

      );
    }else{
        return(

          <RouteWindow
            startPoint = {this.state.startPoint}
            destPoint = {this.state.destMarker}
            clearMap = {this.clearMap}
            addMarker = {this.addMarker}
            setStartPoint = {this.setStartPoint}
            addRouteLayer = {this.addRouteLayer}
            setMapMode = {this.setMapMode}/>

        );
      }
    }
});

module.exports = Main;
<|endoftext|>


<commit_before>/**
 * All this does is add a Date.getTimezone() which makes
 *  a guess at the timezone.  That's all.  Uses [some] Olson
 *  zone data.  Works mostly.
 */
(function(Date) {
	Date.prototype.getTimezone = function() {
		var timezones = {
		//  "OFFSET:DST_AMOUNT:DST_START": "TIMEZONE_ID
			"-39600:0:0":"Pacific/Midway",
			"-36000:3600:1331467200":"America/Adak",
			"-36000:0:0":"Pacific/Honolulu",
			"-34200:0:0":"Pacific/Marquesas",
			"-32400:3600:1331463600":"America/Juneau",
			"-32400:0:0":"Pacific/Gambier",
			"-28800:3600:1333274400":"America/Santa_Isabel",
			"-28800:3600:1331460000":"America/Los_Angeles",
			"-28800:0:0":"America/Metlakatla",
			"-25200:3600:1333270800":"America/Chihuahua",
			"-25200:3600:1331456400":"America/Denver",
			"-25200:0:0":"America/Phoenix",
			"-21600:3600:1333267200":"America/Mexico_City",
			"-21600:3600:1331452800":"America/Chicago",
			"-21600:0:0":"America/Guatemala",
			"-18000:3600:1331449200":"America/New_York",
			"-18000:3600:1331442000":"America/Havana",
			"-18000:0:0":"America/Cayman",
			"-18000:-3600:1331434800":"Pacific/Easter",
			"-16200:0:0":"America/Caracas",
			"-14400:3600:1331445600":"Atlantic/Bermuda",
			"-14400:0:0":"America/Puerto_Rico",
			"-12600:3600:1331443800":"America/St_Johns",
			"-10800:3600:1332637200":"America/Godthab",
			"-10800:3600:1331442000":"America/Miquelon",
			"-10800:0:0":"America/Fortaleza",
			"-10800:-3600:1334466000":"Atlantic/Stanley",
			"-10800:-3600:1333854000":"America/Asuncion",
			"-10800:-3600:1331434800":"America/Santiago",
			"-10800:-3600:1330225200":"America/Campo_Grande",
			"-7200:0:0":"America/Noronha",
			"-7200:-3600:1331438400":"America/Montevideo",
			"-7200:-3600:1330221600":"America/Bahia",
			"-3600:3600:1332637200":"America/Scoresbysund",
			"-3600:0:0":"Atlantic/Cape_Verde",
			"0:0:0":"UTC",
			"0:3600:1332637200":"Europe/London",
			"3600:0:0":"Africa/Algiers",
			"3600:3600:1332637200":"Europe/Stockholm",
			"7200:-3600:1333238400":"Africa/Windhoek",
			"7200:0:0":"Africa/Cairo",
			"7200:3600:1332626400":"Asia/Beirut",
			"7200:3600:1332637200":"Europe/Kiev",
			"7200:3600:1333058400":"Asia/Amman",
			"7200:3600:1333065600":"Asia/Jerusalem",
			"7200:3600:1333663200":"Asia/Damascus",
			"10800:0:0":"Africa/Nairobi",
			"12600:3600:1332275400":"Asia/Tehran",
			"14400:0:0":"Asia/Dubai",
			"14400:3600:1332626400":"Asia/Yerevan",
			"14400:3600:1332633600":"Asia/Baku",
			"16200:0:0":"Asia/Kabul",
			"18000:0:0":"Asia/Karachi",
			"19800:0:0":"Asia/Colombo",
			"20700:0:0":"Asia/Kathmandu",
			"21600:0:0":"Asia/Dhaka",
			"23400:0:0":"Asia/Rangoon",
			"25200:0:0":"Asia/Bangkok",
			"28800:0:0":"Asia/Hong_Kong",
			"31500:0:0":"Australia/Eucla",
			"32400:0:0":"Asia/Tokyo",
			"34200:0:0":"Australia/Darwin",
			"36000:0:0":"Australia/Brisbane",
			"37800:-3600:1333211400":"Australia/Broken_Hill",
			"39600:-1800:1333206000":"Australia/Lord_Howe",
			"39600:-3600:1333209600":"Australia/Sydney",
			"39600:0:0":"Pacific/Pohnpei",
			"41400:0:0":"Pacific/Norfolk",
			"43200:0:0":"Asia/Anadyr",
			"46800:-3600:1327154400":"Pacific/Fiji",
			"46800:-3600:1333202400":"Antarctica/South_Pole",
			"46800:0:0":"Pacific/Enderbury",
			"49500:-3600:1333202400":"Pacific/Chatham",
			"50400:-3600:1333202400":"Pacific/Apia",
			"50400:0:0":"Pacific/Kiritimati",
		};

		var getJanuaryTimezoneOffset = function() {
			return new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0).getTimezoneOffset() * -60;
		}

		var getJuneTimezoneOffset = function() {
			return new Date(new Date().getFullYear(), 5, 1, 0, 0, 0, 0).getTimezoneOffset() * -60;
		}

		var getDSTOffset = function() {
			return getJuneTimezoneOffset() - getJanuaryTimezoneOffset();
		}

		var tzKey = getJanuaryTimezoneOffset() + ':' + getDSTOffset();

		for (var a in timezones) {
			if (a.indexOf(tzKey) != 0)
				continue;

			var tzInfo = a.split(':');

			if (tzInfo[1] == 0)
				return timezones[a];

			var before = new Date();
			before.setTime((parseInt(tzInfo[2]) - 1) * 1000);

			var after = new Date();
			after.setTime(parseInt(tzInfo[2]) * 1000);

			if (before.getTimezoneOffset() != after.getTimezoneOffset())
				return timezones[a];
		}

		return null;
	}
})(Date);
<commit_msg>move timezones object and related internal functions out of the prototype so they aren't generated again every time<commit_after>/**
 * All this does is add a Date.getTimezone() which makes
 *  a guess at the timezone.  That's all.  Uses [some] Olson
 *  zone data.  Works mostly.
 */
(function(Date) {
	//  "OFFSET:DST_AMOUNT:DST_START": "TIMEZONE_ID
	var timezones = {
		"-39600:0:0":"Pacific/Midway",
		"-36000:3600:1331467200":"America/Adak",
		"-36000:0:0":"Pacific/Honolulu",
		"-34200:0:0":"Pacific/Marquesas",
		"-32400:3600:1331463600":"America/Juneau",
		"-32400:0:0":"Pacific/Gambier",
		"-28800:3600:1333274400":"America/Santa_Isabel",
		"-28800:3600:1331460000":"America/Los_Angeles",
		"-28800:0:0":"America/Metlakatla",
		"-25200:3600:1333270800":"America/Chihuahua",
		"-25200:3600:1331456400":"America/Denver",
		"-25200:0:0":"America/Phoenix",
		"-21600:3600:1333267200":"America/Mexico_City",
		"-21600:3600:1331452800":"America/Chicago",
		"-21600:0:0":"America/Guatemala",
		"-18000:3600:1331449200":"America/New_York",
		"-18000:3600:1331442000":"America/Havana",
		"-18000:0:0":"America/Cayman",
		"-18000:-3600:1331434800":"Pacific/Easter",
		"-16200:0:0":"America/Caracas",
		"-14400:3600:1331445600":"Atlantic/Bermuda",
		"-14400:0:0":"America/Puerto_Rico",
		"-12600:3600:1331443800":"America/St_Johns",
		"-10800:3600:1332637200":"America/Godthab",
		"-10800:3600:1331442000":"America/Miquelon",
		"-10800:0:0":"America/Fortaleza",
		"-10800:-3600:1334466000":"Atlantic/Stanley",
		"-10800:-3600:1333854000":"America/Asuncion",
		"-10800:-3600:1331434800":"America/Santiago",
		"-10800:-3600:1330225200":"America/Campo_Grande",
		"-7200:0:0":"America/Noronha",
		"-7200:-3600:1331438400":"America/Montevideo",
		"-7200:-3600:1330221600":"America/Bahia",
		"-3600:3600:1332637200":"America/Scoresbysund",
		"-3600:0:0":"Atlantic/Cape_Verde",
		"0:0:0":"UTC",
		"0:3600:1332637200":"Europe/London",
		"3600:0:0":"Africa/Algiers",
		"3600:3600:1332637200":"Europe/Stockholm",
		"7200:-3600:1333238400":"Africa/Windhoek",
		"7200:0:0":"Africa/Cairo",
		"7200:3600:1332626400":"Asia/Beirut",
		"7200:3600:1332637200":"Europe/Kiev",
		"7200:3600:1333058400":"Asia/Amman",
		"7200:3600:1333065600":"Asia/Jerusalem",
		"7200:3600:1333663200":"Asia/Damascus",
		"10800:0:0":"Africa/Nairobi",
		"12600:3600:1332275400":"Asia/Tehran",
		"14400:0:0":"Asia/Dubai",
		"14400:3600:1332626400":"Asia/Yerevan",
		"14400:3600:1332633600":"Asia/Baku",
		"16200:0:0":"Asia/Kabul",
		"18000:0:0":"Asia/Karachi",
		"19800:0:0":"Asia/Colombo",
		"20700:0:0":"Asia/Kathmandu",
		"21600:0:0":"Asia/Dhaka",
		"23400:0:0":"Asia/Rangoon",
		"25200:0:0":"Asia/Bangkok",
		"28800:0:0":"Asia/Hong_Kong",
		"31500:0:0":"Australia/Eucla",
		"32400:0:0":"Asia/Tokyo",
		"34200:0:0":"Australia/Darwin",
		"36000:0:0":"Australia/Brisbane",
		"37800:-3600:1333211400":"Australia/Broken_Hill",
		"39600:-1800:1333206000":"Australia/Lord_Howe",
		"39600:-3600:1333209600":"Australia/Sydney",
		"39600:0:0":"Pacific/Pohnpei",
		"41400:0:0":"Pacific/Norfolk",
		"43200:0:0":"Asia/Anadyr",
		"46800:-3600:1327154400":"Pacific/Fiji",
		"46800:-3600:1333202400":"Antarctica/South_Pole",
		"46800:0:0":"Pacific/Enderbury",
		"49500:-3600:1333202400":"Pacific/Chatham",
		"50400:-3600:1333202400":"Pacific/Apia",
		"50400:0:0":"Pacific/Kiritimati",
	};

	var getJanuaryTimezoneOffset = function() {
		return new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0).getTimezoneOffset() * -60;
	};

	var getJuneTimezoneOffset = function() {
		return new Date(new Date().getFullYear(), 5, 1, 0, 0, 0, 0).getTimezoneOffset() * -60;
	};

	Date.prototype.getTimezone = function() {
		var savingsOffset = getJuneTimezoneOffset() - getJanuaryTimezoneOffset()

		var tzKey = getJanuaryTimezoneOffset() + ':' + savingsOffset;

		for (var a in timezones) {
			if (a.indexOf(tzKey) != 0)
				continue;

			var tzInfo = a.split(':');

			if (tzInfo[1] == 0)
				return timezones[a];

			var before = new Date();
			before.setTime((parseInt(tzInfo[2]) - 1) * 1000);

			var after = new Date();
			after.setTime(parseInt(tzInfo[2]) * 1000);

			if (before.getTimezoneOffset() != after.getTimezoneOffset())
				return timezones[a];
		}

		return null;
	}
})(Date);
<|endoftext|>


<commit_before>"use strict";
/*jshint mocha: true*/
/*eslint-env mocha*/
/*global assert*/

/*eslint-disable max-nested-callbacks*/

describe("attributes", function () {

    var
        TestAttribute = gpf.define("TestAttribute", "gpf.attributes.Attribute"),
        Test1ValueAttribute = gpf.define("Test1ValueAttribute", TestAttribute),
        Test2ValueAttribute = gpf.define("Test2ValueAttribute", TestAttribute),

        A = gpf.define("A", {
            protected: {

                "[_a]": [new Test1ValueAttribute()],
                _a: 0,

                "[_c]": [new Test1ValueAttribute()],
                _c: 0

            },
            public: {

                constructor: function (value) {
                    this._a = value;
                },

                a: function () {
                    return this._a;
                }

            }
        }),

        a = new A(),

        B = gpf.define("B", A, {
            protected: {

                "[_b]": [new Test2ValueAttribute()],
                _b: 0,

                "[_c]": [new Test2ValueAttribute()],
                _c: 0

            },
            public: {

                constructor: function (value) {
                    this._super(value - 1);
                    this._b = value;
                },

                b: function () {
                    return this._b;
                }
            }
        }),

        b = new B();

    describe("gpf.attributes.Attribute", function () {

        it("is available through gpf.attributes.Map", function () {
            var attributes = new gpf.attributes.Map(a);
            assert(2 === attributes.getCount());
            assert(1 === attributes.getMemberAttributes("_a").getItemsCount());
            assert(0 === attributes.getMemberAttributes("_b").getItemsCount());
            assert(1 === attributes.getMemberAttributes("_c").getItemsCount());
        });

        it("inherits from base class", function () {
            var attributes = new gpf.attributes.Map(b);
            assert(4 === attributes.getCount());
            assert(1 === attributes.getMemberAttributes("_a").getItemsCount());
            assert(1 === attributes.getMemberAttributes("_b").getItemsCount());
            assert(2 === attributes.getMemberAttributes("_c").getItemsCount());
        });

        it("signals any use on non-existing member", function () {
            var caught = null;
            console.expects("error", "gpf.define: Invalid attribute name '_b'");
            try {
                gpf.define("C", A, {
                    "[_b]": [new Test1ValueAttribute()] // should fail
                });
            } catch (e) {
                caught = e;
            }
            assert(null === caught);
        });

    });

    describe("gpf.attributes.Array", function () {

        it("allows to test the presence of an attribute", function () {
            var attributes = new gpf.attributes.Map(a),
                attributesForA = attributes.getMemberAttributes("_a");
            assert(1 === attributesForA.getItemsCount());
            assert(true === attributesForA.has(Test1ValueAttribute));
            assert(false === attributesForA.has(Test2ValueAttribute));
        });

        it("filters on attribute type", function () {
            var attributes = new gpf.attributes.Map(b),
                attributesForC = attributes.getMemberAttributes("_c"),
                test1ValueAttributesForC = attributesForC.filter(Test1ValueAttribute),
                test2ValueAttributesForC = attributesForC.filter(Test2ValueAttribute);
            assert(2 === attributesForC.getItemsCount());
            assert(true === test1ValueAttributesForC.has(Test1ValueAttribute));
            assert(false === test1ValueAttributesForC.has(Test2ValueAttribute));
            assert(false === test2ValueAttributesForC.has(Test1ValueAttribute));
            assert(true === test2ValueAttributesForC.has(Test2ValueAttribute));
        });

        it("offers an enumeration function based on [].forEach", function () {
            var attributes = new gpf.attributes.Map(b),
                attributesForC = attributes.getMemberAttributes("_c"),
                dictionaryOfAttributesForC = {},
                result = attributesForC.forEach(function (attribute, idx, array) {
                    assert("number" === typeof idx);
                    assert(attribute instanceof gpf.attributes.Attribute);
                    assert(array instanceof Array);
                    assert(2 === array.length);
                    dictionaryOfAttributesForC[attribute.constructor.compatibleName()] = [attribute];
                });
            assert(undefined === result);
            assert(1 === dictionaryOfAttributesForC.Test1ValueAttribute.length);
            assert(1 === dictionaryOfAttributesForC.Test2ValueAttribute.length);
        });

        it("offers an enumeration function based on [].every", function () {
            var attributes = new gpf.attributes.Map(b),
                attributesForC = attributes.getMemberAttributes("_c"),
                selectedAttribute,
                result = attributesForC.every(function (attribute, idx, array) {
                    assert("number" === typeof idx);
                    assert(2 === array.length);
                    selectedAttribute = attribute;
                    return !(attribute instanceof Test1ValueAttribute);
                });
            assert(false === result);
            assert(selectedAttribute instanceof Test1ValueAttribute);
        });

    });

    describe("gpf.attributes.Map", function () {

        it("lists members that have attributes", function () {
            var attributes = new gpf.attributes.Map(a),
                members = attributes.getMembers();
            assert(2 === members.length);
            // Order is not guaranteed
            assert(undefined !== gpf.test(members, "_a"));
            assert(undefined !== gpf.test(members, "_c"));
        });

        it("filters on attribute type", function () {
            var attributes = new gpf.attributes.Map(b),
                attributesTest2Value = attributes.filter(Test2ValueAttribute);
            assert(2 === attributesTest2Value.getCount());
            assert(1 === attributesTest2Value.getMemberAttributes("_c").getItemsCount());
        });

        it("offers an enumeration function based on [].forEach", function () {
            var attributes = new gpf.attributes.Map(a),
                members = [],
                result = attributes.forEach(function (attributeArray, member, dictionary) {
                    assert("string" === typeof member);
                    assert(attributeArray instanceof gpf.attributes.Array);
                    assert(null !== dictionary);
                    members.push(member);
                });
            assert(undefined === result);
            assert(2 === members.length);
            // Order is not guaranteed
            assert(undefined !== gpf.test(members, "_a"));
            assert(undefined !== gpf.test(members, "_c"));
        });

        it("is modifiable without altering initial list", function () {
            var attributes = new gpf.attributes.Map(a),
                attributesForA,
                attributes2;
            attributes.add("_a", new Test2ValueAttribute());
            assert(3 === attributes.getCount());
            attributesForA = attributes.getMemberAttributes("_a");
            assert(2 === attributesForA.getItemsCount());
            attributes2 = new gpf.attributes.Map(a);
            assert(2 === attributes2.getCount());
            attributesForA = attributes2.getMemberAttributes("_a");
            assert(1 === attributesForA.getItemsCount());
        });

    });

});
<commit_msg>ESLint fixes<commit_after>"use strict";
/*jshint mocha: true*/
/*eslint-env mocha*/
/*global assert*/

/*eslint-disable max-nested-callbacks*/

describe("attributes", function () {

    var
        TestAttribute = gpf.define("TestAttribute", "gpf.attributes.Attribute"),
        Test1ValueAttribute = gpf.define("Test1ValueAttribute", TestAttribute),
        Test2ValueAttribute = gpf.define("Test2ValueAttribute", TestAttribute),

        A = gpf.define("A", {
            "protected": {

                "[_a]": [new Test1ValueAttribute()],
                _a: 0,

                "[_c]": [new Test1ValueAttribute()],
                _c: 0

            },
            "public": {

                constructor: function (value) {
                    this._a = value;
                },

                a: function () {
                    return this._a;
                }

            }
        }),

        a = new A(),

        B = gpf.define("B", A, {
            "protected": {

                "[_b]": [new Test2ValueAttribute()],
                _b: 0,

                "[_c]": [new Test2ValueAttribute()],
                _c: 0

            },
            "public": {

                constructor: function (value) {
                    this._super(value - 1);
                    this._b = value;
                },

                b: function () {
                    return this._b;
                }
            }
        }),

        b = new B();

    describe("gpf.attributes.Attribute", function () {

        it("is available through gpf.attributes.Map", function () {
            var attributes = new gpf.attributes.Map(a);
            assert(2 === attributes.getCount());
            assert(1 === attributes.getMemberAttributes("_a").getItemsCount());
            assert(0 === attributes.getMemberAttributes("_b").getItemsCount());
            assert(1 === attributes.getMemberAttributes("_c").getItemsCount());
        });

        it("inherits from base class", function () {
            var attributes = new gpf.attributes.Map(b);
            assert(4 === attributes.getCount());
            assert(1 === attributes.getMemberAttributes("_a").getItemsCount());
            assert(1 === attributes.getMemberAttributes("_b").getItemsCount());
            assert(2 === attributes.getMemberAttributes("_c").getItemsCount());
        });

        it("signals any use on non-existing member", function () {
            var caught = null;
            console.expects("error", "gpf.define: Invalid attribute name '_b'");
            try {
                gpf.define("C", A, {
                    "[_b]": [new Test1ValueAttribute()] // should fail
                });
            } catch (e) {
                caught = e;
            }
            assert(null === caught);
        });

    });

    describe("gpf.attributes.Array", function () {

        it("allows to test the presence of an attribute", function () {
            var attributes = new gpf.attributes.Map(a),
                attributesForA = attributes.getMemberAttributes("_a");
            assert(1 === attributesForA.getItemsCount());
            assert(true === attributesForA.has(Test1ValueAttribute));
            assert(false === attributesForA.has(Test2ValueAttribute));
        });

        it("filters on attribute type", function () {
            var attributes = new gpf.attributes.Map(b),
                attributesForC = attributes.getMemberAttributes("_c"),
                test1ValueAttributesForC = attributesForC.filter(Test1ValueAttribute),
                test2ValueAttributesForC = attributesForC.filter(Test2ValueAttribute);
            assert(2 === attributesForC.getItemsCount());
            assert(true === test1ValueAttributesForC.has(Test1ValueAttribute));
            assert(false === test1ValueAttributesForC.has(Test2ValueAttribute));
            assert(false === test2ValueAttributesForC.has(Test1ValueAttribute));
            assert(true === test2ValueAttributesForC.has(Test2ValueAttribute));
        });

        it("offers an enumeration function based on [].forEach", function () {
            var attributes = new gpf.attributes.Map(b),
                attributesForC = attributes.getMemberAttributes("_c"),
                dictionaryOfAttributesForC = {},
                result = attributesForC.forEach(function (attribute, idx, array) {
                    assert("number" === typeof idx);
                    assert(attribute instanceof gpf.attributes.Attribute);
                    assert(array instanceof Array);
                    assert(2 === array.length);
                    dictionaryOfAttributesForC[attribute.constructor.compatibleName()] = [attribute];
                });
            assert(undefined === result);
            assert(1 === dictionaryOfAttributesForC.Test1ValueAttribute.length);
            assert(1 === dictionaryOfAttributesForC.Test2ValueAttribute.length);
        });

        it("offers an enumeration function based on [].every", function () {
            var attributes = new gpf.attributes.Map(b),
                attributesForC = attributes.getMemberAttributes("_c"),
                selectedAttribute,
                result = attributesForC.every(function (attribute, idx, array) {
                    assert("number" === typeof idx);
                    assert(2 === array.length);
                    selectedAttribute = attribute;
                    return !(attribute instanceof Test1ValueAttribute);
                });
            assert(false === result);
            assert(selectedAttribute instanceof Test1ValueAttribute);
        });

    });

    describe("gpf.attributes.Map", function () {

        it("lists members that have attributes", function () {
            var attributes = new gpf.attributes.Map(a),
                members = attributes.getMembers();
            assert(2 === members.length);
            // Order is not guaranteed
            assert(undefined !== gpf.test(members, "_a"));
            assert(undefined !== gpf.test(members, "_c"));
        });

        it("filters on attribute type", function () {
            var attributes = new gpf.attributes.Map(b),
                attributesTest2Value = attributes.filter(Test2ValueAttribute);
            assert(2 === attributesTest2Value.getCount());
            assert(1 === attributesTest2Value.getMemberAttributes("_c").getItemsCount());
        });

        it("offers an enumeration function based on [].forEach", function () {
            var attributes = new gpf.attributes.Map(a),
                members = [],
                result = attributes.forEach(function (attributeArray, member, dictionary) {
                    assert("string" === typeof member);
                    assert(attributeArray instanceof gpf.attributes.Array);
                    assert(null !== dictionary);
                    members.push(member);
                });
            assert(undefined === result);
            assert(2 === members.length);
            // Order is not guaranteed
            assert(undefined !== gpf.test(members, "_a"));
            assert(undefined !== gpf.test(members, "_c"));
        });

        it("is modifiable without altering initial list", function () {
            var attributes = new gpf.attributes.Map(a),
                attributesForA,
                attributes2;
            attributes.add("_a", new Test2ValueAttribute());
            assert(3 === attributes.getCount());
            attributesForA = attributes.getMemberAttributes("_a");
            assert(2 === attributesForA.getItemsCount());
            attributes2 = new gpf.attributes.Map(a);
            assert(2 === attributes2.getCount());
            attributesForA = attributes2.getMemberAttributes("_a");
            assert(1 === attributesForA.getItemsCount());
        });

    });

});
<|endoftext|>


<commit_before>'use strict'

const tap = require('tap')
const utilities = require('../lib/components/utilities')

tap.test('Utility functions', t => {
  t.beforeEach((done, t) => {
    done()
  })

  t.afterEach((done, t) => {
    done()
  })

  t.test('parseDistinguishedName', t => {
    t.test('handling commas which are no component separators inside DNs', t => {
      const input = 'CN=Doe\\, John (Test),OU=Technicians,OU=Users,OU=Local Resources,OU=DEDUS,DC=abc,DC=dom'
      const output = utilities.parseDistinguishedName(input)
      t.equal(output, 'CN=Doe\\\\, John \\\\28Test\\\\29,OU=Technicians,OU=Users,OU=Local Resources,OU=DEDUS,DC=abc,DC=dom')
      t.end()
    })

    t.test('characters to be escaped inside DNs', t => {
      const input = 'CN= Max Mustermann*,OU=Test (12345),OU=Users,OU=Local Resources,OU=DEDUS,DC=abc,DC=dom'
      const output = utilities.parseDistinguishedName(input)
      t.equal(output, 'CN=\\ Max Mustermann\\\\2A,OU=Test \\\\2812345\\\\29,OU=Users,OU=Local Resources,OU=DEDUS,DC=abc,DC=dom')
      t.end()
    })

    t.end()
  })

  t.end()
})
<commit_msg>Remove unnecessary code from utilities.test.js<commit_after>'use strict'

const tap = require('tap')
const utilities = require('../lib/components/utilities')

tap.test('Utility functions', t => {
  t.test('parseDistinguishedName', t => {
    t.test('handling commas which are no component separators inside DNs', t => {
      const input = 'CN=Doe\\, John (Test),OU=Technicians,OU=Users,OU=Local Resources,OU=DEDUS,DC=abc,DC=dom'
      const output = utilities.parseDistinguishedName(input)
      t.equal(output, 'CN=Doe\\\\, John \\\\28Test\\\\29,OU=Technicians,OU=Users,OU=Local Resources,OU=DEDUS,DC=abc,DC=dom')
      t.end()
    })

    t.test('characters to be escaped inside DNs', t => {
      const input = 'CN= Max Mustermann*,OU=Test (12345),OU=Users,OU=Local Resources,OU=DEDUS,DC=abc,DC=dom'
      const output = utilities.parseDistinguishedName(input)
      t.equal(output, 'CN=\\ Max Mustermann\\\\2A,OU=Test \\\\2812345\\\\29,OU=Users,OU=Local Resources,OU=DEDUS,DC=abc,DC=dom')
      t.end()
    })

    t.end()
  })

  t.end()
})
<|endoftext|>


<commit_before>function cancelDefault (e) {
  e.preventDefault()
  e.stopPropagation()
}

let allA = Array.from(document.querySelectorAll('a'))

const checkDupes = test => allA.find(a => a.innerText.replace('/', '') === test)

function rpcFs (call, args, cb) {
  args = args.map(a => a.startsWith('/') ? a.slice(1) : a)
  args = args.map(a => window.location.pathname + a)

  const xhr = new window.XMLHttpRequest()
  xhr.open('POST', window.location.origin + '/rpc/')
  xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
  xhr.send(JSON.stringify({call, args}))
  xhr.onload = cb
}

const mkdirCall = (path, cb) => rpcFs('mkdirp', [path], cb)

// const rmCall = (path, cb) => rpcFs('remove', [path], cb)

// const mvCall = (path1, path2, cb) => rpcFs('move', [path1, path2], cb)

function mkdir () {
  const folder = window.prompt('New folder name', '')

  if (!folder) {
    return
  } else if (checkDupes(folder)) {
    return window.alert('Name already already exists')
  }

  mkdirCall(folder, () => browseTo(window.location.href))
}

function warning (e) {
  return 'Leaving will interrupt transfer\nAre you sure you want to leave?'
}

function newBar (name) {
  const id = Math.random().toString(36).substring(7)

  document.getElementById('progressBars').innerHTML += `

       ${name.split('/').pop()}

1%

  `
  return id
}

function updatePercent (id, percent) {
  const el = document.getElementById(id).querySelectorAll('div.barForeground')[0]
  const width = Math.floor(100 * percent).toString() + '%'
  el.innerText = width
  el.style.width = width
}

function shouldRefresh () {
  totalDone += 1
  if (totalUploads === totalDone) {
    window.onbeforeunload = null
    console.log('Done uploading ' + totalDone + ' files')
    totalDone = 0
    totalUploads = 0
    document.getElementById('progressBars').innerHTML = ''
    browseTo(window.location.href)
  }
}

function postFile (file, path) {
  totalUploads += 1
  window.onbeforeunload = warning

  const xhr = new window.XMLHttpRequest()
  xhr.open('POST', window.location.origin + '/post' + path)
  xhr.upload.id = newBar(path + '/' + file.name)

  const formData = new window.FormData()
  formData.append(file.name, file)

  xhr.upload.addEventListener('progress', a => {
    updatePercent(a.target.id, a.loaded / a.total)
  })

  xhr.upload.addEventListener('load', shouldRefresh)

  xhr.send(formData)
}

const parseDomFolder = f => {
  f.createReader().readEntries(e => e.forEach(i => parseDomItem(i)))
}

function parseDomItem (domFile, shoudCheckDupes) {
  if (shoudCheckDupes && checkDupes(domFile.name)) {
    return window.alert(domFile.name + ' already exists !')
  }

  if (domFile.isFile) {
    domFile.file(f => postFile(f, domFile.fullPath || domFile.name))
  } else {
    mkdirCall(domFile.fullPath, () => parseDomFolder(domFile))
  }
}

function pushEntry (entry) {
  if (!entry.webkitGetAsEntry && !entry.getAsEntry) {
    return window.alert('Unsupported browser ! Please update to chrome/firefox.')
  } else {
    entry = entry.webkitGetAsEntry() || entry.getAsEntry()
  }

  parseDomItem(entry, true)
}

const upGrid = document.getElementById('drop-grid')

document.ondragenter = (e) => {
  if (isPicMode()) { return }
  cancelDefault(e)
  e.dataTransfer.dropEffect = 'copy'
  upGrid.style.display = 'flex'
}

upGrid.ondragleave = (e) => {
  cancelDefault(e)
  upGrid.style.display = 'none'
}

document.ondragover = (e) => {
  cancelDefault(e)
  return false
}

document.ondrop = (e) => {
  cancelDefault(e)
  upGrid.style.display = 'none'

  Array.from(e.dataTransfer.items).forEach(pushEntry)
  return false
}

let totalUploads = 0
let totalDone = 0

const getArrowSelected = () => document.querySelectorAll('i.arrow-selected')[0]

function getASelected () {
  const dest = getArrowSelected()
  return !dest ? false : dest.parentElement.parentElement.querySelectorAll('a')[0]
}

function scrollToArrow () {
  const pos = getArrowSelected().getBoundingClientRect()
  window.scrollTo(0, pos.y)
}

function clearArrowSelected () {
  const arr = getArrowSelected()
  if (!arr) { return }
  arr.classList.remove('arrow-selected')
}

function restoreCursorPos () {
  clearArrowSelected()
  const hrefSelected = window.localStorage.getItem('last-selected' + window.location.href)
  let a = allA.find(el => el.href === hrefSelected)

  if (!a) {
    if (allA[0].innerText === '../') {
      a = allA[1]
    } else {
      a = allA[0]
    }
  }

  const icon = a.parentElement.parentElement.querySelectorAll('.arrow-icon')[0]
  icon.classList.add('arrow-selected')
  scrollToArrow()
}

const storeLastArrowSrc = src => window.localStorage.setItem('last-selected' + window.location.href, src)

function moveArrow (down) {
  const all = Array.from(document.querySelectorAll('i.arrow-icon'))
  let i = all.findIndex(el => el.classList.contains('arrow-selected'))

  clearArrowSelected()

  if (down) {
    i = all[i + 1] ? i + 1 : 0
  } else {
    i = all[i - 1] ? i - 1 : all.length - 1
  }

  all[i].classList.add('arrow-selected')
  storeLastArrowSrc(getASelected().href)

  const itemPos = all[i].getBoundingClientRect()

  if (i === 0) {
    window.scrollTo(0, 0)
  } else if (i === all.length - 1) {
    window.scrollTo(0, document.documentElement.scrollHeight)
  } else if (itemPos.top < 0) {
    window.scrollBy(0, -200)
  } else if (itemPos.bottom > window.innerHeight) {
    window.scrollBy(0, 200)
  }
}

function setCursorToClosest () {
  const a = allA.find(el => el.innerText.toLocaleLowerCase().startsWith(path))
  if (!a) { return }
  storeLastArrowSrc(a.href)
  restoreCursorPos()
}

function browseTo (href) {
  window.fetch(href).then(r => r.text().then(t => {
    const parsed = new window.DOMParser().parseFromString(t, 'text/html')

    const table = parsed.querySelectorAll('table')[0].innerHTML
    document.body.querySelectorAll('table')[0].innerHTML = table

    const title = parsed.head.querySelectorAll('title')[0].innerText
    document.head.querySelectorAll('title')[0].innerText = title
    document.body.querySelectorAll('h1')[0].innerText = '.' + title

    window.history.pushState({}, '', title)
    init()
  }))
}

function nextPage () {
  const a = getASelected()
  if (!a.href || !a.innerText.endsWith('/')) { return }
  browseTo(a.href)
}

function prevPage () {
  if (window.location.origin === window.location.href.slice(0, -1)) { return }
  const path = window.location.pathname.split('/').slice(0, -2).join('/')
  browseTo(window.location.origin + path)
}

function cpPath () {
  var t = document.createElement('textarea')
  t.value = getASelected().href
  document.body.appendChild(t)
  t.select()
  document.execCommand('copy')
  document.body.removeChild(t)
}

const pics = document.getElementById('pics')
const picsHolder = document.getElementById('picsHolder')
const picsLabel = document.getElementById('picsLabel')

const picTypes = ['.jpg', '.jpeg', '.png', '.gif']
const isPic = src => src && picTypes.find(type => src.toLocaleLowerCase().includes(type))

const isPicMode = () => pics.style.display === 'flex'

let imgsIndex
let allImgs

function setImage (src) {
  src = src || allImgs[imgsIndex]
  picsLabel.innerText = src.split('/').pop()
  picsHolder.src = src
  storeLastArrowSrc(src)
}

function picsOn (ifImgSelected) {
  const href = getASelected().href

  if (isPicMode()) {
    return false
  } else if (ifImgSelected && !isPic(href)) {
    return false
  }

  if (isPic(href)) {
    imgsIndex = allImgs.findIndex(el => el === href)
    setImage()
  } else {
    setImage(picsHolder.src)
  }

  pics.style.display = 'flex'
  return true
}

function picsToggle () {
  if (!isPicMode()) {
    picsOn()
  } else {
    pics.style.display = 'none'
    restoreCursorPos()
  }
}

function picsNav (down) {
  if (!isPicMode()) { return false }

  if (down) {
    imgsIndex = allImgs[imgsIndex + 1] ? imgsIndex + 1 : 0
  } else {
    imgsIndex = allImgs[imgsIndex - 1] ? imgsIndex - 1 : allImgs.length - 1
  }

  setImage()
  return true
}

let path = ''
let clearPathToken = null

document.body.addEventListener('keydown', e => {
  switch (e.code) {
    case 'Tab':
    case 'ArrowDown':
      e.preventDefault()
      return picsNav(true) || moveArrow(true)

    case 'ArrowUp':
      e.preventDefault()
      return picsNav(false) || moveArrow(false)

    case 'ArrowRight':
      e.preventDefault()
      return picsOn(true) || picsNav(true) || nextPage()

    case 'ArrowLeft':
      e.preventDefault()
      return picsNav(false) || prevPage()

    case 'Escape':
      if (isPicMode) {
        e.preventDefault()
        return picsToggle()
      }
  }

  // Ctrl keys
  if (e.ctrlKey || e.metaKey) {
    switch (e.code) {
      case 'KeyD':
        e.preventDefault()
        return isPicMode() || mkdir()

      case 'KeyC':
        e.preventDefault()
        return isPicMode() || cpPath()
    }
  }

  // Any other key, for text search
  if (e.code.includes('Key')) {
    path += e.code.replace('Key', '').toLocaleLowerCase()
    window.clearTimeout(clearPathToken)
    clearPathToken = setTimeout(() => { path = '' }, 1000)
    setCursorToClosest()
  }
}, false)

function partialBrowseOnClickFolders () {
  allA.forEach(a => {
    if (!a.innerText.endsWith('/')) { return }
    a.addEventListener('click', e => {
      e.preventDefault()
      browseTo(e.target.href)
    })
  }, false)
}

function init () {
  allA = Array.from(document.querySelectorAll('a'))
  allImgs = allA.map(el => el.href).filter(isPic)
  document.getElementById('picsToggle').style.display = allImgs.length > 0 ? 'flex' : 'none'

  imgsIndex = 0
  partialBrowseOnClickFolders()
  restoreCursorPos()
  console.log('Browsed to ' + window.location.href)
}

init()

window.picsToggle = picsToggle
window.picsNav = () => picsNav(true)
window.mkdir = mkdir
<commit_msg>Fix history<commit_after>function cancelDefault (e) {
  e.preventDefault()
  e.stopPropagation()
}

let allA = Array.from(document.querySelectorAll('a'))

const checkDupes = test => allA.find(a => a.innerText.replace('/', '') === test)

function rpcFs (call, args, cb) {
  args = args.map(a => a.startsWith('/') ? a.slice(1) : a)
  args = args.map(a => window.location.pathname + a)

  const xhr = new window.XMLHttpRequest()
  xhr.open('POST', window.location.origin + '/rpc/')
  xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
  xhr.send(JSON.stringify({call, args}))
  xhr.onload = cb
}

const mkdirCall = (path, cb) => rpcFs('mkdirp', [path], cb)

// const rmCall = (path, cb) => rpcFs('remove', [path], cb)

// const mvCall = (path1, path2, cb) => rpcFs('move', [path1, path2], cb)

function mkdir () {
  const folder = window.prompt('New folder name', '')

  if (!folder) {
    return
  } else if (checkDupes(folder)) {
    return window.alert('Name already already exists')
  }

  mkdirCall(folder, () => browseTo(currentLocation))
}

function warning (e) {
  return 'Leaving will interrupt transfer\nAre you sure you want to leave?'
}

function newBar (name) {
  const id = Math.random().toString(36).substring(7)

  document.getElementById('progressBars').innerHTML += `

       ${name.split('/').pop()}

1%

  `
  return id
}

function updatePercent (id, percent) {
  const el = document.getElementById(id).querySelectorAll('div.barForeground')[0]
  const width = Math.floor(100 * percent).toString() + '%'
  el.innerText = width
  el.style.width = width
}

function shouldRefresh () {
  totalDone += 1
  if (totalUploads === totalDone) {
    window.onbeforeunload = null
    console.log('Done uploading ' + totalDone + ' files')
    totalDone = 0
    totalUploads = 0
    document.getElementById('progressBars').innerHTML = ''
    browseTo(currentLocation)
  }
}

function postFile (file, path) {
  totalUploads += 1
  window.onbeforeunload = warning

  const xhr = new window.XMLHttpRequest()
  xhr.open('POST', window.location.origin + '/post' + path)
  xhr.upload.id = newBar(path + '/' + file.name)

  const formData = new window.FormData()
  formData.append(file.name, file)

  xhr.upload.addEventListener('progress', a => {
    updatePercent(a.target.id, a.loaded / a.total)
  })

  xhr.upload.addEventListener('load', shouldRefresh)

  xhr.send(formData)
}

const parseDomFolder = f => {
  f.createReader().readEntries(e => e.forEach(i => parseDomItem(i)))
}

function parseDomItem (domFile, shoudCheckDupes) {
  if (shoudCheckDupes && checkDupes(domFile.name)) {
    return window.alert(domFile.name + ' already exists !')
  }

  if (domFile.isFile) {
    domFile.file(f => postFile(f, domFile.fullPath || domFile.name))
  } else {
    mkdirCall(domFile.fullPath, () => parseDomFolder(domFile))
  }
}

function pushEntry (entry) {
  if (!entry.webkitGetAsEntry && !entry.getAsEntry) {
    return window.alert('Unsupported browser ! Please update to chrome/firefox.')
  } else {
    entry = entry.webkitGetAsEntry() || entry.getAsEntry()
  }

  parseDomItem(entry, true)
}

const upGrid = document.getElementById('drop-grid')

document.ondragenter = (e) => {
  if (isPicMode()) { return }
  cancelDefault(e)
  e.dataTransfer.dropEffect = 'copy'
  upGrid.style.display = 'flex'
}

upGrid.ondragleave = (e) => {
  cancelDefault(e)
  upGrid.style.display = 'none'
}

document.ondragover = (e) => {
  cancelDefault(e)
  return false
}

document.ondrop = (e) => {
  cancelDefault(e)
  upGrid.style.display = 'none'

  Array.from(e.dataTransfer.items).forEach(pushEntry)
  return false
}

let totalUploads = 0
let totalDone = 0

const getArrowSelected = () => document.querySelectorAll('i.arrow-selected')[0]

function getASelected () {
  const dest = getArrowSelected()
  return !dest ? false : dest.parentElement.parentElement.querySelectorAll('a')[0]
}

function scrollToArrow () {
  const pos = getArrowSelected().getBoundingClientRect()
  window.scrollTo(0, pos.y)
}

function clearArrowSelected () {
  const arr = getArrowSelected()
  if (!arr) { return }
  arr.classList.remove('arrow-selected')
}

function restoreCursorPos () {
  clearArrowSelected()
  const hrefSelected = window.localStorage.getItem('last-selected' + currentLocation)
  let a = allA.find(el => el.href === hrefSelected)

  if (!a) {
    if (allA[0].innerText === '../') {
      a = allA[1]
    } else {
      a = allA[0]
    }
  }

  const icon = a.parentElement.parentElement.querySelectorAll('.arrow-icon')[0]
  icon.classList.add('arrow-selected')
  scrollToArrow()
}

const storeLastArrowSrc = src => window.localStorage.setItem('last-selected' + currentLocation, src)

function moveArrow (down) {
  const all = Array.from(document.querySelectorAll('i.arrow-icon'))
  let i = all.findIndex(el => el.classList.contains('arrow-selected'))

  clearArrowSelected()

  if (down) {
    i = all[i + 1] ? i + 1 : 0
  } else {
    i = all[i - 1] ? i - 1 : all.length - 1
  }

  all[i].classList.add('arrow-selected')
  storeLastArrowSrc(getASelected().href)

  const itemPos = all[i].getBoundingClientRect()

  if (i === 0) {
    window.scrollTo(0, 0)
  } else if (i === all.length - 1) {
    window.scrollTo(0, document.documentElement.scrollHeight)
  } else if (itemPos.top < 0) {
    window.scrollBy(0, -200)
  } else if (itemPos.bottom > window.innerHeight) {
    window.scrollBy(0, 200)
  }
}

function setCursorToClosest () {
  const a = allA.find(el => el.innerText.toLocaleLowerCase().startsWith(path))
  if (!a) { return }
  storeLastArrowSrc(a.href)
  restoreCursorPos()
}

window.onpopstate = prevPage

function browseTo (href) {
  currentLocation = href

  window.fetch(href).then(r => r.text().then(t => {
    const parsed = new window.DOMParser().parseFromString(t, 'text/html')

    const table = parsed.querySelectorAll('table')[0].innerHTML
    document.body.querySelectorAll('table')[0].innerHTML = table

    const title = parsed.head.querySelectorAll('title')[0].innerText
    document.head.querySelectorAll('title')[0].innerText = title
    document.body.querySelectorAll('h1')[0].innerText = '.' + title

    window.history.pushState({}, '', title)
    init()
  }))
}

function nextPage () {
  const a = getASelected()
  if (!a.href || !a.innerText.endsWith('/')) { return }
  browseTo(a.href)
}

function prevPage () {
  if (window.location.origin === currentLocation.slice(0, -1)) { return }
  const path = currentLocation.split('/').slice(0, -1).join('/')
  browseTo(path)
}

function cpPath () {
  var t = document.createElement('textarea')
  t.value = getASelected().href
  document.body.appendChild(t)
  t.select()
  document.execCommand('copy')
  document.body.removeChild(t)
}

const pics = document.getElementById('pics')
const picsHolder = document.getElementById('picsHolder')
const picsLabel = document.getElementById('picsLabel')

const picTypes = ['.jpg', '.jpeg', '.png', '.gif']
const isPic = src => src && picTypes.find(type => src.toLocaleLowerCase().includes(type))

const isPicMode = () => pics.style.display === 'flex'

let imgsIndex
let allImgs

function setImage (src) {
  src = src || allImgs[imgsIndex]
  picsLabel.innerText = src.split('/').pop()
  picsHolder.src = src
  storeLastArrowSrc(src)
}

function picsOn (ifImgSelected) {
  const href = getASelected().href

  if (isPicMode()) {
    return false
  } else if (ifImgSelected && !isPic(href)) {
    return false
  }

  if (isPic(href)) {
    imgsIndex = allImgs.findIndex(el => el === href)
    setImage()
  } else {
    setImage(picsHolder.src)
  }

  pics.style.display = 'flex'
  return true
}

function picsToggle () {
  if (!isPicMode()) {
    picsOn()
  } else {
    pics.style.display = 'none'
    restoreCursorPos()
  }
}

function picsNav (down) {
  if (!isPicMode()) { return false }

  if (down) {
    imgsIndex = allImgs[imgsIndex + 1] ? imgsIndex + 1 : 0
  } else {
    imgsIndex = allImgs[imgsIndex - 1] ? imgsIndex - 1 : allImgs.length - 1
  }

  setImage()
  return true
}

let path = ''
let clearPathToken = null

document.body.addEventListener('keydown', e => {
  switch (e.code) {
    case 'Tab':
    case 'ArrowDown':
      e.preventDefault()
      return picsNav(true) || moveArrow(true)

    case 'ArrowUp':
      e.preventDefault()
      return picsNav(false) || moveArrow(false)

    case 'ArrowRight':
      e.preventDefault()
      return picsOn(true) || picsNav(true) || nextPage()

    case 'ArrowLeft':
      e.preventDefault()
      return picsNav(false) || prevPage()

    case 'Escape':
      if (isPicMode) {
        e.preventDefault()
        return picsToggle()
      }
  }

  // Ctrl keys
  if (e.ctrlKey || e.metaKey) {
    switch (e.code) {
      case 'KeyD':
        e.preventDefault()
        return isPicMode() || mkdir()

      case 'KeyC':
        e.preventDefault()
        return isPicMode() || cpPath()
    }
  }

  // Any other key, for text search
  if (e.code.includes('Key')) {
    path += e.code.replace('Key', '').toLocaleLowerCase()
    window.clearTimeout(clearPathToken)
    clearPathToken = setTimeout(() => { path = '' }, 1000)
    setCursorToClosest()
  }
}, false)

function partialBrowseOnClickFolders () {
  allA.forEach(a => {
    if (!a.innerText.endsWith('/')) { return }
    a.addEventListener('click', e => {
      e.preventDefault()
      storeLastArrowSrc(e.target.href)
      browseTo(e.target.href)
    })
  }, false)
}

function init () {
  allA = Array.from(document.querySelectorAll('a'))
  allImgs = allA.map(el => el.href).filter(isPic)
  document.getElementById('picsToggle').style.display = allImgs.length > 0 ? 'flex' : 'none'

  imgsIndex = 0
  partialBrowseOnClickFolders()
  restoreCursorPos()
  console.log('Browsed to ' + currentLocation)
}

let currentLocation = window.location.href

init()

window.picsToggle = picsToggle
window.picsNav = () => picsNav(true)
window.mkdir = mkdir
<|endoftext|>


<commit_before>var vows = require('vows'),
  fs = require('fs'),
  assert = require('assert'),
  cleanCSS = require('../index');

var batchContexts = function() {
  var context = {};
  fs.readdirSync('./test/data/').forEach(function(filename) {
    if (/min.css$/.exec(filename)) return;
    var testName = filename.split('.')[0];

    context[testName] = {
      topic: function() {
        return {
          plain: fs.readFileSync('./test/data/' + testName + '.css').toString('utf-8'),
          minimized: fs.readFileSync('./test/data/' + testName + '-min.css').toString('utf-8').replace(/\n/g, '')
        };
      }
    }
    context[testName]['minimizing ' + testName + '.css'] = function(data) {
      assert.equal(cleanCSS.process(data.plain), data.minimized)
    };
  });

  return context;
};

vows.describe('clean-batch')
  .addBatch(batchContexts())
  .export(module);<commit_msg>Fix test data path<commit_after>var vows = require('vows'),
  path = require('path'),
  fs = require('fs'),
  assert = require('assert'),
  cleanCSS = require('../index');

var batchContexts = function() {
  var context = {};
  fs.readdirSync(path.join(__dirname, 'data')).forEach(function(filename) {
    if (/min.css$/.exec(filename)) return;
    var testName = filename.split('.')[0];

    context[testName] = {
      topic: function() {
        return {
          plain: fs.readFileSync(path.join(__dirname, 'data', testName + '.css')).toString('utf-8'),
          minimized: fs.readFileSync(path.join(__dirname, 'data', testName + '-min.css')).toString('utf-8').replace(/\n/g, '')
        };
      }
    }
    context[testName]['minimizing ' + testName + '.css'] = function(data) {
      assert.equal(cleanCSS.process(data.plain), data.minimized)
    };
  });

  return context;
};

vows.describe('clean-batch')
  .addBatch(batchContexts())
  .export(module);
<|endoftext|>