<commit_before>const addToCache = (request, networkResponse) => {
  return caches.open('playbulb-candle')
    .then((cache) => cache.put(request, networkResponse.clone()));
};

const getCacheResponse = (request) => {
  return caches.open('playbulb-candle').then((cache) => {
    return cache.match(request);
  });
};

const getNetworkOrCacheResponse = (request) => {
  return new Promise((resolve) => {
    fetch(request).then((networkResponse) => {
      addToCache(request, networkResponse);
      resolve(networkResponse);
    }).catch(() => {
      getCacheResponse(request).then((cacheResponse) => {
        resolve(cacheResponse || Response.error());
      });
    });
  });
};

self.addEventListener('fetch', (event) => {
  event.respondWith(getNetworkOrCacheResponse(event.request));
});

const cleanOldCache = () => {
  return caches.keys().then(cacheNames => {
    return Promise.all(
      cacheNames.filter(cacheName => (cacheName !== 'playbulb-candle'))
                .map(cacheName => caches.delete(cacheName))
    );
  })
}

self.addEventListener('activate', (event) => {
  event.waitUntil(cleanOldCache());
});
<commit_msg>Use function instead of const (#57)<commit_after>function addToCache(request, networkResponse) {
  return caches.open('playbulb-candle')
    .then((cache) => cache.put(request, networkResponse.clone()));
}

function getCacheResponse(request) {
  return caches.open('playbulb-candle').then((cache) => {
    return cache.match(request);
  });
}

function getNetworkOrCacheResponse(request) {
  return new Promise((resolve) => {
    fetch(request).then((networkResponse) => {
      addToCache(request, networkResponse);
      resolve(networkResponse);
    }).catch(() => {
      getCacheResponse(request).then((cacheResponse) => {
        resolve(cacheResponse || Response.error());
      });
    });
  });
}

self.addEventListener('fetch', (event) => {
  event.respondWith(getNetworkOrCacheResponse(event.request));
});

function cleanOldCache() {
  return caches.keys().then(cacheNames => {
    return Promise.all(
      cacheNames.filter(cacheName => (cacheName !== 'playbulb-candle'))
                .map(cacheName => caches.delete(cacheName))
    );
  })
}

self.addEventListener('activate', (event) => {
  event.waitUntil(cleanOldCache());
});
<|endoftext|>


<commit_before>var st = require('../st.js')
var test = require('tap').test
var port = process.env.PORT || 1337
var path = require('path')
var request = require('request')
var middlewareServer
var server
var assert = require('assert')
var fs = require('fs')
var http = require('http')

// mount the dirname on the /test url
var mount1 = st({
  autoindex: true,
  path: path.dirname(__dirname),
  url: '/test',
  cache: {
    fd: {
      max: 3
    }
  }
})

// mount the test dir on the /blerg url
var mount2 = st({
  autoindex: true,
  path: __dirname,
  url: '/blerg',
  cache: {
    fd: {
      max: 3
    }
  }
})

function req (url, headers, cb) {
  if (typeof headers === 'function')
    cb = headers, headers = {}

  var reqs = 0
  var errState = null
  var prev = null

  console.error('requesting', url)
  request({ encoding: null,
            url: 'http://localhost:' + port + url,
            headers: headers }, next)
  request({ encoding: null,
            url: 'http://localhost:' + (port + 1) + url,
            headers: headers }, next)

  function next (er, res, body) {
    if (errState)
      return
    if (er)
      return cb(errState = er, res, body)
    if (++reqs === 2) {
      console.error('done with reqs', url)
      assert.equal(res.statusCode, prev.res.statusCode)
      // compare dates, they should be approximately the same
      assert(Math.abs(new Date(res.headers.date).getTime() -
                      new Date(res.headers.date).getTime()) < 1000)
      // compare the headers minus the 'date' value
      res.headers.date = prev.res.headers.date = null
      assert.deepEqual(res.headers, prev.res.headers)
      assert.equal('' + body, '' + prev.body)
      return cb(er, res, body)
    }
    prev = { res: res, body: body }
  }
}

test('setup middleware server', function (t) {
  // using the middleware approach
  middlewareServer = http.createServer(function (req, res) {
    mount1(req, res, function () {
      mount2(req, res, function () {
        res.statusCode = 404
        return res.end('Not a match: ' + req.url)
      })
    })
  })
  middlewareServer.listen(port, '127.0.0.1', function () {
    t.pass('listening')
    t.end()
  })
})

test('setup regular server', function (t) {
  server = http.createServer(function (req, res) {
    if (!mount1(req, res) && !mount2(req, res)) {
      res.statusCode = 404
      return res.end('Not a match: ' + req.url)
    }
  })
  server.listen(port + 1, '127.0.0.1', function () {
    t.pass('listening')
    t.end()
  })
})

var stEtag
var stExpect = fs.readFileSync(require.resolve('../st.js')).toString()
test('/test/st.js', function (t) {
  req('/test/st.js', function (er, res, body) {
    t.equal(res.statusCode, 200)
    t.ok(res.headers.etag)
    stEtag = res.headers.etag
    t.equal(body.toString(), stExpect)
    t.end()
  })
})

test('/test/st.js 304', function (t) {
  req('/test/st.js', {'if-none-match':stEtag}, function (er, res, body) {
    t.equal(res.statusCode, 304)
    t.notOk(body)
    t.end()
  })
})

var mmEtag
var mmExpect = fs.readFileSync(__filename, 'utf8')
test('/blerg/multi-mount.js', function (t) {
  req('/blerg/multi-mount.js', function (er, res, body) {
    t.equal(res.statusCode, 200)
    t.ok(res.headers.etag)
    mmEtag = res.headers.etag
    t.equal(body.toString(), mmExpect)
    t.end()
  })
})

test('/test/test/multi-mount.js', function (t) {
  req('/test/test/multi-mount.js', function (er, res, body) {
    t.equal(res.statusCode, 200)
    t.equal(mmEtag, res.headers.etag)
    t.equal(body.toString(), mmExpect)
    t.end()
  })
})

var rmEtag
var rmExpect = fs.readFileSync(path.resolve(__dirname, '../README.md'), 'utf8')
var pjEtag
var pjExpect = fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf8')
var idEtag
var idExpect = fs.readFileSync(__dirname + '/fixtures/index.html', 'utf8')
test('just get a few more etags', function(t) {
  var n = 3

  req('/test/package.json', function (er, res, body) {
    if (er)
      throw er
    t.equal(body.toString(), pjExpect)
    pjEtag = res.headers.etag
    if (--n === 0)
      t.end()
  })

  req('/test/README.md', function (er, res, body) {
    if (er)
      throw er
    t.equal(body.toString(), rmExpect)
    rmEtag = res.headers.etag
    if (--n === 0)
      t.end()
  })

  req('/test/test/fixtures/index.html', function (er, res, body) {
    if (er)
      throw er
    t.equal(body.toString(), idExpect)
    idEtag = res.headers.etag
    if (--n === 0)
      t.end()
  })
})

test('many parallel requests', function (t) {
  var n = 50
  var reqs =
    [ ['/test/test/multi-mount.js', mmEtag, mmExpect],
      ['/blerg/multi-mount.js', mmEtag, mmExpect],
      ['/test/st.js', stEtag, stExpect],
      ['/test/README.md', rmEtag, rmExpect],
      ['/test/package.json', pjEtag, pjExpect],
      ['/test/test/fixtures/index.html', idEtag, idExpect],
      ['/blerg/fixtures/index.html', idEtag, idExpect] ]

  var total = n * reqs.length

  for (var i = 0; i < n; i ++) {
    reqs.forEach(function (r) {
      req(r[0], next(r))
    })
  }

  function next (r) { return function (er, res, body) {
    if (er) {
      console.error('problem with', r[0])
      throw er
    }

    t.pass(r[0])
    t.ok(res)
    t.ok(res.headers)
    t.equal(res.headers.etag, r[1])
    t.equal(body.toString(), r[2].toString())

    if (--total === 0) {
      process.nextTick(function () {
        t.ok(require('fd')._totalOpenFds <= 6) // max of 3 fds per mount
        t.end()
      })
    }
  }}
})

test('shutdown regular server', function (t) {
  server.close(function () {
    t.pass('closed')
    t.end()
  })
})

test('shutdown middleware server', function (t) {
  middlewareServer.close(function () {
    t.pass('closed')
    t.end()
  })
})
<commit_msg>fix breaking tests for 0.12/iojs and new request<commit_after>var st = require('../st.js')
var test = require('tap').test
var port = process.env.PORT || 1337
var path = require('path')
var request = require('request')
var middlewareServer
var server
var assert = require('assert')
var fs = require('fs')
var http = require('http')

// mount the dirname on the /test url
var mount1 = st({
  autoindex: true,
  path: path.dirname(__dirname),
  url: '/test',
  cache: {
    fd: {
      max: 3
    }
  }
})

// mount the test dir on the /blerg url
var mount2 = st({
  autoindex: true,
  path: __dirname,
  url: '/blerg',
  cache: {
    fd: {
      max: 3
    }
  }
})

function req (url, headers, cb) {
  if (typeof headers === 'function')
    cb = headers, headers = {}

  var reqs = 0
  var errState = null
  var prev = null

  request({ encoding: null,
            url: 'http://localhost:' + port + url,
            headers: headers,
            agentOptions: { maxSockets: 50 } }, next)
  request({ encoding: null,
            url: 'http://localhost:' + (port + 1) + url,
            headers: headers,
            agentOptions: { maxSockets: 50 } }, next)

  function next (er, res, body) {
    if (errState)
      return
    if (er)
      return cb(errState = er, res, body)
    if (++reqs === 2) {
      assert.equal(res.statusCode, prev.res.statusCode)
      // compare dates, they should be approximately the same
      assert(Math.abs(new Date(res.headers.date).getTime() -
                      new Date(res.headers.date).getTime()) < 1000)
      // compare the headers minus the 'date' value
      res.headers.date = prev.res.headers.date = null
      assert.deepEqual(res.headers, prev.res.headers)
      assert.equal('' + body, '' + prev.body)
      return cb(er, res, body)
    }
    prev = { res: res, body: body }
  }
}

test('setup middleware server', function (t) {
  // using the middleware approach
  middlewareServer = http.createServer(function (req, res) {
    mount1(req, res, function () {
      mount2(req, res, function () {
        res.statusCode = 404
        return res.end('Not a match: ' + req.url)
      })
    })
  })
  middlewareServer.listen(port, '127.0.0.1', function () {
    t.pass('listening')
    t.end()
  })
})

test('setup regular server', function (t) {
  server = http.createServer(function (req, res) {
    if (!mount1(req, res) && !mount2(req, res)) {
      res.statusCode = 404
      return res.end('Not a match: ' + req.url)
    }
  })
  server.listen(port + 1, '127.0.0.1', function () {
    t.pass('listening')
    t.end()
  })
})

var stEtag
var stExpect = fs.readFileSync(require.resolve('../st.js')).toString()
test('/test/st.js', function (t) {
  req('/test/st.js', function (er, res, body) {
    t.equal(res.statusCode, 200)
    t.ok(res.headers.etag)
    stEtag = res.headers.etag
    t.equal(body.toString(), stExpect)
    t.end()
  })
})

test('/test/st.js 304', function (t) {
  req('/test/st.js', {'if-none-match':stEtag}, function (er, res, body) {
    t.equal(res.statusCode, 304)
    t.equal(body.length, 0)
    t.end()
  })
})

var mmEtag
var mmExpect = fs.readFileSync(__filename, 'utf8')
test('/blerg/multi-mount.js', function (t) {
  req('/blerg/multi-mount.js', function (er, res, body) {
    t.equal(res.statusCode, 200)
    t.ok(res.headers.etag)
    mmEtag = res.headers.etag
    t.equal(body.toString(), mmExpect)
    t.end()
  })
})

test('/test/test/multi-mount.js', function (t) {
  req('/test/test/multi-mount.js', function (er, res, body) {
    t.equal(res.statusCode, 200)
    t.equal(mmEtag, res.headers.etag)
    t.equal(body.toString(), mmExpect)
    t.end()
  })
})

var rmEtag
var rmExpect = fs.readFileSync(path.resolve(__dirname, '../README.md'), 'utf8')
var pjEtag
var pjExpect = fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf8')
var idEtag
var idExpect = fs.readFileSync(__dirname + '/fixtures/index.html', 'utf8')
test('just get a few more etags', function(t) {
  var n = 3

  req('/test/package.json', function (er, res, body) {
    if (er)
      throw er
    t.equal(body.toString(), pjExpect)
    pjEtag = res.headers.etag
    if (--n === 0)
      t.end()
  })

  req('/test/README.md', function (er, res, body) {
    if (er)
      throw er
    t.equal(body.toString(), rmExpect)
    rmEtag = res.headers.etag
    if (--n === 0)
      t.end()
  })

  req('/test/test/fixtures/index.html', function (er, res, body) {
    if (er)
      throw er
    t.equal(body.toString(), idExpect)
    idEtag = res.headers.etag
    if (--n === 0)
      t.end()
  })
})

test('many parallel requests', function (t) {
  var n = 50
  var reqs =
    [ ['/test/test/multi-mount.js', mmEtag, mmExpect],
      ['/blerg/multi-mount.js', mmEtag, mmExpect],
      ['/test/st.js', stEtag, stExpect],
      ['/test/README.md', rmEtag, rmExpect],
      ['/test/package.json', pjEtag, pjExpect],
      ['/test/test/fixtures/index.html', idEtag, idExpect],
      ['/blerg/fixtures/index.html', idEtag, idExpect] ]

  var total = n * reqs.length

  for (var i = 0; i < n; i ++) {
    reqs.forEach(function (r) {
      req(r[0], next(r))
    })
  }

  function next (r) { return function (er, res, body) {
    if (er) {
      console.error('problem with', r[0])
      throw er
    }

    t.pass(r[0])
    t.ok(res)
    t.ok(res.headers)
    t.equal(res.headers.etag, r[1])
    t.equal(body.toString(), r[2].toString())

    if (--total === 0) {
      process.nextTick(function () {
        t.ok(require('fd')._totalOpenFds <= 6) // max of 3 fds per mount
        t.end()
      })
    }
  }}
})

test('shutdown regular server', function (t) {
  server.close(function () {
    t.pass('closed')
    t.end()
  })
})

test('shutdown middleware server', function (t) {
  middlewareServer.close(function () {
    t.pass('closed')
    t.end()
  })
})
<|endoftext|>


<commit_before>export default function() {
  return function({ addUtilities, variants, target }) {
    addUtilities(
      {
        '.block': {
          display: 'block',
        },
        '.inline-block': {
          display: 'inline-block',
        },
        '.inline': {
          display: 'inline',
        },
        '.flex': {
          display: 'flex',
        },
        '.inline-flex': {
          display: 'inline-flex',
        },
        '.table': {
          display: 'table',
        },
        '.table-caption': {
          display: 'table-caption',
        },
        '.table-cell': {
          display: 'table-cell',
        },
        '.table-column': {
          display: 'table-column',
        },
        '.table-column-group': {
          display: 'table-column-group',
        },
        '.table-footer-group': {
          display: 'table-footer-group',
        },
        '.table-header-group': {
          display: 'table-header-group',
        },
        '.table-row-group': {
          display: 'table-row-group',
        },
        '.table-row': {
          display: 'table-row',
        },
        ...(target('display') === 'ie11'
          ? {}
          : {
              '.flow-root': {
                display: 'flow-root',
              },
              '.grid': {
                display: 'grid',
              },
              '.inline-grid': {
                display: 'inline-grid',
              },
            }),
        '.hidden': {
          display: 'none',
        },
      },
      variants('display')
    )
  }
}
<commit_msg>Update display.js<commit_after>export default function() {
  return function({ addUtilities, variants, target }) {
    addUtilities(
      {
        '.block': {
          display: 'block',
        },
        '.contents': {
          display: 'contents',
        },
        '.inline-block': {
          display: 'inline-block',
        },
        '.inline': {
          display: 'inline',
        },
        '.flex': {
          display: 'flex',
        },
        '.inline-flex': {
          display: 'inline-flex',
        },
        '.table': {
          display: 'table',
        },
        '.table-caption': {
          display: 'table-caption',
        },
        '.table-cell': {
          display: 'table-cell',
        },
        '.table-column': {
          display: 'table-column',
        },
        '.table-column-group': {
          display: 'table-column-group',
        },
        '.table-footer-group': {
          display: 'table-footer-group',
        },
        '.table-header-group': {
          display: 'table-header-group',
        },
        '.table-row-group': {
          display: 'table-row-group',
        },
        '.table-row': {
          display: 'table-row',
        },
        ...(target('display') === 'ie11'
          ? {}
          : {
              '.flow-root': {
                display: 'flow-root',
              },
              '.grid': {
                display: 'grid',
              },
              '.inline-grid': {
                display: 'inline-grid',
              },
            }),
        '.hidden': {
          display: 'none',
        },
      },
      variants('display')
    )
  }
}
<|endoftext|>


<commit_before><commit_msg>fix locale fallback, fixed QingWei-Li/docsify/issues/152<commit_after><|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version["enyo-ilib"] = "2.5.4-pre.1.lite.1";
}
<commit_msg>Update version string to 2.5.4-pre.1.lite.2<commit_after>if (enyo && enyo.version) {
	enyo.version["enyo-ilib"] = "2.5.4-pre.1.lite.2";
}
<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version["enyo-cordova"] = "2.5.2-pre.3";
}
<commit_msg>Update version string to 2.5.2-pre.4<commit_after>if (enyo && enyo.version) {
	enyo.version["enyo-cordova"] = "2.5.2-pre.4";
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var os = require('os');
var childProcess = require('child_process');
var mkdirp = require('mkdirp');
var sinon = require('sinon');
var should = require('should');
var expect = require('chai').expect;
var nodeMinify = require('../lib/node-minify');

var oneFile = __dirname + '/../examples/public/js/sample.js';
var filesArray = [
  __dirname + '/../examples/public/js/sample.js',
  __dirname + '/../examples/public/js/sample2.js'
];
var filesArrayWithWildcards = [
  'sample.js',
  'sample2.js',
  '**/*.js'
];
var filesArrayWithWildcards2 = [
  __dirname + '/../examples/public/js/sample.js',
  __dirname + '/../examples/public/js/sample2.js',
  __dirname + '/../examples/public/js2/**/*.js'
];
var fileJSOut = __dirname + '/../examples/public/dist/sample.js';
var fileCSS = __dirname + '/../examples/public/css/sample.css';
var fileCSSArray = [
  __dirname + '/../examples/public/css/sample.css',
  __dirname + '/../examples/public/css/sample2.css'
];
var fileCSSArrayWithWildcards = [
  __dirname + '/../examples/public/css/sample.css',
  __dirname + '/../examples/public/css/sample2.css',
  __dirname + '/**/*.css'
];
var fileCSSOut = __dirname + '/../examples/public/dist/sample.css';

var tests = {
  concat: [
    {
      it: 'should concat javascript and no compress and an array of file',
      minify: {
        compressor: 'no-compress',
        input: filesArray,
        output: fileJSOut
      }
    },
    {
      it: 'should concat javascript and no compress and a single file',
      minify: {
        compressor: 'no-compress',
        input: oneFile,
        output: fileJSOut
      }
    }
  ],
  commoncss: [
    {
      it: 'should compress css with {compressor} and a single file',
      minify: {
        compressor: '{compressor}',
        input: fileCSS,
        output: fileCSSOut
      }
    },
    {
      it: 'should compress css with {compressor} and an array of file',
      minify: {
        compressor: '{compressor}',
        input: fileCSSArray,
        output: fileCSSOut
      }
    },
    {
      it: 'should compress css with {compressor} and an array of file with wildcards',
      minify: {
        compressor: '{compressor}',
        input: fileCSSArrayWithWildcards,
        output: fileCSSOut
      }
    }
  ],
  commonjs: [
    {
      it: 'should compress javascript with {compressor} and a single file',
      minify: {
        compressor: '{compressor}',
        input: oneFile,
        output: fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a custom public folder',
      minify: {
        compressor: '{compressor}',
        input: 'sample.js',
        output: fileJSOut,
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a custom public folder and full path',
      minify: {
        compressor: '{compressor}',
        input: __dirname + '/../examples/public/js/sample.js',
        output: fileJSOut,
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a custom buffer size',
      minify: {
        compressor: '{compressor}',
        input: oneFile,
        output: fileJSOut,
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with some options',
      minify: {
        compressor: '{compressor}',
        input: oneFile,
        output: fileJSOut,
        options: {
          charset: 'utf8'
        }
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file',
      minify: {
        compressor: '{compressor}',
        input: filesArray,
        output: fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file with a custom public folder',
      minify: {
        compressor: '{compressor}',
        input: [
          'sample.js',
          'sample2.js'
        ],
        output: fileJSOut,
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file with a custom buffer size',
      minify: {
        compressor: '{compressor}',
        input: filesArray,
        output: fileJSOut,
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path',
      minify: {
        compressor: '{compressor}',
        input: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path with a custom public folder',
      minify: {
        compressor: '{compressor}',
        input: '**/*.js',
        output: fileJSOut,
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path with a custom buffer size',
      minify: {
        compressor: '{compressor}',
        input: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut,
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of strings and wildcards path',
      minify: {
        compressor: '{compressor}',
        input: filesArrayWithWildcards2,
        output: fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of strings and wildcards path' +
      ' with a custom public folder',
      minify: {
        compressor: '{compressor}',
        input: filesArrayWithWildcards,
        output: fileJSOut,
        publicFolder: __dirname + '/../examples/public/js/'
      }
    }
  ]
};

var runOneTest = function(options, compressor, sync) {
  options = JSON.parse(JSON.stringify(options));

  options.minify.compressor = options.minify.compressor.replace('{compressor}', compressor);
  options.minify.output = options.minify.output.replace('{compressor}', compressor);

  if (sync) {
    options.minify.sync = true;
  }

  it(options.it.replace('{compressor}', compressor), function(done) {
    options.minify.callback = function(err, min) {
      should.not.exist(err);
      should.exist(min);
      should(typeof min).be.exactly('string');

      done();
    };

    nodeMinify.minify(options.minify);
  });
};

describe('node-minify', function() {
  mkdirp('/tmp/');

  describe('Fake binary', function() {
    it('should throw an error if binary does not exist', function(done) {
      var options = {};
      options.minify = {
        compressor: 'fake',
        input: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });
  });

  describe('No mandatories', function() {
    it('should throw an error if no compressor', function(done) {
      var options = {};
      options.minify = {
        input: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });

    it('should throw an error if no input', function(done) {
      var options = {};
      options.minify = {
        compressor: 'no-compress',
        output: fileJSOut
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });

    it('should throw an error if no output', function(done) {
      var options = {};
      options.minify = {
        compressor: 'no-compress',
        input: __dirname + '/../examples/public/js/**/*.js'
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });
  });

  describe('Create errors', function() {
    it('should callback an error if gcc with bad options', function(done) {
      var options = {};
      options.minify = {
        compressor: 'gcc-java',
        input: oneFile,
        output: fileJSOut,
        options: {
          fake: true
        },
        callback: function(err, min) {
          should.exist(err);
          should.not.exist(min);

          done();
        }
      };

      nodeMinify.minify(options.minify);
    });

    it('should callback an error if yui with bad options', function(done) {
      var options = {};
      options.minify = {
        compressor: 'yui-js',
        input: oneFile,
        output: fileJSOut,
        sync: true,
        options: {
          fake: true
        },
        callback: function(err, min) {
          should.exist(err);
          should.not.exist(min);

          done();
        }
      };

      nodeMinify.minify(options.minify);
    });
  });

  describe('Create more errors', function() {
    beforeEach(function() {
      this.stub = sinon.stub(childProcess, 'spawnSync').throws(new Error('UnsupportedClassVersionError'));
    });
    afterEach(function() {
      this.stub.restore();
    });
    it('should callback an error on spawnSync', function(done) {
      var options = {};
      options.minify = {
        compressor: 'gcc-java',
        input: oneFile,
        output: fileJSOut,
        sync: true,
        callback: function(err, min) {
          should.exist(err);
          should.not.exist(min);

          done();
        }
      };

      nodeMinify.minify(options.minify);
    });
  });

  describe('Deprecated', function() {
    it('should show a deprecated message', function(done) {
      var options = {};
      options.minify = {
        compressor: 'uglifyjs',
        input: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut
      };

      options.minify.callback = function(err, min) {
        should.not.exist(err);
        should.exist(min);

        done();
      };

      new nodeMinify.minify(options.minify);
    });

    it('should show throw on type option', function(done) {
      var options = {};
      options.minify = {
        type: 'uglifyjs',
        input: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });

    it('should show throw on type fileIn', function(done) {
      var options = {};
      options.minify = {
        compressor: 'uglifyjs',
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });

    it('should show throw on type fileOut', function(done) {
      var options = {};
      options.minify = {
        compressor: 'uglifyjs',
        input: __dirname + '/../examples/public/js/**/*.js',
        fileOut: fileJSOut
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });
  });

  describe('Concatenation', function() {
    tests.concat.forEach(function(o) {
      runOneTest(o, 'no-compress');
    });
  });

  describe('GCC', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc', true);
    });
  });

  describe('GCC Java', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc-java');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc-java', true);
    });
  });

  describe('GCC Legacy', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc-legacy');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc-legacy', true);
    });
  });

  describe('YUI', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'yui-js');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'yui-js', true);
    });

    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'yui-css');
    });
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'yui', true);
    });
  });

  describe('UglifyJS', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'uglifyjs');
    });
  });

  describe('Clean-css', function() {
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'clean-css');
    });
  });

  describe('CSSO', function() {
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'csso');
    });
  });

  describe('Sqwish', function() {
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'sqwish');
    });
  });
});
<commit_msg>Update tests for Babili<commit_after>'use strict';

var fs = require('fs');
var os = require('os');
var childProcess = require('child_process');
var mkdirp = require('mkdirp');
var sinon = require('sinon');
var should = require('should');
var expect = require('chai').expect;
var nodeMinify = require('../lib/node-minify');

var oneFile = __dirname + '/../examples/public/js/sample.js';
var filesArray = [
  __dirname + '/../examples/public/js/sample.js',
  __dirname + '/../examples/public/js/sample2.js'
];
var filesArrayWithWildcards = [
  'sample.js',
  'sample2.js',
  '**/*.js'
];
var filesArrayWithWildcards2 = [
  __dirname + '/../examples/public/js/sample.js',
  __dirname + '/../examples/public/js/sample2.js',
  __dirname + '/../examples/public/js2/**/*.js'
];
var fileJSOut = __dirname + '/../examples/public/dist/sample.js';
var fileCSS = __dirname + '/../examples/public/css/sample.css';
var fileCSSArray = [
  __dirname + '/../examples/public/css/sample.css',
  __dirname + '/../examples/public/css/sample2.css'
];
var fileCSSArrayWithWildcards = [
  __dirname + '/../examples/public/css/sample.css',
  __dirname + '/../examples/public/css/sample2.css',
  __dirname + '/**/*.css'
];
var fileCSSOut = __dirname + '/../examples/public/dist/sample.css';

var tests = {
  concat: [
    {
      it: 'should concat javascript and no compress and an array of file',
      minify: {
        compressor: 'no-compress',
        input: filesArray,
        output: fileJSOut
      }
    },
    {
      it: 'should concat javascript and no compress and a single file',
      minify: {
        compressor: 'no-compress',
        input: oneFile,
        output: fileJSOut
      }
    }
  ],
  commoncss: [
    {
      it: 'should compress css with {compressor} and a single file',
      minify: {
        compressor: '{compressor}',
        input: fileCSS,
        output: fileCSSOut
      }
    },
    {
      it: 'should compress css with {compressor} and an array of file',
      minify: {
        compressor: '{compressor}',
        input: fileCSSArray,
        output: fileCSSOut
      }
    },
    {
      it: 'should compress css with {compressor} and an array of file with wildcards',
      minify: {
        compressor: '{compressor}',
        input: fileCSSArrayWithWildcards,
        output: fileCSSOut
      }
    }
  ],
  commonjs: [
    {
      it: 'should compress javascript with {compressor} and a single file',
      minify: {
        compressor: '{compressor}',
        input: oneFile,
        output: fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a custom public folder',
      minify: {
        compressor: '{compressor}',
        input: 'sample.js',
        output: fileJSOut,
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a custom public folder and full path',
      minify: {
        compressor: '{compressor}',
        input: __dirname + '/../examples/public/js/sample.js',
        output: fileJSOut,
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a custom buffer size',
      minify: {
        compressor: '{compressor}',
        input: oneFile,
        output: fileJSOut,
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with some options',
      minify: {
        compressor: '{compressor}',
        input: oneFile,
        output: fileJSOut,
        options: {
          charset: 'utf8'
        }
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file',
      minify: {
        compressor: '{compressor}',
        input: filesArray,
        output: fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file with a custom public folder',
      minify: {
        compressor: '{compressor}',
        input: [
          'sample.js',
          'sample2.js'
        ],
        output: fileJSOut,
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file with a custom buffer size',
      minify: {
        compressor: '{compressor}',
        input: filesArray,
        output: fileJSOut,
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path',
      minify: {
        compressor: '{compressor}',
        input: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path with a custom public folder',
      minify: {
        compressor: '{compressor}',
        input: '**/*.js',
        output: fileJSOut,
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path with a custom buffer size',
      minify: {
        compressor: '{compressor}',
        input: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut,
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of strings and wildcards path',
      minify: {
        compressor: '{compressor}',
        input: filesArrayWithWildcards2,
        output: fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of strings and wildcards path' +
      ' with a custom public folder',
      minify: {
        compressor: '{compressor}',
        input: filesArrayWithWildcards,
        output: fileJSOut,
        publicFolder: __dirname + '/../examples/public/js/'
      }
    }
  ]
};

var runOneTest = function(options, compressor, sync) {
  options = JSON.parse(JSON.stringify(options));

  options.minify.compressor = options.minify.compressor.replace('{compressor}', compressor);
  options.minify.output = options.minify.output.replace('{compressor}', compressor);

  if (sync) {
    options.minify.sync = true;
  }

  it(options.it.replace('{compressor}', compressor), function(done) {
    options.minify.callback = function(err, min) {
      should.not.exist(err);
      should.exist(min);
      should(typeof min).be.exactly('string');

      done();
    };

    nodeMinify.minify(options.minify);
  });
};

describe('node-minify', function() {
  mkdirp('/tmp/');

  describe('Fake binary', function() {
    it('should throw an error if binary does not exist', function(done) {
      var options = {};
      options.minify = {
        compressor: 'fake',
        input: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });
  });

  describe('No mandatories', function() {
    it('should throw an error if no compressor', function(done) {
      var options = {};
      options.minify = {
        input: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });

    it('should throw an error if no input', function(done) {
      var options = {};
      options.minify = {
        compressor: 'no-compress',
        output: fileJSOut
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });

    it('should throw an error if no output', function(done) {
      var options = {};
      options.minify = {
        compressor: 'no-compress',
        input: __dirname + '/../examples/public/js/**/*.js'
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });
  });

  describe('Create errors', function() {
    it('should callback an error if gcc with bad options', function(done) {
      var options = {};
      options.minify = {
        compressor: 'gcc-java',
        input: oneFile,
        output: fileJSOut,
        options: {
          fake: true
        },
        callback: function(err, min) {
          should.exist(err);
          should.not.exist(min);

          done();
        }
      };

      nodeMinify.minify(options.minify);
    });

    it('should callback an error if yui with bad options', function(done) {
      var options = {};
      options.minify = {
        compressor: 'yui-js',
        input: oneFile,
        output: fileJSOut,
        sync: true,
        options: {
          fake: true
        },
        callback: function(err, min) {
          should.exist(err);
          should.not.exist(min);

          done();
        }
      };

      nodeMinify.minify(options.minify);
    });
  });

  describe('Create more errors', function() {
    beforeEach(function() {
      this.stub = sinon.stub(childProcess, 'spawnSync').throws(new Error('UnsupportedClassVersionError'));
    });
    afterEach(function() {
      this.stub.restore();
    });
    it('should callback an error on spawnSync', function(done) {
      var options = {};
      options.minify = {
        compressor: 'gcc-java',
        input: oneFile,
        output: fileJSOut,
        sync: true,
        callback: function(err, min) {
          should.exist(err);
          should.not.exist(min);

          done();
        }
      };

      nodeMinify.minify(options.minify);
    });
  });

  describe('Deprecated', function() {
    it('should show a deprecated message', function(done) {
      var options = {};
      options.minify = {
        compressor: 'uglifyjs',
        input: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut
      };

      options.minify.callback = function(err, min) {
        should.not.exist(err);
        should.exist(min);

        done();
      };

      new nodeMinify.minify(options.minify);
    });

    it('should show throw on type option', function(done) {
      var options = {};
      options.minify = {
        type: 'uglifyjs',
        input: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });

    it('should show throw on type fileIn', function(done) {
      var options = {};
      options.minify = {
        compressor: 'uglifyjs',
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        output: fileJSOut
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });

    it('should show throw on type fileOut', function(done) {
      var options = {};
      options.minify = {
        compressor: 'uglifyjs',
        input: __dirname + '/../examples/public/js/**/*.js',
        fileOut: fileJSOut
      };

      expect(function() {
        nodeMinify.minify(options.minify);
      }).to.throw();
      done();
    });
  });

  describe('Concatenation', function() {
    tests.concat.forEach(function(o) {
      runOneTest(o, 'no-compress');
    });
  });

  describe('Babili', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'babili');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'babili', true);
    });
  });

  describe('GCC', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc', true);
    });
  });

  describe('GCC Java', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc-java');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc-java', true);
    });
  });

  describe('GCC Legacy', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc-legacy');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc-legacy', true);
    });
  });

  describe('YUI', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'yui-js');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'yui-js', true);
    });

    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'yui-css');
    });
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'yui', true);
    });
  });

  describe('UglifyJS', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'uglifyjs');
    });
  });

  describe('Clean-css', function() {
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'clean-css');
    });
  });

  describe('CSSO', function() {
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'csso');
    });
  });

  describe('Sqwish', function() {
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'sqwish');
    });
  });
});
<|endoftext|>


<commit_before>(function () {
  var Timeline = function (elementID) {
    var thiz = this;

    thiz.element = typeof elementID === "string" ? document.getElementById(elementID) : elementID || {};

    thiz.defaults = {
      frameRate: atc.defaults.frameRate,
      pauseDuration: atc.defaults.pauseDuration,
      loop: atc.defaults.loop
    };

    thiz._ = {
      queue: [],
      queueIndex: 0,
      stopped: true,
      duration: 0,
      endText: ""
    };
  },
  addToQueue = function (thiz, methodName, funktion, duration, endText) {
    thiz._.duration += duration;
    thiz._.endText = endText;
    thiz._.queue.push({ methodName: methodName, funktion: funktion, duration: duration, endText: endText });
  },
  findText = function (thiz) {
    var text,
        len = thiz._.queue.length;

    if (len) {
      text = thiz._.queue[len - 1].endText;
    } else {
      text = thiz.element.textContent;
    }

    return text;
  },
  nextFrame = function (frameRate) {
    var now, difference;

    now = new Date().getTime();
    expected = expected || now;
    difference = now - expected;

    expected += frameRate;
    return Math.max(0, frameRate - difference);
  },
  nextAnimation = function (thiz) {
    expected = null;

    if (thiz._.queueIndex < thiz._.queue.length && !thiz._.stopped) {
      thiz._.queueIndex += 1;
      thiz._.queue[thiz._.queueIndex - 1].funktion();
    } else if (!thiz._.stopped) {
      thiz._.queueIndex = 0;
      if (thiz.defaults.loop) {
        thiz._.queueIndex += 1;
        thiz._.queue[thiz._.queueIndex - 1].funktion();
      } else {
        thiz._.stopped = true;
      }
    }
  },
  expected,
  timeout;

  Timeline.prototype.go = function (timelineObj) {
    var thiz = this,
        len = thiz._.queue.length,
        funktion;

    if (timelineObj) {
      funktion = function () {
        timelineObj.go();
        timeout = setTimeout(function () { nextAnimation(thiz); }, timelineObj._.duration);
      };

      addToQueue(thiz, "go", funktion, timelineObj.duration, timelineObj.endText);
    } else if (len > 0) {
      thiz._.stopped = false;
      nextAnimation(thiz);
    }

    return thiz;
  };

  Timeline.prototype.stop = function (now) {
    var thiz = this;
    if (now) {
      thiz._.stopped = true;
      clearTimeout(timeout);
      expected = null;
    } else {
      var funktion = function () {
            thiz._.stopped = true;
          };

      addToQueue(thiz, "stop", funktion, 0, findText(thiz));
    }

    return thiz;
  };

  Timeline.prototype.frameRate = function (frameRate) {
    this.defaults.frameRate = frameRate || this.defaults.frameRate;

    return this;
  };

  Timeline.prototype.pauseDuration = function (duration) {
    this.defaults.pauseDuration = duration || this.defaults.pauseDuration;

    return this;
  };

  Timeline.prototype.loop = function (bool) {
    this.defaults.loop = typeof bool === "undefined" ? true : bool;

    return this;
  };

  Timeline.prototype.on = function (eventType, funktion, useCapture) {
    useCapture = useCapture || false;
    this.element.addEventListener(eventType, funktion, useCapture);

    return this;
  };

  Timeline.prototype.text = function (text) {
    var thiz = this,
        funktion;

    if (text) {
      funktion = function () {
        thiz.element.textContent = text;
        nextAnimation(thiz);
      };

      addToQueue(thiz, "text", funktion, 0, text);

      return thiz;
    }
    return thiz.element.textContent;
  };

  Timeline.prototype.html = function (html) {
    var thiz = this,
    funktion = function () {
      thiz.element.innerHTML = html;
      nextAnimation(thiz);
    };

    addToQueue(thiz, "html", funktion, 0, html);

    return thiz;
  };

  Timeline.prototype.switchElement = function (elementID) {
    var thiz = this,
    funktion = function () {
      thiz.element = typeof elementID === "string" ? document.getElementById(elementID) : elementID;
      nextAnimation(thiz);
    };

    addToQueue(thiz, "switchElement", funktion, 0, thiz.element.textContent); // TODO fix endText value

    return thiz;
  };

  Timeline.prototype.custom = function (customFunktion, options) {
    options = options || {};

    var thiz = this,
        duration = options.duration || 0,
        endText = options.endText || findText(thiz),
        funktion = function () {
          customFunktion();
          timeout = setTimeout(function () { nextAnimation(thiz); }, duration);
        };

    addToQueue(thiz, "custom", funktion, duration, endText);

    return thiz;
  };

  Timeline.prototype.frameByFrame = function (frames, options) {
    options = options || {};

    var thiz = this,
        len = frames.length,
        lastFrame = frames[len - 1],
        loops = options.loops || 1,
        totalFrames = len * loops,
        duration = options.duration || totalFrames * thiz.defaults.frameRate,
        frameRate = duration / totalFrames,
        i = 0,
        funktion = function () {
          if (i < totalFrames && !thiz._.stopped) {
            thiz.element.textContent = frames[i % len];

            timeout = setTimeout(funktion, nextFrame(frameRate));
            i++;
          } else {
            i = 0;
            nextAnimation(thiz);
          }
        };

    addToQueue(thiz, "frameByFrame", funktion, duration, lastFrame);

    return thiz;
  };

  Timeline.prototype.rollNumbers = function (startValue, endValue, options) {
    options = options || {};

    var thiz = this,
        difference = endValue - startValue,
        newValue = startValue,
        increment = options.increment || 1,
        addFrame = increment,
        totalFrames,
        frameRate,
        duration,
        funktion,
        i = 0;

    if (difference < 0) {
      difference = -difference;
      addFrame = -addFrame;
    }

    totalFrames = difference / increment;
    frameRate = options.duration / totalFrames || thiz.defaults.frameRate;
    duration = options.duration || thiz.defaults.frameRate * totalFrames;

    funktion = function () {
      if (i < totalFrames && !thiz._.stopped) {
        newValue += addFrame;
        thiz.element.textContent = newValue;

        timeout = setTimeout(funktion, nextFrame(frameRate));
        i++;
      } else {
        thiz.element.textContent = endValue;
        newValue = startValue;
        i = 0;
        nextAnimation(thiz);
      }
    };

    addToQueue(thiz, "rollNumbers", funktion, duration, endValue);

    return thiz;
  };

  Timeline.prototype.erase = function (options) {
    options = options || {};

    var thiz = this,
        text = findText(thiz),
        textArray = options.byWord ? text.match(/\S+\s*/g) : text.split(''),
        len = textArray.length,
        duration = options.duration || thiz.defaults.frameRate * len,
        frameRate = duration / len,
        funktion,
        i = 0;

    funktion = function () {
      if (i < len && !thiz._.stopped) {
        textArray.pop();
        thiz.element.textContent = textArray.join('');

        timeout = setTimeout(funktion, nextFrame(frameRate));
        i++;
      } else {
        textArray = options.byWord ? text.match(/\S+\s*/g) : text.split('');
        i = 0;
        nextAnimation(thiz);
      }
    };

    addToQueue(thiz, "erase", funktion, duration, "");

    return thiz;
  };

  Timeline.prototype.typeIn = function (text, options) {
    options = options || {};

    var thiz = this,
        textArray = options.byWord ? text.match(/\S+\s*/g) : text.split(''),
        displayTextArray = [],
        len = textArray.length,
        duration = options.duration || thiz.defaults.frameRate * len,
        frameRate = duration / len,
        funktion,
        i = 0;

    funktion = function () {
      if (i < len && !thiz._.stopped) {
        displayTextArray.push(textArray.shift());
        thiz.element.textContent = displayTextArray.join('');
        timeout = setTimeout(funktion, nextFrame(frameRate));
        i++;
      } else {
        textArray = displayTextArray;
        displayTextArray = [];
        i = 0;

        nextAnimation(thiz);
      }
    };

    addToQueue(thiz, "typeIn", funktion, duration, text);

    return thiz;
  };

  Timeline.prototype.fadeIn = function (options) {
    options = options || {};

    var thiz = this,
        text = options.text || findText(thiz),
        textArray = text.split(''),
        textLen = textArray.length,
        inOrOut = arguments[1] === "Out" ? "Out" : "In",
        fadeIn = inOrOut === "In",
        fadeOut = !fadeIn,
        spans = [],
        spansLen = 10,
        len = textLen + spansLen,
        duration = options.duration || thiz.defaults.frameRate * len,
        frameRate = duration / len,
        funktion,
        i;

    for (i = 0; i < spansLen; i++) {
      spans[i] = {
        el: document.createElement('span'),
        arr: []
      };
      if (fadeIn) {
        spans[i].el.style.opacity = i / (spansLen - 1);
      } else {
        spans[i].el.style.opacity = 1 - i / (spansLen - 1);
      }
    }

    i = 0;

    funktion = function () {
      var j, span;

      if (i === 0) {
        thiz.element.style.opacity = 1;
        thiz.element.textContent = "";

        for (j = spansLen - 1; j >= 0; j--) {
          spans[j].el.textContent = "";
          spans[j].arr = [];
          thiz.element.appendChild(spans[j].el);
        }

        spans[0].el.textContent = text;
        spans[0].arr = textArray;
      }

      if (i < len && !thiz._.stopped) {
        for (j = spansLen - 1; j > 0; j--) {
          spans[j].arr.push(spans[j - 1].arr.shift());
        }

        for (j = 0; j < spansLen; j++) {
          spans[j].el.textContent = spans[j].arr.join('');
        }

        timeout = setTimeout(funktion, nextFrame(frameRate));
        i++;
      } else {
        textArray = text.split('');
        thiz.element.style.opacity = +fadeIn;
        thiz.element.textContent = text;
        i = 0;
        if (fadeOut && options.remove) {
          thiz.element.remove();
        }

        nextAnimation(thiz);
      }
    };

    addToQueue(thiz, "fade" + inOrOut, funktion, duration, text);

    return thiz;
  };

  Timeline.prototype.fadeOut = function (options) {
    this.fadeIn(options, "Out");

    return this;
  };

  Timeline.prototype.pause = function (duration) {
    duration = duration || this.defaults.pauseDuration;

    var thiz = this,
        endText = findText(thiz),
        funktion = function () {
          timeout = setTimeout(function () { nextAnimation(thiz); }, duration);
        };

    addToQueue(thiz, "pause", funktion, duration, endText);

    return thiz;
  };

  Timeline.prototype.clearTimeline = function () {
    this._.queue = [];
    this._.duration = 0;
    this._.endText = "";

    return this.stop(true);
  };

  atc = function (elementID) {
    return new Timeline(elementID);
  };

  atc.defaults = {
    frameRate: 1000/24,
    pauseDuration: 2000,
    loop: false
  };

  atc.frameRate = function (frameRate) {
    atc.defaults.frameRate = frameRate || atc.defaults.frameRate;

    return atc;
  };

  atc.pauseDuration = function (duration) {
    atc.defaults.pauseDuration = duration || atc.defaults.pauseDuration;

    return atc;
  };

  atc.loop = function (bool) {
    atc.defaults.loop = typeof bool === "undefined" ? true : bool;

    return atc;
  };
})();<commit_msg>fix endText value for html method<commit_after>(function () {
  var Timeline = function (elementID) {
    var thiz = this;

    thiz.element = typeof elementID === "string" ? document.getElementById(elementID) : elementID || {};

    thiz.defaults = {
      frameRate: atc.defaults.frameRate,
      pauseDuration: atc.defaults.pauseDuration,
      loop: atc.defaults.loop
    };

    thiz._ = {
      queue: [],
      queueIndex: 0,
      stopped: true,
      duration: 0,
      endText: ""
    };
  },
  addToQueue = function (thiz, methodName, funktion, duration, endText) {
    thiz._.duration += duration;
    thiz._.endText = endText;
    thiz._.queue.push({ methodName: methodName, funktion: funktion, duration: duration, endText: endText });
  },
  findText = function (thiz) {
    var text,
        len = thiz._.queue.length;

    if (len) {
      text = thiz._.queue[len - 1].endText;
    } else {
      text = thiz.element.textContent;
    }

    return text;
  },
  nextFrame = function (frameRate) {
    var now, difference;

    now = new Date().getTime();
    expected = expected || now;
    difference = now - expected;

    expected += frameRate;
    return Math.max(0, frameRate - difference);
  },
  nextAnimation = function (thiz) {
    expected = null;

    if (thiz._.queueIndex < thiz._.queue.length && !thiz._.stopped) {
      thiz._.queueIndex += 1;
      thiz._.queue[thiz._.queueIndex - 1].funktion();
    } else if (!thiz._.stopped) {
      thiz._.queueIndex = 0;
      if (thiz.defaults.loop) {
        thiz._.queueIndex += 1;
        thiz._.queue[thiz._.queueIndex - 1].funktion();
      } else {
        thiz._.stopped = true;
      }
    }
  },
  expected,
  timeout;

  Timeline.prototype.go = function (timelineObj) {
    var thiz = this,
        len = thiz._.queue.length,
        funktion;

    if (timelineObj) {
      funktion = function () {
        timelineObj.go();
        timeout = setTimeout(function () { nextAnimation(thiz); }, timelineObj._.duration);
      };

      addToQueue(thiz, "go", funktion, timelineObj.duration, timelineObj.endText);
    } else if (len > 0) {
      thiz._.stopped = false;
      nextAnimation(thiz);
    }

    return thiz;
  };

  Timeline.prototype.stop = function (now) {
    var thiz = this;
    if (now) {
      thiz._.stopped = true;
      clearTimeout(timeout);
      expected = null;
    } else {
      var funktion = function () {
            thiz._.stopped = true;
          };

      addToQueue(thiz, "stop", funktion, 0, findText(thiz));
    }

    return thiz;
  };

  Timeline.prototype.frameRate = function (frameRate) {
    this.defaults.frameRate = frameRate || this.defaults.frameRate;

    return this;
  };

  Timeline.prototype.pauseDuration = function (duration) {
    this.defaults.pauseDuration = duration || this.defaults.pauseDuration;

    return this;
  };

  Timeline.prototype.loop = function (bool) {
    this.defaults.loop = typeof bool === "undefined" ? true : bool;

    return this;
  };

  Timeline.prototype.on = function (eventType, funktion, useCapture) {
    useCapture = useCapture || false;
    this.element.addEventListener(eventType, funktion, useCapture);

    return this;
  };

  Timeline.prototype.text = function (text) {
    var thiz = this,
        funktion;

    if (text) {
      funktion = function () {
        thiz.element.textContent = text;
        nextAnimation(thiz);
      };

      addToQueue(thiz, "text", funktion, 0, text);

      return thiz;
    }
    return thiz.element.textContent;
  };

  Timeline.prototype.html = function (html) {
    var thiz = this,
    funktion = function () {
      thiz.element.innerHTML = html;
      nextAnimation(thiz);
    };

    addToQueue(thiz, "html", funktion, 0, html.replace(/(<([^>]+)>)/ig,""));

    return thiz;
  };

  Timeline.prototype.switchElement = function (elementID) {
    var thiz = this,
    funktion = function () {
      thiz.element = typeof elementID === "string" ? document.getElementById(elementID) : elementID;
      nextAnimation(thiz);
    };

    addToQueue(thiz, "switchElement", funktion, 0, thiz.element.textContent); // TODO fix endText value

    return thiz;
  };

  Timeline.prototype.custom = function (customFunktion, options) {
    options = options || {};

    var thiz = this,
        duration = options.duration || 0,
        endText = options.endText || findText(thiz),
        funktion = function () {
          customFunktion();
          timeout = setTimeout(function () { nextAnimation(thiz); }, duration);
        };

    addToQueue(thiz, "custom", funktion, duration, endText);

    return thiz;
  };

  Timeline.prototype.frameByFrame = function (frames, options) {
    options = options || {};

    var thiz = this,
        len = frames.length,
        lastFrame = frames[len - 1],
        loops = options.loops || 1,
        totalFrames = len * loops,
        duration = options.duration || totalFrames * thiz.defaults.frameRate,
        frameRate = duration / totalFrames,
        i = 0,
        funktion = function () {
          if (i < totalFrames && !thiz._.stopped) {
            thiz.element.textContent = frames[i % len];

            timeout = setTimeout(funktion, nextFrame(frameRate));
            i++;
          } else {
            i = 0;
            nextAnimation(thiz);
          }
        };

    addToQueue(thiz, "frameByFrame", funktion, duration, lastFrame);

    return thiz;
  };

  Timeline.prototype.rollNumbers = function (startValue, endValue, options) {
    options = options || {};

    var thiz = this,
        difference = endValue - startValue,
        newValue = startValue,
        increment = options.increment || 1,
        addFrame = increment,
        totalFrames,
        frameRate,
        duration,
        funktion,
        i = 0;

    if (difference < 0) {
      difference = -difference;
      addFrame = -addFrame;
    }

    totalFrames = difference / increment;
    frameRate = options.duration / totalFrames || thiz.defaults.frameRate;
    duration = options.duration || thiz.defaults.frameRate * totalFrames;

    funktion = function () {
      if (i < totalFrames && !thiz._.stopped) {
        newValue += addFrame;
        thiz.element.textContent = newValue;

        timeout = setTimeout(funktion, nextFrame(frameRate));
        i++;
      } else {
        thiz.element.textContent = endValue;
        newValue = startValue;
        i = 0;
        nextAnimation(thiz);
      }
    };

    addToQueue(thiz, "rollNumbers", funktion, duration, endValue);

    return thiz;
  };

  Timeline.prototype.erase = function (options) {
    options = options || {};

    var thiz = this,
        text = findText(thiz),
        textArray = options.byWord ? text.match(/\S+\s*/g) : text.split(''),
        len = textArray.length,
        duration = options.duration || thiz.defaults.frameRate * len,
        frameRate = duration / len,
        funktion,
        i = 0;

    funktion = function () {
      if (i < len && !thiz._.stopped) {
        textArray.pop();
        thiz.element.textContent = textArray.join('');

        timeout = setTimeout(funktion, nextFrame(frameRate));
        i++;
      } else {
        textArray = options.byWord ? text.match(/\S+\s*/g) : text.split('');
        i = 0;
        nextAnimation(thiz);
      }
    };

    addToQueue(thiz, "erase", funktion, duration, "");

    return thiz;
  };

  Timeline.prototype.typeIn = function (text, options) {
    options = options || {};

    var thiz = this,
        textArray = options.byWord ? text.match(/\S+\s*/g) : text.split(''),
        displayTextArray = [],
        len = textArray.length,
        duration = options.duration || thiz.defaults.frameRate * len,
        frameRate = duration / len,
        funktion,
        i = 0;

    funktion = function () {
      if (i < len && !thiz._.stopped) {
        displayTextArray.push(textArray.shift());
        thiz.element.textContent = displayTextArray.join('');
        timeout = setTimeout(funktion, nextFrame(frameRate));
        i++;
      } else {
        textArray = displayTextArray;
        displayTextArray = [];
        i = 0;

        nextAnimation(thiz);
      }
    };

    addToQueue(thiz, "typeIn", funktion, duration, text);

    return thiz;
  };

  Timeline.prototype.fadeIn = function (options) {
    options = options || {};

    var thiz = this,
        text = options.text || findText(thiz),
        textArray = text.split(''),
        textLen = textArray.length,
        inOrOut = arguments[1] === "Out" ? "Out" : "In",
        fadeIn = inOrOut === "In",
        fadeOut = !fadeIn,
        spans = [],
        spansLen = 10,
        len = textLen + spansLen,
        duration = options.duration || thiz.defaults.frameRate * len,
        frameRate = duration / len,
        funktion,
        i;

    for (i = 0; i < spansLen; i++) {
      spans[i] = {
        el: document.createElement('span'),
        arr: []
      };
      if (fadeIn) {
        spans[i].el.style.opacity = i / (spansLen - 1);
      } else {
        spans[i].el.style.opacity = 1 - i / (spansLen - 1);
      }
    }

    i = 0;

    funktion = function () {
      var j, span;

      if (i === 0) {
        thiz.element.style.opacity = 1;
        thiz.element.textContent = "";

        for (j = spansLen - 1; j >= 0; j--) {
          spans[j].el.textContent = "";
          spans[j].arr = [];
          thiz.element.appendChild(spans[j].el);
        }

        spans[0].el.textContent = text;
        spans[0].arr = textArray;
      }

      if (i < len && !thiz._.stopped) {
        for (j = spansLen - 1; j > 0; j--) {
          spans[j].arr.push(spans[j - 1].arr.shift());
        }

        for (j = 0; j < spansLen; j++) {
          spans[j].el.textContent = spans[j].arr.join('');
        }

        timeout = setTimeout(funktion, nextFrame(frameRate));
        i++;
      } else {
        textArray = text.split('');
        thiz.element.style.opacity = +fadeIn;
        thiz.element.textContent = text;
        i = 0;
        if (fadeOut && options.remove) {
          thiz.element.remove();
        }

        nextAnimation(thiz);
      }
    };

    addToQueue(thiz, "fade" + inOrOut, funktion, duration, text);

    return thiz;
  };

  Timeline.prototype.fadeOut = function (options) {
    this.fadeIn(options, "Out");

    return this;
  };

  Timeline.prototype.pause = function (duration) {
    duration = duration || this.defaults.pauseDuration;

    var thiz = this,
        endText = findText(thiz),
        funktion = function () {
          timeout = setTimeout(function () { nextAnimation(thiz); }, duration);
        };

    addToQueue(thiz, "pause", funktion, duration, endText);

    return thiz;
  };

  Timeline.prototype.clearTimeline = function () {
    this._.queue = [];
    this._.duration = 0;
    this._.endText = "";

    return this.stop(true);
  };

  atc = function (elementID) {
    return new Timeline(elementID);
  };

  atc.defaults = {
    frameRate: 1000/24,
    pauseDuration: 2000,
    loop: false
  };

  atc.frameRate = function (frameRate) {
    atc.defaults.frameRate = frameRate || atc.defaults.frameRate;

    return atc;
  };

  atc.pauseDuration = function (duration) {
    atc.defaults.pauseDuration = duration || atc.defaults.pauseDuration;

    return atc;
  };

  atc.loop = function (bool) {
    atc.defaults.loop = typeof bool === "undefined" ? true : bool;

    return atc;
  };
})();<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version["enyo-ilib"] = "2.5.1-pre.8";
}
<commit_msg>Update version string to 2.5.1-pre.9<commit_after>if (enyo && enyo.version) {
	enyo.version["enyo-ilib"] = "2.5.1-pre.9";
}
<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version.moonstone = "2.3.0-rc.4";
}
<commit_msg>Update version to 2.3.0-rc.5<commit_after>if (enyo && enyo.version) {
	enyo.version.moonstone = "2.3.0-rc.5";
}
<|endoftext|>


<commit_before><commit_msg>add util<commit_after><|endoftext|>


<commit_before>var vumigo = require('vumigo_v02');
var DummyResource = vumigo.dummy.resources.DummyResource;

var DummyOptoutResource = DummyResource.extend(function(self) {
    DummyResource.call(self, 'optout');

    /* opt-out stubbery */
    self.optout_store = [
    ];

    self.handlers.optout = function (payload) {
        var key = payload.address_type + ':' + payload.address_value;
        self.optout_store.push(key);
        return {
            success: true
        };
    };

    self.handlers.status = function (payload) {
        var key = payload.address_type + ':' + payload.address_value;
        return {
            success: true,
            opted_out: self.optout_store.indexOf(key) >= 0,
            created_at: new Date().toISOString(),
            message_id: 'the-message-id'
        };
    };

    self.handlers.cancel_optout = function (payload) {
        var key = payload.address_type + ':' + payload.address_value;
        var index = self.optout_store.indexOf(key);
        if(index > -1) {
            self.optout_store.splice(index, 1);
        }
        return {
            success: true,
            opted_out: false
        };
    };

});

this.DummyOptoutResource = DummyOptoutResource;
<commit_msg>remove legacy optoutstore<commit_after><|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var Parser = require('../lib/parser')
  , nodes = require('../lib/nodes')
  , should = require('should');

module.exports = {
  'test variable': function(){
    var parser = new Parser('@foo')
      , ast = parser.parse();

    ast.should.be.an.instanceof(nodes.Root);
    ast.nodes[0].should.be.an.instanceof(nodes.Expression);
    ast.nodes[0].nodes[0].should.be.an.instanceof(nodes.Variable);
    ast.nodes[0].nodes[0].should.have.property('name', 'foo');
    ast.nodes[0].nodes[0].val.should.be.an.instanceof(nodes.Null);
  },

  'test variable assignment': function(){
    var parser = new Parser('@light-color: #fff')
      , ast = parser.parse();

    ast.should.be.an.instanceof(nodes.Root);
    ast.nodes[0].should.be.an.instanceof(nodes.Expression);
    ast.nodes[0].nodes[0].should.be.an.instanceof(nodes.Variable);
    ast.nodes[0].nodes[0].should.have.property('name', 'light-color');
    ast.nodes[0].nodes[0].val.should.be.an.instanceof(nodes.Expression);
    ast.nodes[0].nodes[0].val.nodes[0].should.be.an.instanceof(nodes.Color);
  },

  'test selector': function(){
    var parser = new Parser('body a\n  color #fff\n  font-size 12px')
      , ast = parser.parse();

    ast.should.be.an.instanceof(nodes.Root);
    var selector = ast.nodes[0];
    selector.should.be.an.instanceof(nodes.Selector);
    selector.val.should.equal('body a');
    var block = selector.block.nodes;

    block[0].should.be.an.instanceof(nodes.Property);
    block[0].should.have.property('name', 'color');

    block[1].should.be.an.instanceof(nodes.Property);
    block[1].should.have.property('name', 'font-size');
  }
};<commit_msg>More Parser tests<commit_after>
/**
 * Module dependencies.
 */

var Parser = require('../lib/parser')
  , nodes = require('../lib/nodes')
  , should = require('should');

module.exports = {
  'test variable': function(){
    var parser = new Parser('@foo')
      , ast = parser.parse();

    ast.should.be.an.instanceof(nodes.Root);
    ast.nodes[0].should.be.an.instanceof(nodes.Expression);
    ast.nodes[0].nodes[0].should.be.an.instanceof(nodes.Variable);
    ast.nodes[0].nodes[0].should.have.property('name', 'foo');
    ast.nodes[0].nodes[0].val.should.be.an.instanceof(nodes.Null);
  },

  'test variable assignment': function(){
    var parser = new Parser('@light-color: #fff')
      , ast = parser.parse();

    ast.should.be.an.instanceof(nodes.Root);
    ast.nodes[0].should.be.an.instanceof(nodes.Expression);
    ast.nodes[0].nodes[0].should.be.an.instanceof(nodes.Variable);
    ast.nodes[0].nodes[0].should.have.property('name', 'light-color');
    ast.nodes[0].nodes[0].val.should.be.an.instanceof(nodes.Expression);
    ast.nodes[0].nodes[0].val.nodes[0].should.be.an.instanceof(nodes.Color);
  },

  'test selector': function(){
    var parser = new Parser('body a\n  color #fff\n  font-size 12px')
      , ast = parser.parse();

    ast.should.be.an.instanceof(nodes.Root);
    var selector = ast.nodes[0];
    selector.should.be.an.instanceof(nodes.Selector);
    selector.val.should.equal('body a');
    var block = selector.block.nodes;

    block[0].should.be.an.instanceof(nodes.Property);
    block[0].should.have.property('name', 'color');

    block[1].should.be.an.instanceof(nodes.Property);
    block[1].should.have.property('name', 'font-size');
  },

  'test arithmetic': function(){
    var parser = new Parser('15px + 5 - 2')
      , ast = parser.parse();

    var op = ast.nodes[0].nodes[0];
    op.should.be.an.instanceof(nodes.BinOp);
    op.should.have.property('op', '-');
    op.right.val.should.equal(2);

    var op = op.left;
    op.left.val.should.equal(15);
    op.left.type.should.equal('px');
    op.right.val.should.equal(5);
  }
};<|endoftext|>


<commit_before><commit_msg>Resolution de divers bugs de Webos.File.fstab.<commit_after><|endoftext|>


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

var should = require('should'),
    es = require('event-stream'),
    gulp = require('gulp');

delete require.cache[require.resolve('..')];
var plumber = require('../');
var fixturesGlob = ['./test/fixtures/*'];

describe('stream', function () {

    it('should emit `end` after source emit `finish`', function (done) {
        gulp.src(fixturesGlob)
            .pipe(plumber({ errorHandler: done }))
            .on('finish', done)
            .on('error', done);
    });

    it('should passThrough all incoming files', function (done) {
        gulp.src(fixturesGlob)
            .pipe(plumber({ errorHandler: done }))
            .pipe(es.writeArray(function (err, array) {
                array.should.eql(this.expected);
                done();
            }.bind(this)))
            .on('error', done);
    });

    it('should passThrough all incoming files with on(`data`) handler attached', function (done) {
        gulp.src(fixturesGlob)
            .pipe(plumber({ errorHandler: done }))
            .on('data', function (file) { should.exist(file); })
            .pipe(es.writeArray(function (err, array) {
                array.should.eql(this.expected);
                done();
            }.bind(this)))
            .on('error', done);
    });

    before(function (done) {
        gulp.src(fixturesGlob)
            .pipe(es.writeArray(function (err, array) {
                this.expected = array;
                done();
            }.bind(this)));
    });

});
<commit_msg>Added test for piping through es.readArray<commit_after>/*global describe, it, before */
'use strict';

var should = require('should'),
    es = require('event-stream'),
    gulp = require('gulp');

delete require.cache[require.resolve('..')];
var plumber = require('../');
var fixturesGlob = ['./test/fixtures/*'];

describe('stream', function () {

    it('should work with es.readarray', function (done) {
        var expected = ['1\n', '2\n', '3\n', '4\n', '5\n'];

        es.readArray([1, 2, 3, 4, 5])
            .pipe(plumber())
            .pipe(es.stringify())
            .pipe(es.writeArray(function (error, array) {
                array.should.eql(expected);
                done();
            }));
    });

    it('should emit `end` after source emit `finish`', function (done) {
        gulp.src(fixturesGlob)
            .pipe(plumber())
            .on('finish', done)
            .on('error', done);
    });

    it('should passThrough all incoming files', function (done) {
        gulp.src(fixturesGlob)
            .pipe(plumber({ errorHandler: done }))
            .pipe(es.writeArray(function (err, array) {
                array.should.eql(this.expected);
                done();
            }.bind(this)))
            .on('error', done);
    });

    it('should passThrough all incoming files with on(`data`) handler attached', function (done) {
        gulp.src(fixturesGlob)
            .pipe(plumber({ errorHandler: done }))
            .on('data', function (file) { should.exist(file); })
            .pipe(es.writeArray(function (err, array) {
                array.should.eql(this.expected);
                done();
            }.bind(this)))
            .on('error', done);
    });

    before(function (done) {
        gulp.src(fixturesGlob)
            .pipe(es.writeArray(function (err, array) {
                this.expected = array;
                done();
            }.bind(this)));
    });

});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'react-proptypes';

export default class CanvasPane extends React.Component {

    render() {
        const canvasLayerStyle = {
            position: 'absolute',
            width: this.props.width,
            height: this.props.height,
            background: this.props.style.backgroundColor,
        };

        return (

                <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink"
                     width={this.props.width} height={this.props.height}>
                    {this.drawWhiteboardCanvas()}
                </svg>

        );
    }

    drawWhiteboardCanvas() {
        return this.props.dataHolder.dataset
            .reduce((prev, element) => {
                if (!element.point) {
                    prev.push({
                        strokeWidth: null,
                        strokeColor: null,
                        values: [],
                    });
                    return prev;
                }

                let last = prev[prev.length - 1];
                last.strokeWidth = element.strokeWidth;
                last.strokeColor = element.strokeColor;
                last.values.push(element.point);
                return prev;
            }, [{
                strokeWidth: null,
                strokeColor: null,
                values: [],
            }])
            .filter((element) => {
                return element.values.length > 1;
            })
            .map((element, index) => {
                const k = index;
                const d = element.values.map((point, index) => {
                    if (index === 0) {
                        return 'M ' + point.x + ' ' + point.y;
                    } else {
                        return 'L ' + point.x + ' ' + point.y;
                    }
                });

                return (
                    <path key={k} d={d.join(' ')} fill="none" stroke={element.strokeColor} strokeWidth={element.strokeWidth}></path>
                );
            });
    }
}

CanvasPane.propTypes = {
    width: PropTypes.number,
    height: PropTypes.number,
    dataHolder: PropTypes.object,
    style: PropTypes.shape({
        backgroundColor: PropTypes.string,
    }),
};
<commit_msg>Render lines in order of layer indices<commit_after>import React from 'react';
import PropTypes from 'react-proptypes';

export default class CanvasPane extends React.Component {

    render() {
        const canvasLayerStyle = {
            position: 'absolute',
            width: this.props.width,
            height: this.props.height,
            background: this.props.style.backgroundColor,
        };

        return (

                <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink"
                     width={this.props.width} height={this.props.height}>
                    {this.drawWhiteboardCanvas()}
                </svg>

        );
    }

    drawWhiteboardCanvas() {
        return this.props.dataHolder.dataset
            .reduce((prev, element) => {
                if (!element.point) {
                    prev.forEach(p => {
                        p.push({
                            strokeWidth: null,
                            strokeColor: null,
                            values: [],
                        });
                    });
                    return prev;
                }

                if (!prev[element.layer]) {
                    prev[element.layer] = [{
                        strokeWidth: null,
                        strokeColor: null,
                        values: [],
                    }];
                }

                let last = prev[element.layer][prev[element.layer].length - 1];
                last.strokeWidth = element.strokeWidth;
                last.strokeColor = element.strokeColor;
                last.values.push(element.point);
                return prev;
            }, [[{
                strokeWidth: null,
                strokeColor: null,
                values: [],
            }]])
            .reduce((prev, element) => {
                return prev.concat(element);
            }, [])
            .filter((element) => {
                return element.values.length > 1;
            })
            .map((element, index) => {
                const k = index;
                const d = element.values.map((point, index) => {
                    if (index === 0) {
                        return 'M ' + point.x + ' ' + point.y;
                    } else {
                        return 'L ' + point.x + ' ' + point.y;
                    }
                });

                return (
                    <path key={k} d={d.join(' ')} fill="none" stroke={element.strokeColor} strokeWidth={element.strokeWidth}></path>
                );
            });
    }
}

CanvasPane.propTypes = {
    width: PropTypes.number,
    height: PropTypes.number,
    dataHolder: PropTypes.object,
    style: PropTypes.shape({
        backgroundColor: PropTypes.string,
    }),
};
<|endoftext|>


<commit_before>/**
 * Created by JiaHao on 18/8/15.
 */

var phantomBase = require('./../lib/phantomBase');

const testUrls = ['http://techcrunch.com/', 'https://www.facebook.com/'];

describe('Base PhantomJS functions', function () {
    this.timeout(30000);
    it('Can open a page', function (done) {
        phantomBase.openPage(testUrls[1], function (error, page, ph) {
            ph.exit();
            done(error);
        })
    })

});<commit_msg>Change test case to test with multiple urls<commit_after>/**
 * Created by JiaHao on 18/8/15.
 */

var async = require('async');
var phantomBase = require('./../lib/phantomBase');

const testUrls = ['http://techcrunch.com/', 'https://www.facebook.com/'];

describe('Testing base PhantomJS functions', function () {
    this.timeout(50000);
    it('Can open a page', function (done) {

        async.each(testUrls, function (testUrl, callback) {
            phantomBase.openPage(testUrl, function (error, page, ph) {
                ph.exit();
                callback(error);
            });
        }, function (error) {
           done(error);
        });

    })

});<|endoftext|>


<commit_before>import React, { PureComponent } from 'react'
import {
  defaultTo,
  F,
  ifElse,
  is,
  lensProp,
  over,
  pick,
  prop,
  when
} from 'ramda'
import classnames from 'classnames'
import styled from 'styled-components'

const StyledCell = styled.div`
  box-sizing: border-box;
  flex: 0 0 auto;
`
export default class Cell extends PureComponent {
  flexProperties = [
    'alignSelf',
    'flexBasis',
    'flexGrow',
    'flexShrink',
    'flex',
    'order'
  ]

  render() {
    const { breakPoint, children, columns } = this.props
    const spanOptions = over(
      lensProp('0'),
      defaultTo(columns),
      this.props.spanOptions
    )
    const span = prop(breakPoint, spanOptions)
    const cols = when(is(Object), prop('cols'))(span)
    const className = ifElse(is(Object), prop('className'), F)(span)
    const flexStyles = pick(this.flexProperties)(this.props)
    const width = `${cols / columns * 100}%`

    const cellClassName = classnames(
      { [className]: className }
    )

    return (
      <StyledCell style={{ ...flexStyles, width }} className={cellClassName}>
        {children}
      </StyledCell>
    )
  }
}
<commit_msg>Make Cell stateless functional component<commit_after>import React, { PureComponent } from 'react'
import {
  defaultTo,
  F,
  ifElse,
  is,
  lensProp,
  over,
  pick,
  prop,
  when
} from 'ramda'
import classnames from 'classnames'
import styled from 'styled-components'

const StyledCell = styled.div`
  box-sizing: border-box;
  flex: 0 0 auto;
`
const flexProperties = [
  'alignSelf',
  'flexBasis',
  'flexGrow',
  'flexShrink',
  'flex',
  'order'
]

export default function Cell(props) {
  const { breakPoint, children, columns, ...rest} = props
  const spanOptions = over(
    lensProp('0'),
    defaultTo(columns),
    props.spanOptions
  )
  const span = prop(breakPoint, spanOptions)
  const cols = when(is(Object), prop('cols'))(span)
  const className = ifElse(is(Object), prop('className'), F)(span)
  const flexStyles = pick(flexProperties)(rest)
  const width = `${cols / columns * 100}%`

  const cellClassName = classnames(
    { [className]: className }
  )

  return (
    <StyledCell style={{ ...flexStyles, width }} className={cellClassName}>
      {children}
    </StyledCell>
  )
}
<|endoftext|>