<commit_before>import * as assert from 'assert';
import Dat, { now } from '../lib/Dat';
import { random } from '../lib/Num';

describe('it should test Dat#', () => {
  describe('add()', () => {
    it('should support (what, number) syntax', () => {
      const date = new Date('1999-12-08T00:00:00.00Z');
      const wrap = new Dat(date);

      wrap.add('c', 999);
      wrap.add('s', 59);
      wrap.add('m', 59);
      wrap.add('h', 23);
      wrap.add('d', 2);
      wrap.add('w', 3);

      assert.strictEqual(date.toJSON(), '1999-12-31T23:59:59.999Z');
    });
    it('should support { [what]: number, ... } syntax', () => {
      const date = new Date('1999-12-08T00:00:00.00Z');
      const wrap = new Dat(date);

      wrap.add({
        c: 999,
        s: 59,
        m: 59,
        h: 23,
        d: 2,
        w: 3
      });

      assert.strictEqual(date.toJSON(), '1999-12-31T23:59:59.999Z');
    });
  });
  describe('expires()', () => {
    it('should return promise, that resolves when context comes', (done) => {
      const date = new Date(now() + 100);
      const wrap = new Dat(date);
      const unique = {};

      wrap.expires(unique)
        .then((value) => {
          assert.strictEqual(value, unique);

          done();
        })
        .catch(done);
    });
  });
  describe('format()', () => {
    it('should return formatted date', () => {
      const date = new Date('1999-12-31T23:59:59.999Z');
      const wrap = new Dat(date);

      assert.strictEqual(wrap.format('ss.ccc'), '59.999');
    });
    it('should support second argument', () => {
      const date = new Date('1999-12-31T23:59:59.999Z');
      const wrap = new Dat(date);

      assert.strictEqual(wrap.format('ss: $ss. ccc: $ccc.', '$'), 'ss: 59. ccc: 999.');
    });
  });
  describe('formatUTC()', () => {
    it('should return formatted date', () => {
      const date = new Date('1999-12-31T23:59:59.999Z');
      const wrap = new Dat(date);

      assert.strictEqual(wrap.formatUTC('yyyy-MM-ddThh:mm:ss.cccZ'), date.toISOString());
    });
    it('should support second argument', () => {
      const date = new Date('1999-12-31T23:59:59.999Z');
      const wrap = new Dat(date);

      assert.strictEqual(
        wrap.formatUTC('Year is $yyyy.', '$'),
        'Year is 1999.'
      );
      assert.strictEqual(
        wrap.formatUTC('Month name is $MMMM.', '$'),
        'Month name is December.'
      );
      assert.strictEqual(
        wrap.formatUTC('Month alias is $MMM.', '$'),
        'Month alias is Dec.'
      );
      assert.strictEqual(
        wrap.formatUTC('Month number is $M.', '$'),
        'Month number is 12.'
      );
      assert.strictEqual(
        wrap.formatUTC('Day of the week name is $dddd.', '$'),
        'Day of the week name is Friday.'
      );
      assert.strictEqual(
        wrap.formatUTC('Day of the week alias is $ddd.', '$'),
        'Day of the week alias is Fri.'
      );
      assert.strictEqual(
        wrap.formatUTC('Date is $yyyy-$MM-$dd.', '$'),
        'Date is 1999-12-31.'
      );
      assert.strictEqual(
        wrap.formatUTC('Time is $hh:$mm:$ss.$ccc.', '$'),
        'Time is 23:59:59.999.'
      );
    });
  });
  describe('get()', () => {
    it('should return proper date parameter', () => {
      const date = new Date('1999-12-31T23:59:59.999Z');
      const wrap = new Dat(date);

      assert.strictEqual(wrap.get('c'), date.getMilliseconds());
      assert.strictEqual(wrap.get('s'), date.getSeconds());
      assert.strictEqual(wrap.get('m'), date.getMinutes());
      assert.strictEqual(wrap.get('h'), date.getHours());
      assert.strictEqual(wrap.get('d'), date.getDate());
      assert.strictEqual(wrap.get('dw'), date.getDay());
      assert.strictEqual(wrap.get('M'), date.getMonth() + 1);
      assert.strictEqual(wrap.get('y'), date.getFullYear());
    });
  });
  describe('getUTC()', () => {
    it('should return proper date utc parameter', () => {
      const date = new Date('1999-12-31T23:59:59.999Z');
      const wrap = new Dat(date);

      assert.strictEqual(wrap.getUTC('c'), date.getUTCMilliseconds());
      assert.strictEqual(wrap.getUTC('s'), date.getUTCSeconds());
      assert.strictEqual(wrap.getUTC('m'), date.getUTCMinutes());
      assert.strictEqual(wrap.getUTC('h'), date.getUTCHours());
      assert.strictEqual(wrap.getUTC('d'), date.getUTCDate());
      assert.strictEqual(wrap.getUTC('dw'), date.getUTCDay());
      assert.strictEqual(wrap.getUTC('M'), date.getUTCMonth() + 1);
      assert.strictEqual(wrap.getUTC('y'), date.getUTCFullYear());
    });
  });
  describe('isAfter()', () => {
    it('should return true with argument before context', () => {
      const date = new Date();
      const wrap = new Dat(date);
      const before = new Date(now() - 100);

      assert.strictEqual(wrap.isAfter(before), true);
    });
    it('should return false with argument after context', () => {
      const date = new Date();
      const wrap = new Dat(date);
      const after = new Date(now() + 100);

      assert.strictEqual(wrap.isAfter(after), false);
    });
  });
  describe('isBefore()', () => {
    it('should return true with argument after context', () => {
      const date = new Date();
      const wrap = new Dat(date);
      const after = new Date(now() + 100);

      assert.strictEqual(wrap.isBefore(after), true);
    });
    it('should return false with argument before context', () => {
      const date = new Date();
      const wrap = new Dat(date);
      const before = new Date(now() - 100);

      assert.strictEqual(wrap.isBefore(before), false);
    });
  });
  describe('isBetween()', () => {
    it('should return true with first argument before context and second after', () => {
      const date = new Date();
      const wrap = new Dat(date);
      const before = new Date(now() - 100);
      const after = new Date(now() + 100);

      assert.strictEqual(wrap.isBetween(before, after), true);
    });
    it('should return true with first argument after context or second before', () => {
      const date = new Date();
      const wrap = new Dat(date);
      const before = new Date(now() - 100);
      const after = new Date(now() + 100);

      assert.strictEqual(wrap.isBetween(before, before), false);
      assert.strictEqual(wrap.isBetween(after, after), false);
      assert.strictEqual(wrap.isBetween(after, before), false);
    });
  });
  describe('isInvalid()', () => {
    it('should return true with invalid context', () => {
      const date = new Date('a');
      const wrap = new Dat(date);

      assert.strictEqual(wrap.isInvalid(), true);
    });
    it('should return false with not invalid context', () => {
      const date = new Date();
      const wrap = new Dat(date);

      assert.strictEqual(wrap.isInvalid(), false);
    });
  });
  describe('isPassed()', () => {
    it('should return true with context before now', () => {
      const date = new Date(now() - 100);
      const wrap = new Dat(date);

      assert.strictEqual(wrap.isPassed(), true);
    });
    it('should return false with context after now', () => {
      const date = new Date(now() + 100);
      const wrap = new Dat(date);

      assert.strictEqual(wrap.isPassed(), false);
    });
  });
  describe('ofOne()', () => {
    it('should return true with second argument of one <first argument>', () => {
      const date1 = new Date('1999-12-31T23:59:59.999Z');
      const date2 = new Date('1999-12-31T23:59:59.998Z');
      const wrap = new Dat(date1);

      assert.strictEqual(wrap.ofOne('s', date2), true);
      assert.strictEqual(wrap.ofOne('m', date2), true);
      assert.strictEqual(wrap.ofOne('h', date2), true);
      assert.strictEqual(wrap.ofOne('d', date2), true);
      assert.strictEqual(wrap.ofOne('M', date2), true);
      assert.strictEqual(wrap.ofOne('y', date2), true);
    });
    it('should return true with second argument not of one <first argument>', () => {
      const date1 = new Date('1999-12-31T23:59:59.999Z');
      const date2 = new Date('1998-12-31T23:59:59.998Z');
      const wrap = new Dat(date1);

      assert.strictEqual(wrap.ofOne('s', date2), false);
      assert.strictEqual(wrap.ofOne('m', date2), false);
      assert.strictEqual(wrap.ofOne('h', date2), false);
      assert.strictEqual(wrap.ofOne('d', date2), false);
      assert.strictEqual(wrap.ofOne('M', date2), false);
      assert.strictEqual(wrap.ofOne('y', date2), false);
    });
  });
  describe('set()', () => {
    it('should support (what, number) syntax', () => {
      const date = new Date();
      const wrap = new Dat(date);

      wrap.set('y', 1999);
      wrap.set('M', 12);
      wrap.set('d', 31);
      wrap.set('h', 23);
      wrap.set('m', 59);
      wrap.set('s', 59);
      wrap.set('c', 999);

      assert.strictEqual(date.getMilliseconds(), 999);
      assert.strictEqual(date.getSeconds(), 59);
      assert.strictEqual(date.getMinutes(), 59);
      assert.strictEqual(date.getHours(), 23);
      assert.strictEqual(date.getDate(), 31);
      assert.strictEqual(date.getMonth(), 11);
      assert.strictEqual(date.getFullYear(), 1999);
    });
    it('should support { [what]: number, ... } syntax', () => {
      const date = new Date();
      const wrap = new Dat(date);

      wrap.set({
        y: 1999,
        M: 12,
        d: 31,
        h: 23,
        m: 59,
        s: 59,
        c: 999
      });

      assert.strictEqual(date.getMilliseconds(), 999);
      assert.strictEqual(date.getSeconds(), 59);
      assert.strictEqual(date.getMinutes(), 59);
      assert.strictEqual(date.getHours(), 23);
      assert.strictEqual(date.getDate(), 31);
      assert.strictEqual(date.getMonth(), 11);
      assert.strictEqual(date.getFullYear(), 1999);
    });
  });
  describe('setUTC()', () => {
    it('should support (what, number) syntax', () => {
      const date = new Date();
      const wrap = new Dat(date);

      wrap.setUTC('y', 1999);
      wrap.setUTC('M', 12);
      wrap.setUTC('d', 31);
      wrap.setUTC('h', 23);
      wrap.setUTC('m', 59);
      wrap.setUTC('s', 59);
      wrap.setUTC('c', 999);

      assert.strictEqual(date.toJSON(), '1999-12-31T23:59:59.999Z');
    });
    it('should support { [what]: number, ... } syntax', () => {
      const date = new Date();
      const wrap = new Dat(date);

      wrap.setUTC({
        y: 1999,
        M: 12,
        d: 31,
        h: 23,
        m: 59,
        s: 59,
        c: 999
      });

      assert.strictEqual(date.toJSON(), '1999-12-31T23:59:59.999Z');
    });
  });
  describe('time()', () => {
    it('should get time without arguments', () => {
      const time = now() - random(50, 100);
      const date = new Date(time);
      const wrap = new Dat(date);

      assert.strictEqual(wrap.time(), date.getTime());
    });
    it('should set time of argument', () => {
      const time = now() - random(50, 100);
      const date = new Date(time);
      const wrap = new Dat(date);

      wrap.time(time);

      assert.strictEqual(date.getTime(), time);
    });
  });
  describe('toLocaleString()', () => {
    it('should return the same as <context>.toLocaleString()', () => {
      const date = new Date();
      const wrap = new Dat(date);

      assert.strictEqual(wrap.toLocaleString(), date.toLocaleString());
    });
  });
  describe('toString()', () => {
    it('should return the same as <context>.toString()', () => {
      const date = new Date();
      const wrap = new Dat(date);

      assert.strictEqual(wrap.toString(), date.toString());
    });
  });
  describe('valueOf()', () => {
    it('should return the same as <context>.valueOf()', () => {
      const date = new Date();
      const wrap = new Dat(date);

      assert.strictEqual(wrap.valueOf(), date.valueOf());
    });
  });
});
<commit_msg>Dat: export assert methods directly.<commit_after>import { strictEqual } from 'assert';
import Dat, { now } from '../lib/Dat';
import { random } from '../lib/Num';

describe('it should test Dat#', () => {
  describe('add()', () => {
    it('should support (what, number) syntax', () => {
      const date = new Date('1999-12-08T00:00:00.00Z');
      const wrap = new Dat(date);

      wrap.add('c', 999);
      wrap.add('s', 59);
      wrap.add('m', 59);
      wrap.add('h', 23);
      wrap.add('d', 2);
      wrap.add('w', 3);

      strictEqual(date.toJSON(), '1999-12-31T23:59:59.999Z');
    });
    it('should support { [what]: number, ... } syntax', () => {
      const date = new Date('1999-12-08T00:00:00.00Z');
      const wrap = new Dat(date);

      wrap.add({
        c: 999,
        s: 59,
        m: 59,
        h: 23,
        d: 2,
        w: 3
      });

      strictEqual(date.toJSON(), '1999-12-31T23:59:59.999Z');
    });
  });
  describe('expires()', () => {
    it('should return promise, that resolves when context comes', (done) => {
      const date = new Date(now() + 100);
      const wrap = new Dat(date);
      const unique = {};

      wrap.expires(unique)
        .then((value) => {
          strictEqual(value, unique);

          done();
        })
        .catch(done);
    });
  });
  describe('format()', () => {
    it('should return formatted date', () => {
      const date = new Date('1999-12-31T23:59:59.999Z');
      const wrap = new Dat(date);

      strictEqual(wrap.format('ss.ccc'), '59.999');
    });
    it('should support second argument', () => {
      const date = new Date('1999-12-31T23:59:59.999Z');
      const wrap = new Dat(date);

      strictEqual(wrap.format('ss: $ss. ccc: $ccc.', '$'), 'ss: 59. ccc: 999.');
    });
  });
  describe('formatUTC()', () => {
    it('should return formatted date', () => {
      const date = new Date('1999-12-31T23:59:59.999Z');
      const wrap = new Dat(date);

      strictEqual(wrap.formatUTC('yyyy-MM-ddThh:mm:ss.cccZ'), date.toISOString());
    });
    it('should support second argument', () => {
      const date = new Date('1999-12-31T23:59:59.999Z');
      const wrap = new Dat(date);

      strictEqual(
        wrap.formatUTC('Year is $yyyy.', '$'),
        'Year is 1999.'
      );
      strictEqual(
        wrap.formatUTC('Month name is $MMMM.', '$'),
        'Month name is December.'
      );
      strictEqual(
        wrap.formatUTC('Month alias is $MMM.', '$'),
        'Month alias is Dec.'
      );
      strictEqual(
        wrap.formatUTC('Month number is $M.', '$'),
        'Month number is 12.'
      );
      strictEqual(
        wrap.formatUTC('Day of the week name is $dddd.', '$'),
        'Day of the week name is Friday.'
      );
      strictEqual(
        wrap.formatUTC('Day of the week alias is $ddd.', '$'),
        'Day of the week alias is Fri.'
      );
      strictEqual(
        wrap.formatUTC('Date is $yyyy-$MM-$dd.', '$'),
        'Date is 1999-12-31.'
      );
      strictEqual(
        wrap.formatUTC('Time is $hh:$mm:$ss.$ccc.', '$'),
        'Time is 23:59:59.999.'
      );
    });
  });
  describe('get()', () => {
    it('should return proper date parameter', () => {
      const date = new Date('1999-12-31T23:59:59.999Z');
      const wrap = new Dat(date);

      strictEqual(wrap.get('c'), date.getMilliseconds());
      strictEqual(wrap.get('s'), date.getSeconds());
      strictEqual(wrap.get('m'), date.getMinutes());
      strictEqual(wrap.get('h'), date.getHours());
      strictEqual(wrap.get('d'), date.getDate());
      strictEqual(wrap.get('dw'), date.getDay());
      strictEqual(wrap.get('M'), date.getMonth() + 1);
      strictEqual(wrap.get('y'), date.getFullYear());
    });
  });
  describe('getUTC()', () => {
    it('should return proper date utc parameter', () => {
      const date = new Date('1999-12-31T23:59:59.999Z');
      const wrap = new Dat(date);

      strictEqual(wrap.getUTC('c'), date.getUTCMilliseconds());
      strictEqual(wrap.getUTC('s'), date.getUTCSeconds());
      strictEqual(wrap.getUTC('m'), date.getUTCMinutes());
      strictEqual(wrap.getUTC('h'), date.getUTCHours());
      strictEqual(wrap.getUTC('d'), date.getUTCDate());
      strictEqual(wrap.getUTC('dw'), date.getUTCDay());
      strictEqual(wrap.getUTC('M'), date.getUTCMonth() + 1);
      strictEqual(wrap.getUTC('y'), date.getUTCFullYear());
    });
  });
  describe('isAfter()', () => {
    it('should return true with argument before context', () => {
      const date = new Date();
      const wrap = new Dat(date);
      const before = new Date(now() - 100);

      strictEqual(wrap.isAfter(before), true);
    });
    it('should return false with argument after context', () => {
      const date = new Date();
      const wrap = new Dat(date);
      const after = new Date(now() + 100);

      strictEqual(wrap.isAfter(after), false);
    });
  });
  describe('isBefore()', () => {
    it('should return true with argument after context', () => {
      const date = new Date();
      const wrap = new Dat(date);
      const after = new Date(now() + 100);

      strictEqual(wrap.isBefore(after), true);
    });
    it('should return false with argument before context', () => {
      const date = new Date();
      const wrap = new Dat(date);
      const before = new Date(now() - 100);

      strictEqual(wrap.isBefore(before), false);
    });
  });
  describe('isBetween()', () => {
    it('should return true with first argument before context and second after', () => {
      const date = new Date();
      const wrap = new Dat(date);
      const before = new Date(now() - 100);
      const after = new Date(now() + 100);

      strictEqual(wrap.isBetween(before, after), true);
    });
    it('should return true with first argument after context or second before', () => {
      const date = new Date();
      const wrap = new Dat(date);
      const before = new Date(now() - 100);
      const after = new Date(now() + 100);

      strictEqual(wrap.isBetween(before, before), false);
      strictEqual(wrap.isBetween(after, after), false);
      strictEqual(wrap.isBetween(after, before), false);
    });
  });
  describe('isInvalid()', () => {
    it('should return true with invalid context', () => {
      const date = new Date('a');
      const wrap = new Dat(date);

      strictEqual(wrap.isInvalid(), true);
    });
    it('should return false with not invalid context', () => {
      const date = new Date();
      const wrap = new Dat(date);

      strictEqual(wrap.isInvalid(), false);
    });
  });
  describe('isPassed()', () => {
    it('should return true with context before now', () => {
      const date = new Date(now() - 100);
      const wrap = new Dat(date);

      strictEqual(wrap.isPassed(), true);
    });
    it('should return false with context after now', () => {
      const date = new Date(now() + 100);
      const wrap = new Dat(date);

      strictEqual(wrap.isPassed(), false);
    });
  });
  describe('ofOne()', () => {
    it('should return true with second argument of one <first argument>', () => {
      const date1 = new Date('1999-12-31T23:59:59.999Z');
      const date2 = new Date('1999-12-31T23:59:59.998Z');
      const wrap = new Dat(date1);

      strictEqual(wrap.ofOne('s', date2), true);
      strictEqual(wrap.ofOne('m', date2), true);
      strictEqual(wrap.ofOne('h', date2), true);
      strictEqual(wrap.ofOne('d', date2), true);
      strictEqual(wrap.ofOne('M', date2), true);
      strictEqual(wrap.ofOne('y', date2), true);
    });
    it('should return true with second argument not of one <first argument>', () => {
      const date1 = new Date('1999-12-31T23:59:59.999Z');
      const date2 = new Date('1998-12-31T23:59:59.998Z');
      const wrap = new Dat(date1);

      strictEqual(wrap.ofOne('s', date2), false);
      strictEqual(wrap.ofOne('m', date2), false);
      strictEqual(wrap.ofOne('h', date2), false);
      strictEqual(wrap.ofOne('d', date2), false);
      strictEqual(wrap.ofOne('M', date2), false);
      strictEqual(wrap.ofOne('y', date2), false);
    });
  });
  describe('set()', () => {
    it('should support (what, number) syntax', () => {
      const date = new Date();
      const wrap = new Dat(date);

      wrap.set('y', 1999);
      wrap.set('M', 12);
      wrap.set('d', 31);
      wrap.set('h', 23);
      wrap.set('m', 59);
      wrap.set('s', 59);
      wrap.set('c', 999);

      strictEqual(date.getMilliseconds(), 999);
      strictEqual(date.getSeconds(), 59);
      strictEqual(date.getMinutes(), 59);
      strictEqual(date.getHours(), 23);
      strictEqual(date.getDate(), 31);
      strictEqual(date.getMonth(), 11);
      strictEqual(date.getFullYear(), 1999);
    });
    it('should support { [what]: number, ... } syntax', () => {
      const date = new Date();
      const wrap = new Dat(date);

      wrap.set({
        y: 1999,
        M: 12,
        d: 31,
        h: 23,
        m: 59,
        s: 59,
        c: 999
      });

      strictEqual(date.getMilliseconds(), 999);
      strictEqual(date.getSeconds(), 59);
      strictEqual(date.getMinutes(), 59);
      strictEqual(date.getHours(), 23);
      strictEqual(date.getDate(), 31);
      strictEqual(date.getMonth(), 11);
      strictEqual(date.getFullYear(), 1999);
    });
  });
  describe('setUTC()', () => {
    it('should support (what, number) syntax', () => {
      const date = new Date();
      const wrap = new Dat(date);

      wrap.setUTC('y', 1999);
      wrap.setUTC('M', 12);
      wrap.setUTC('d', 31);
      wrap.setUTC('h', 23);
      wrap.setUTC('m', 59);
      wrap.setUTC('s', 59);
      wrap.setUTC('c', 999);

      strictEqual(date.toJSON(), '1999-12-31T23:59:59.999Z');
    });
    it('should support { [what]: number, ... } syntax', () => {
      const date = new Date();
      const wrap = new Dat(date);

      wrap.setUTC({
        y: 1999,
        M: 12,
        d: 31,
        h: 23,
        m: 59,
        s: 59,
        c: 999
      });

      strictEqual(date.toJSON(), '1999-12-31T23:59:59.999Z');
    });
  });
  describe('time()', () => {
    it('should get time without arguments', () => {
      const time = now() - random(50, 100);
      const date = new Date(time);
      const wrap = new Dat(date);

      strictEqual(wrap.time(), date.getTime());
    });
    it('should set time of argument', () => {
      const time = now() - random(50, 100);
      const date = new Date(time);
      const wrap = new Dat(date);

      wrap.time(time);

      strictEqual(date.getTime(), time);
    });
  });
  describe('toLocaleString()', () => {
    it('should return the same as <context>.toLocaleString()', () => {
      const date = new Date();
      const wrap = new Dat(date);

      strictEqual(wrap.toLocaleString(), date.toLocaleString());
    });
  });
  describe('toString()', () => {
    it('should return the same as <context>.toString()', () => {
      const date = new Date();
      const wrap = new Dat(date);

      strictEqual(wrap.toString(), date.toString());
    });
  });
  describe('valueOf()', () => {
    it('should return the same as <context>.valueOf()', () => {
      const date = new Date();
      const wrap = new Dat(date);

      strictEqual(wrap.valueOf(), date.valueOf());
    });
  });
});
<|endoftext|>


<commit_before>const postcss = require('postcss');
const match = require('minimatch');

function PostPostCSSPlugin(plugins) {
  this.postPostCssPlugins = plugins;
}

PostPostCSSPlugin.prototype.apply = function(compiler) {
  compiler.plugin("compilation", (compilation) => {
    compilation.plugin('optimize-chunk-assets', (_, done) => {
      Promise.all(
        Object.keys(compilation.assets)
          .map(key => {
            if (match(key, '**/*.css')) {
              const src = compilation.assets[key].source();

              return postcss(this.postPostCssPlugins)
                .process(src)
                .then(res => {
                  compilation.assets[key] = {
                    source: () => res.css,
                    size: () => res.css.length
                  };

                  return Promise.resolve();
                })
            } else {
              return Promise.resolve(compilation.assets[key]);
            }

          })
      ).then(() => {
        done();
      })

    });
  });
}

module.exports = PostPostCSSPlugin;
<commit_msg>makes css images relative<commit_after>const postcss = require('postcss');
const match = require('minimatch');

const makeAbsolutePathRelative = output => {
  return output
    .replace(/url\(\/assets/gi, `url(.`)
    .replace(/url\(\"\/assets/gi, `url(".`)
}

function PostPostCSSPlugin(plugins) {
  this.postPostCssPlugins = plugins;
}

PostPostCSSPlugin.prototype.apply = function(compiler) {
  compiler.plugin("compilation", (compilation) => {
    compilation.plugin('optimize-chunk-assets', (_, done) => {
      Promise.all(
        Object.keys(compilation.assets)
          .map(key => {
            if (match(key, '**/*.css')) {
              const src = compilation.assets[key].source();

              return postcss(this.postPostCssPlugins)
                .process(src)
                .then(res => {
                  res.css = makeAbsolutePathRelative(res.css);

                  compilation.assets[key] = {
                    source: () => res.css,
                    size: () => res.css.length
                  };

                  return Promise.resolve();
                })
                .catch(e => {
                  done(e);
                })
            } else {
              return Promise.resolve(compilation.assets[key]);
            }

          })
      ).then(() => {
        done();
      })

    });
  });
}

module.exports = PostPostCSSPlugin;
<|endoftext|>


<commit_before>'use babel';
'use strict';

/**
 * Handles dispatching commands
 * @class CommandDispatcher
 * @param {Bot} bot - Bot instance
 */
export default class CommandDispatcher
{
	constructor(bot)
	{
		/** @type {Bot} */
		this._bot = bot;

		// Register message listener
		if (!this._bot.passive)
		{
			this._bot.on('message', message =>
			{
				this.handleMessage(message);
			});
		}
	}

	/**
	 * Determine if message is a valid command call and send to {@link CommandDispatcher#dispatch}
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {external:Message} message - Discord.js message object
	 * @returns {*}
	 */
	handleMessage(message)
	{
		let config = this._bot.config;
		if (this._bot.selfbot && message.author !== this._bot.user) return false;
		if (message.author.bot) return false;
		let original = message.content;

		let { command, mentions, args, content, dm } = this.processContent(message);
		message.content = content;

		if (dm && !command && !this._bot.selfbot)
		{
			return this.commandNotFoundError(message);
		}
		else if (!command)
		{
			message.content = original;
			return false;
		}

		let guildStorage = !dm ? this._bot.guildStorages.get(message.guild) : null;
		if (!dm && guildStorage.settingExists('disabledGroups')
			&& guildStorage.getSetting('disabledGroups').includes(command.group)) return false;
		if (command.ownerOnly && !config.owner.includes(message.author.id)) return false;
		if (dm && command.guildOnly) return this.guildOnlyError(message);

		let missingPermissions = this.checkPermissions(dm, message, command);
		if (missingPermissions.length > 0) return this.missingPermissionsError(missingPermissions, message);

		if (!this.hasRoles(dm, message, command)) return this.missingRolesError(message, command);

		return this.dispatch(command, message, args, mentions, original);
	}

	/**
	 * Processes message content, finding the command to execute and creating an
	 * object containing the found command, mentions, args, processed content, and
	 * if the message is a DM
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {external:Message} message - Discord.js message object
	 * @returns {Object}
	 */
	processContent(message)
	{
		let dm = message.channel.type === 'dm' || message.channel.type === 'group';
		let mentions;
		let duplicateMention;
		let regexMentions = message.content.match(/<@!?\d+>/g);
		if (regexMentions && regexMentions.length > 1)
		{
			let firstMention = regexMentions.shift();
			duplicateMention = regexMentions.includes(firstMention);
		}
		mentions = message.mentions.users.array().sort((a, b) =>
			message.content.indexOf(a.id) - message.content.indexOf(b.id));

		let botMention = /^<@!?\d+>.+/.test(message.content)
			&& mentions[0].id === this._bot.user.id
			&& !this._bot.selfbot;

		let content;
		if (botMention && !duplicateMention)
		{
			content = message.content.replace(/<@!?\d+>/g, '').trim();
			mentions = mentions.slice(1);
		}
		else if (botMention && duplicateMention)
		{
			content = message.content.replace(/<@!?\d+>/g, '').trim();
		}
		else if (!dm && (message.content.startsWith(this._bot.getPrefix(message.guild))
			|| !this._bot.getPrefix(message.guild)))
		{
			content = message.content.slice(this._bot.getPrefix(message.guild)
				? this._bot.getPrefix(message.guild).length : 0).replace(/<@!?\d+>/g, '').trim();
		}
		else if (dm)
		{
			if (/<@!?\d+>.+/.test(message.content))
			{
				content = message.content.replace(/<@!?\d+>/g, '').trim();
				mentions = mentions.slice(1);
			}
			else
			{
				content = message.content.trim();
			}
		}
		else
		{
			return false;
		}
		content = content.replace(/ +/g, ' ');

		let commandName = content.split(' ')[0];
		let command = this._bot.commands.findByNameOrAlias(commandName);

		let args = content.split(command ? command.argOpts.separator : ' ').slice(1)
			.map(a => !isNaN(a) && command && !command.argOpts.stringArgs ? parseFloat(a) : a)
			.map(a => typeof a === 'string' ? a.trim() : a);

		return { command: command, mentions: mentions, args: args, content: content, dm: dm };
	}

	/**
	 * Get a list of missing permissions for the command caller for the
	 * given command, if any
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {boolean} dm - Whether the message is a DM
	 * @param {external:Message} message - Discord.js message object
	 * @param {Command} command - Command found by the dispatcher
	 * @returns {external:PermissionResolvable[]}
	 */
	checkPermissions(dm, message, command)
	{
		return dm ? [] : command.permissions.filter(a =>
			!message.channel.permissionsFor(message.author).hasPermission(a));
	}

	/**
	 * Checks if the command caller has roles for the given command
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {boolean} dm - Whether the message is a DM
	 * @param {external:Message} message - Discord.js message object
	 * @param {Command} command - Command found by the dispatcher
	 * @returns {boolean}
	 */
	hasRoles(dm, message, command)
	{
		return command.roles.length === 0 || dm
			|| message.member.roles.filter(role =>
				command.roles.includes(role.name)).size > 0;
	}

	/**
	 * Send a 'command not found' error message to the channel
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {external:Message} message - Discord.js message object
	 * @returns {Promise<external:Message>}
	 */
	commandNotFoundError(message)
	{
		return message.channel.sendMessage(``
			+ `Sorry, I didn't recognize any command in your message.\n`
			+ `Try saying "help" to view a list of commands you can use in `
			+ `this DM, or try calling the\nhelp command in a server channel `
			+ `to see what commands you can use there!`);
	}

	/**
	 * Send a 'guild only' error message to the channel
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {external:Message} message - Discord.js message object
	 * @returns {Promise<external:Message>}
	 */
	guildOnlyError(message)
	{
		return message.channel.sendMessage(``
			+ `That command is for servers only. Try saying "help" to see a `
			+ `list of commands you can use in this DM`);
	}

	/**
	 * Send a 'missing permissions' error message to the channel
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {external:PermissionResolvable[]} missing - Array of missing permissions
	 * @param {external:Message} message - Discord.js message object
	 * @returns {Promise<external:Message>}
	 */
	missingPermissionsError(missing, message)
	{
		return message[`${this._bot.selfbot ? 'channel' : 'author'}`].sendMessage(``
			+ `**You're missing the following permission`
			+ `${missing.length > 1 ? 's' : ''} `
			+ `for that command:**\n\`\`\`css\n`
			+ `${missing.join(', ')}\n\`\`\``)
				.then(response =>
				{
					if (this._bot.selfbot) response.delete(10 * 1000);
				});
	}

	/**
	 * Send a 'missing roles' error message to the channel
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {external:Message} message - Discord.js message object
	 * @param {Command} command - Command found by the dispatcher
	 * @returns {Promise<external:Message>}
	 */
	missingRolesError(message, command)
	{
		return message[`${this._bot.selfbot ? 'channel' : 'author'}`].sendMessage(``
			+ `**You must have ${command.roles.length > 1
				? 'one of the following roles' : 'the following role'}`
			+ ` to use that command:**\n\`\`\`css\n`
			+ `${command.roles.join(', ')}\n\`\`\``)
				.then(response =>
				{
					if (this._bot.selfbot) response.delete(10 * 1000);
				});
	}

	/**
	 * Pass the necessary items to the found Command's {@link Command#action} method
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {Command} command - The command found by the dispatcher
	 * @param {external:Message} message - Discord.js message object
	 * @param {args[]} args - An array containing the args parsed from the command calling message
	 * @param {external:User[]} mentions - An array containing the Discord.js User
	 * objects parsed from the mentions contained in a message
	 * @param {string} original - The original raw content of the message that called the command
	 */
	async dispatch(command, message, args, mentions, original)
	{
		try
		{
			command.action(message, args, mentions, original);
		}
		catch (err)
		{
			console.log(err); // eslint-disable-line no-console
		}
	}
}
<commit_msg>Emit event on successful command call<commit_after>'use babel';
'use strict';

/**
 * Handles dispatching commands
 * @class CommandDispatcher
 * @param {Bot} bot - Bot instance
 */
export default class CommandDispatcher
{
	constructor(bot)
	{
		/** @type {Bot} */
		this._bot = bot;

		// Register message listener
		if (!this._bot.passive)
		{
			this._bot.on('message', message =>
			{
				this.handleMessage(message);
			});
		}
	}

	/**
	 * Determine if message is a valid command call and send to {@link CommandDispatcher#dispatch}
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {external:Message} message - Discord.js message object
	 * @returns {*}
	 */
	handleMessage(message)
	{
		let config = this._bot.config;
		if (this._bot.selfbot && message.author !== this._bot.user) return false;
		if (message.author.bot) return false;
		let original = message.content;

		let { command, mentions, args, content, dm } = this.processContent(message);
		message.content = content;

		if (dm && !command && !this._bot.selfbot)
		{
			return this.commandNotFoundError(message);
		}
		else if (!command)
		{
			message.content = original;
			return false;
		}

		let guildStorage = !dm ? this._bot.guildStorages.get(message.guild) : null;
		if (!dm && guildStorage.settingExists('disabledGroups')
			&& guildStorage.getSetting('disabledGroups').includes(command.group)) return false;
		if (command.ownerOnly && !config.owner.includes(message.author.id)) return false;
		if (dm && command.guildOnly) return this.guildOnlyError(message);

		let missingPermissions = this.checkPermissions(dm, message, command);
		if (missingPermissions.length > 0) return this.missingPermissionsError(missingPermissions, message);

		if (!this.hasRoles(dm, message, command)) return this.missingRolesError(message, command);

		return this.dispatch(command, message, args, mentions, original);
	}

	/**
	 * Processes message content, finding the command to execute and creating an
	 * object containing the found command, mentions, args, processed content, and
	 * if the message is a DM
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {external:Message} message - Discord.js message object
	 * @returns {Object}
	 */
	processContent(message)
	{
		let dm = message.channel.type === 'dm' || message.channel.type === 'group';
		let mentions;
		let duplicateMention;
		let regexMentions = message.content.match(/<@!?\d+>/g);
		if (regexMentions && regexMentions.length > 1)
		{
			let firstMention = regexMentions.shift();
			duplicateMention = regexMentions.includes(firstMention);
		}
		mentions = message.mentions.users.array().sort((a, b) =>
			message.content.indexOf(a.id) - message.content.indexOf(b.id));

		let botMention = /^<@!?\d+>.+/.test(message.content)
			&& mentions[0].id === this._bot.user.id
			&& !this._bot.selfbot;

		let content;
		if (botMention && !duplicateMention)
		{
			content = message.content.replace(/<@!?\d+>/g, '').trim();
			mentions = mentions.slice(1);
		}
		else if (botMention && duplicateMention)
		{
			content = message.content.replace(/<@!?\d+>/g, '').trim();
		}
		else if (!dm && (message.content.startsWith(this._bot.getPrefix(message.guild))
			|| !this._bot.getPrefix(message.guild)))
		{
			content = message.content.slice(this._bot.getPrefix(message.guild)
				? this._bot.getPrefix(message.guild).length : 0).replace(/<@!?\d+>/g, '').trim();
		}
		else if (dm)
		{
			if (/<@!?\d+>.+/.test(message.content))
			{
				content = message.content.replace(/<@!?\d+>/g, '').trim();
				mentions = mentions.slice(1);
			}
			else
			{
				content = message.content.trim();
			}
		}
		else
		{
			return false;
		}
		content = content.replace(/ +/g, ' ');

		let commandName = content.split(' ')[0];
		let command = this._bot.commands.findByNameOrAlias(commandName);

		let args = content.split(command ? command.argOpts.separator : ' ').slice(1)
			.map(a => !isNaN(a) && command && !command.argOpts.stringArgs ? parseFloat(a) : a)
			.map(a => typeof a === 'string' ? a.trim() : a);

		return { command: command, mentions: mentions, args: args, content: content, dm: dm };
	}

	/**
	 * Get a list of missing permissions for the command caller for the
	 * given command, if any
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {boolean} dm - Whether the message is a DM
	 * @param {external:Message} message - Discord.js message object
	 * @param {Command} command - Command found by the dispatcher
	 * @returns {external:PermissionResolvable[]}
	 */
	checkPermissions(dm, message, command)
	{
		return dm ? [] : command.permissions.filter(a =>
			!message.channel.permissionsFor(message.author).hasPermission(a));
	}

	/**
	 * Checks if the command caller has roles for the given command
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {boolean} dm - Whether the message is a DM
	 * @param {external:Message} message - Discord.js message object
	 * @param {Command} command - Command found by the dispatcher
	 * @returns {boolean}
	 */
	hasRoles(dm, message, command)
	{
		return command.roles.length === 0 || dm
			|| message.member.roles.filter(role =>
				command.roles.includes(role.name)).size > 0;
	}

	/**
	 * Send a 'command not found' error message to the channel
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {external:Message} message - Discord.js message object
	 * @returns {Promise<external:Message>}
	 */
	commandNotFoundError(message)
	{
		return message.channel.sendMessage(``
			+ `Sorry, I didn't recognize any command in your message.\n`
			+ `Try saying "help" to view a list of commands you can use in `
			+ `this DM, or try calling the\nhelp command in a server channel `
			+ `to see what commands you can use there!`);
	}

	/**
	 * Send a 'guild only' error message to the channel
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {external:Message} message - Discord.js message object
	 * @returns {Promise<external:Message>}
	 */
	guildOnlyError(message)
	{
		return message.channel.sendMessage(``
			+ `That command is for servers only. Try saying "help" to see a `
			+ `list of commands you can use in this DM`);
	}

	/**
	 * Send a 'missing permissions' error message to the channel
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {external:PermissionResolvable[]} missing - Array of missing permissions
	 * @param {external:Message} message - Discord.js message object
	 * @returns {Promise<external:Message>}
	 */
	missingPermissionsError(missing, message)
	{
		return message[`${this._bot.selfbot ? 'channel' : 'author'}`].sendMessage(``
			+ `**You're missing the following permission`
			+ `${missing.length > 1 ? 's' : ''} `
			+ `for that command:**\n\`\`\`css\n`
			+ `${missing.join(', ')}\n\`\`\``)
				.then(response =>
				{
					if (this._bot.selfbot) response.delete(10 * 1000);
				});
	}

	/**
	 * Send a 'missing roles' error message to the channel
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {external:Message} message - Discord.js message object
	 * @param {Command} command - Command found by the dispatcher
	 * @returns {Promise<external:Message>}
	 */
	missingRolesError(message, command)
	{
		return message[`${this._bot.selfbot ? 'channel' : 'author'}`].sendMessage(``
			+ `**You must have ${command.roles.length > 1
				? 'one of the following roles' : 'the following role'}`
			+ ` to use that command:**\n\`\`\`css\n`
			+ `${command.roles.join(', ')}\n\`\`\``)
				.then(response =>
				{
					if (this._bot.selfbot) response.delete(10 * 1000);
				});
	}

	/**
	 * Pass the necessary items to the found Command's {@link Command#action} method
	 * @memberof CommandDispatcher
	 * @instance
	 * @param {Command} command - The command found by the dispatcher
	 * @param {external:Message} message - Discord.js message object
	 * @param {args[]} args - An array containing the args parsed from the command calling message
	 * @param {external:User[]} mentions - An array containing the Discord.js User
	 * objects parsed from the mentions contained in a message
	 * @param {string} original - The original raw content of the message that called the command
	 */
	async dispatch(command, message, args, mentions, original)
	{
		try
		{
			command.action(message, args, mentions, original);

			/**
			 * Emitted whenever a command is successfully called
			 * @memberof Bot
			 * @instance
			 * @event event:command
			 * @param {string} name - name of the called command
			 * @param {args[]} args - args passed to the called command
			 * @param {string} original - original content of the message that called the command
			 */
			this._bot.emit('command', command.name, args, original);
		}
		catch (err)
		{
			console.log(err); // eslint-disable-line no-console
		}
	}
}
<|endoftext|>


<commit_before>cc.Sprite._create = cc.Sprite.create;
/**
 * Create a sprite with image path or frame name or texture or spriteFrame.
 * @constructs
 * @param {String|cc.Texture2D|cc.SpriteFrame} fileName  The string which indicates a path to image file, e.g., "scene1/monster.png".
 * @param {cc.Rect} rect  Only the contents inside rect of pszFileName's texture will be applied for this sprite.
 * @return {cc.Sprite} A valid sprite object
 * @example
 *
 * 1.Create a sprite with image path and rect
 * var sprite1 = cc.Sprite.create("res/HelloHTML5World.png");
 * var sprite2 = cc.Sprite.create("res/HelloHTML5World.png",cc.rect(0,0,480,320));
 *
 * 2.Create a sprite with a sprite frame name. Must add "#" before frame name.
 * var sprite = cc.Sprite.create('#grossini_dance_01.png');
 *
 * 3.Create a sprite with a sprite frame
 * var spriteFrame = cc.spriteFrameCache.getSpriteFrame("grossini_dance_01.png");
 * var sprite = cc.Sprite.create(spriteFrame);
 *
 * 4.Create a sprite with an exsiting texture contained in a CCTexture2D object
 *      After creation, the rect will be the size of the texture, and the offset will be (0,0).
 * var texture = cc.textureCache.addImage("HelloHTML5World.png");
 * var sprite1 = cc.Sprite.create(texture);
 * var sprite2 = cc.Sprite.create(texture, cc.rect(0,0,480,320));
 *
 */
cc.Sprite.create = function (fileName, rect) {
    var sprite;

    if (arguments.length == 0) {
        sprite = cc.Sprite._create();
        return sprite;
    }

    if (typeof(fileName) === "string") {
        if (fileName[0] === "#") {
            //init with a sprite frame name
            var frameName = fileName.substr(1, fileName.length - 1);
            var spriteFrame = cc.spriteFrameCache.getSpriteFrame(frameName);
            sprite = cc.Sprite.createWithSpriteFrame(spriteFrame);
        } else {
            // Create with filename and rect
            sprite = rect ? cc.Sprite._create(fileName, rect) : cc.Sprite._create(fileName);
        }
        if (sprite)
            return sprite;
        else return null;
    }

    if (typeof(fileName) === "object") {
        if (fileName instanceof cc.Texture2D) {
            //init  with texture and rect
            sprite = rect ? cc.Sprite.createWithTexture(fileName, rect) : cc.Sprite.createWithTexture(fileName);
        } else if (fileName instanceof cc.SpriteFrame) {
            //init with a sprite frame
            sprite = cc.Sprite.createWithSpriteFrame(fileName);
        }
        if (sprite)
            return  sprite;
        else return null;
    }

    return null;
};

cc.PhysicsSprite._create = cc.PhysicsSprite.create;
cc.PhysicsSprite.create = function (fileName, rect) {
    var sprite;

    if (arguments.length == 0) {
        sprite = cc.PhysicsSprite._create();
        return sprite;
    }

    if (typeof(fileName) === "string") {
        if (fileName[0] === "#") {
            //init with a sprite frame name
            var frameName = fileName.substr(1, fileName.length - 1);
            var spriteFrame = cc.spriteFrameCache.getSpriteFrame(frameName);
            sprite = cc.PhysicsSprite.createWithSpriteFrame(spriteFrame);
        } else {
            // Create with filename and rect
            sprite = rect ? cc.PhysicsSprite._create(fileName, rect) : cc.PhysicsSprite._create(fileName);
        }
        if (sprite)
            return sprite;
        else return null;
    }

    if (typeof(fileName) === "object") {
        if (fileName instanceof cc.Texture2D) {
            //init  with texture and rect
            sprite = rect ? cc.PhysicsSprite.createWithTexture(fileName, rect) : cc.PhysicsSprite.createWithTexture(fileName);
        } else if (fileName instanceof cc.SpriteFrame) {
            //init with a sprite frame
            sprite = cc.PhysicsSprite.createWithSpriteFrame(fileName)
        }
        if (sprite)
            return  sprite;
        else return null;
    }

    return null;
};

cc.LabelTTF._create = cc.LabelTTF.create;
/**
 * creates a cc.LabelTTF from a font name, alignment, dimension and font size
 * @param {String} text
 * @param {String|cc.FontDefinition} fontName
 * @param {Number} fontSize
 * @param {cc.Size} [dimensions=cc.size(0,0)]
 * @param {Number} [hAlignment=]
 * @param {Number} [vAlignment=cc.VERTICAL_TEXT_ALIGNMENT_TOP]
 * @return {cc.LabelTTF|Null}
 * @example
 * // Example
 * 1.
 * var myLabel = cc.LabelTTF.create('label text',  'Times New Roman', 32, cc.size(320,32), cc.TEXT_ALIGNMENT_LEFT);
 * 2.
 * var fontDef = new cc.FontDefinition();
 * fontDef.fontName = "Arial";
 * fontDef.fontSize = "32";
 * var myLabel = cc.LabelTTF.create('label text',  fontDef);
 */
cc.LabelTTF.create = function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) {
    var label;
    if (fontName && fontName instanceof cc.FontDefinition) {
        label = cc.LabelTTF.createWithFontDefinition(text, fontName);
    }
    else {
        fontName = fontName || "Arial";
        fontSize = fontSize || 16;
        dimensions = dimensions || cc.size(0, 0);
        hAlignment = hAlignment || cc.TEXT_ALIGNMENT_CENTER;
        vAlignment = vAlignment || cc.VERTICAL_TEXT_ALIGNMENT_TOP;
        label = cc.LabelTTF._create(text, fontName, fontSize, dimensions, hAlignment, vAlignment);
    }
    if (label)
        return label;
    else return null;
};

cc.SpriteBatchNode._create = cc.SpriteBatchNode.create;
/**
 *

 *    creates a cc.SpriteBatchNodeCanvas with a file image (.png, .jpg etc) with a default capacity of 29 children.

 *    The capacity will be increased in 33% in runtime if it run out of space.

 *    The file will be loaded using the TextureMgr.

 *

 * @param {String|cc.Texture2D} fileImage
 * @param {Number} capacity
 * @return {cc.SpriteBatchNode}
 * @example
 * 1.
 * //create a SpriteBatchNode with image path
 * var spriteBatchNode = cc.SpriteBatchNode.create("res/animations/grossini.png", 50);
 * 2.
 * //create a SpriteBatchNode with texture
 * var texture = cc.textureCache.addImage("res/animations/grossini.png");
 * var spriteBatchNode = cc.SpriteBatchNode.create(texture,50);
 */
cc.SpriteBatchNode.create = function(fileName,capacity){
    if (typeof(fileName) == "string")
        return cc.SpriteBatchNode._create(fileName);
    else if (fileName instanceof cc.Texture2D)
        return cc.SpriteBatchNode.createWithTexture(fileName,capacity);
    return null;
};

cc.SpriteFrame._create = cc.SpriteFrame.create;
/**
 *

 *    Create a cc.SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels.

 *    The originalSize is the size in pixels of the frame before being trimmed.
 *

 * @param {String|cc.Texture2D} filename
 * @param {cc.Rect} rect if parameters' length equal 2, rect in points, else rect in pixels
 * @param {Boolean} rotated
 * @param {cc.Point} offset
 * @param {cc.Size} originalSize
 * @return {cc.SpriteFrame}
 * @example
 * 1.
 * //Create a cc.SpriteFrame with image path
 * var frame1 = cc.SpriteFrame.create("res/grossini_dance.png",cc.rect(0,0,90,128));
 * var frame2 = cc.SpriteFrame.create("res/grossini_dance.png",cc.rect(0,0,90,128),false,0,cc.size(90,128));
 *
 * 2.
 * //Create a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
 * var texture = cc.textureCache.addImage("res/grossini_dance.png");
 * var frame1 = cc.SpriteFrame.create(texture, cc.rect(0,0,90,128));
 * var frame2 = cc.SpriteFrame.create(texture, cc.rect(0,0,90,128),false,0,cc.size(90,128));
 */
cc.SpriteFrame.create = function(fileName, rect, rotated, offset, originalSize){
    var spriteFrame = null;
    switch (arguments.length) {
        case 2:
            spriteFrame = cc.SpriteFrame._create(fileName, rect);
            break;
        case 5:
            spriteFrame = cc.SpriteFrame._create(fileName, rect, rotated, offset, originalSize);
            break;
        default:
            throw "Argument must be non-nil ";
            break;
    }
    return spriteFrame;
};

cc.ParticleSystem._create = cc.ParticleSystem.create;
/**
 *
 return the string found by key in dict.

 *    This plist files can be create manually or with Particle Designer:

 *    http://particledesigner.71squared.com/

 *

 * @param {String|Number} plistFile
 * @return {cc.ParticleSystem}
 */
cc.ParticleSystem.create = function(plistFile){
    var particleSystem =null;
    if (typeof(plistFile) === "number") {
        particleSystem = cc.ParticleSystem.createWithTotalParticles(plistFile);
    }else if(typeof(plistFile) === "string"){
        particleSystem = cc.ParticleSystem._create(plistFile);
    }
    return particleSystem;
};
<commit_msg>Refactor #4237: fix create function for cc.SpriteBatchNode<commit_after>cc.Sprite._create = cc.Sprite.create;
/**
 * Create a sprite with image path or frame name or texture or spriteFrame.
 * @constructs
 * @param {String|cc.Texture2D|cc.SpriteFrame} fileName  The string which indicates a path to image file, e.g., "scene1/monster.png".
 * @param {cc.Rect} rect  Only the contents inside rect of pszFileName's texture will be applied for this sprite.
 * @return {cc.Sprite} A valid sprite object
 * @example
 *
 * 1.Create a sprite with image path and rect
 * var sprite1 = cc.Sprite.create("res/HelloHTML5World.png");
 * var sprite2 = cc.Sprite.create("res/HelloHTML5World.png",cc.rect(0,0,480,320));
 *
 * 2.Create a sprite with a sprite frame name. Must add "#" before frame name.
 * var sprite = cc.Sprite.create('#grossini_dance_01.png');
 *
 * 3.Create a sprite with a sprite frame
 * var spriteFrame = cc.spriteFrameCache.getSpriteFrame("grossini_dance_01.png");
 * var sprite = cc.Sprite.create(spriteFrame);
 *
 * 4.Create a sprite with an exsiting texture contained in a CCTexture2D object
 *      After creation, the rect will be the size of the texture, and the offset will be (0,0).
 * var texture = cc.textureCache.addImage("HelloHTML5World.png");
 * var sprite1 = cc.Sprite.create(texture);
 * var sprite2 = cc.Sprite.create(texture, cc.rect(0,0,480,320));
 *
 */
cc.Sprite.create = function (fileName, rect) {
    var sprite;

    if (arguments.length == 0) {
        sprite = cc.Sprite._create();
        return sprite;
    }

    if (typeof(fileName) === "string") {
        if (fileName[0] === "#") {
            //init with a sprite frame name
            var frameName = fileName.substr(1, fileName.length - 1);
            var spriteFrame = cc.spriteFrameCache.getSpriteFrame(frameName);
            sprite = cc.Sprite.createWithSpriteFrame(spriteFrame);
        } else {
            // Create with filename and rect
            sprite = rect ? cc.Sprite._create(fileName, rect) : cc.Sprite._create(fileName);
        }
        if (sprite)
            return sprite;
        else return null;
    }

    if (typeof(fileName) === "object") {
        if (fileName instanceof cc.Texture2D) {
            //init  with texture and rect
            sprite = rect ? cc.Sprite.createWithTexture(fileName, rect) : cc.Sprite.createWithTexture(fileName);
        } else if (fileName instanceof cc.SpriteFrame) {
            //init with a sprite frame
            sprite = cc.Sprite.createWithSpriteFrame(fileName);
        }
        if (sprite)
            return  sprite;
        else return null;
    }

    return null;
};

cc.PhysicsSprite._create = cc.PhysicsSprite.create;
cc.PhysicsSprite.create = function (fileName, rect) {
    var sprite;

    if (arguments.length == 0) {
        sprite = cc.PhysicsSprite._create();
        return sprite;
    }

    if (typeof(fileName) === "string") {
        if (fileName[0] === "#") {
            //init with a sprite frame name
            var frameName = fileName.substr(1, fileName.length - 1);
            var spriteFrame = cc.spriteFrameCache.getSpriteFrame(frameName);
            sprite = cc.PhysicsSprite.createWithSpriteFrame(spriteFrame);
        } else {
            // Create with filename and rect
            sprite = rect ? cc.PhysicsSprite._create(fileName, rect) : cc.PhysicsSprite._create(fileName);
        }
        if (sprite)
            return sprite;
        else return null;
    }

    if (typeof(fileName) === "object") {
        if (fileName instanceof cc.Texture2D) {
            //init  with texture and rect
            sprite = rect ? cc.PhysicsSprite.createWithTexture(fileName, rect) : cc.PhysicsSprite.createWithTexture(fileName);
        } else if (fileName instanceof cc.SpriteFrame) {
            //init with a sprite frame
            sprite = cc.PhysicsSprite.createWithSpriteFrame(fileName)
        }
        if (sprite)
            return  sprite;
        else return null;
    }

    return null;
};

cc.LabelTTF._create = cc.LabelTTF.create;
/**
 * creates a cc.LabelTTF from a font name, alignment, dimension and font size
 * @param {String} text
 * @param {String|cc.FontDefinition} fontName
 * @param {Number} fontSize
 * @param {cc.Size} [dimensions=cc.size(0,0)]
 * @param {Number} [hAlignment=]
 * @param {Number} [vAlignment=cc.VERTICAL_TEXT_ALIGNMENT_TOP]
 * @return {cc.LabelTTF|Null}
 * @example
 * // Example
 * 1.
 * var myLabel = cc.LabelTTF.create('label text',  'Times New Roman', 32, cc.size(320,32), cc.TEXT_ALIGNMENT_LEFT);
 * 2.
 * var fontDef = new cc.FontDefinition();
 * fontDef.fontName = "Arial";
 * fontDef.fontSize = "32";
 * var myLabel = cc.LabelTTF.create('label text',  fontDef);
 */
cc.LabelTTF.create = function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) {
    var label;
    if (fontName && fontName instanceof cc.FontDefinition) {
        label = cc.LabelTTF.createWithFontDefinition(text, fontName);
    }
    else {
        fontName = fontName || "Arial";
        fontSize = fontSize || 16;
        dimensions = dimensions || cc.size(0, 0);
        hAlignment = hAlignment || cc.TEXT_ALIGNMENT_CENTER;
        vAlignment = vAlignment || cc.VERTICAL_TEXT_ALIGNMENT_TOP;
        label = cc.LabelTTF._create(text, fontName, fontSize, dimensions, hAlignment, vAlignment);
    }
    if (label)
        return label;
    else return null;
};

cc.SpriteBatchNode._create = cc.SpriteBatchNode.create;
/**
 *

 *    creates a cc.SpriteBatchNodeCanvas with a file image (.png, .jpg etc) with a default capacity of 29 children.

 *    The capacity will be increased in 33% in runtime if it run out of space.

 *    The file will be loaded using the TextureMgr.

 *

 * @param {String|cc.Texture2D} fileImage
 * @param {Number} capacity
 * @return {cc.SpriteBatchNode}
 * @example
 * 1.
 * //create a SpriteBatchNode with image path
 * var spriteBatchNode = cc.SpriteBatchNode.create("res/animations/grossini.png", 50);
 * 2.
 * //create a SpriteBatchNode with texture
 * var texture = cc.textureCache.addImage("res/animations/grossini.png");
 * var spriteBatchNode = cc.SpriteBatchNode.create(texture,50);
 */
cc.SpriteBatchNode.create = function(fileName,capacity){
    if (typeof(fileName) == "string")
        return cc.SpriteBatchNode._create(fileName);
    else if (fileName instanceof cc.Texture2D) {
        return isNaN(capacity) ? cc.SpriteBatchNode.createWithTexture(fileName) :  cc.SpriteBatchNode.createWithTexture(fileName,capacity);
    }
    return null;
};

cc.SpriteFrame._create = cc.SpriteFrame.create;
/**
 *

 *    Create a cc.SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels.

 *    The originalSize is the size in pixels of the frame before being trimmed.
 *

 * @param {String|cc.Texture2D} filename
 * @param {cc.Rect} rect if parameters' length equal 2, rect in points, else rect in pixels
 * @param {Boolean} rotated
 * @param {cc.Point} offset
 * @param {cc.Size} originalSize
 * @return {cc.SpriteFrame}
 * @example
 * 1.
 * //Create a cc.SpriteFrame with image path
 * var frame1 = cc.SpriteFrame.create("res/grossini_dance.png",cc.rect(0,0,90,128));
 * var frame2 = cc.SpriteFrame.create("res/grossini_dance.png",cc.rect(0,0,90,128),false,0,cc.size(90,128));
 *
 * 2.
 * //Create a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
 * var texture = cc.textureCache.addImage("res/grossini_dance.png");
 * var frame1 = cc.SpriteFrame.create(texture, cc.rect(0,0,90,128));
 * var frame2 = cc.SpriteFrame.create(texture, cc.rect(0,0,90,128),false,0,cc.size(90,128));
 */
cc.SpriteFrame.create = function(fileName, rect, rotated, offset, originalSize){
    var spriteFrame = null;
    switch (arguments.length) {
        case 2:
            spriteFrame = cc.SpriteFrame._create(fileName, rect);
            break;
        case 5:
            spriteFrame = cc.SpriteFrame._create(fileName, rect, rotated, offset, originalSize);
            break;
        default:
            throw "Argument must be non-nil ";
            break;
    }
    return spriteFrame;
};

cc.ParticleSystem._create = cc.ParticleSystem.create;
/**
 *
 return the string found by key in dict.

 *    This plist files can be create manually or with Particle Designer:

 *    http://particledesigner.71squared.com/

 *

 * @param {String|Number} plistFile
 * @return {cc.ParticleSystem}
 */
cc.ParticleSystem.create = function(plistFile){
    var particleSystem =null;
    if (typeof(plistFile) === "number") {
        particleSystem = cc.ParticleSystem.createWithTotalParticles(plistFile);
    }else if(typeof(plistFile) === "string"){
        particleSystem = cc.ParticleSystem._create(plistFile);
    }
    return particleSystem;
};
<|endoftext|>


<commit_before>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.tabIndex = 1;
canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = "../image/png/spaceCat.png";

// Kitty Image
var kittyReady = false;
var kittyImage = new Image();
kittyImage.onload = function () {
  kittyReady = true;
};
kittyImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var kitty = {
  x: 0,
  y: 0
};
var kittyCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
  e.preventDefault();
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = (canvas.width / 2) - 16;
  hero.y = (canvas.height / 2) - 16;

  kitty.x = 32 + (Math.random() * (canvas.width - 64));
  kitty.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Stop from going off the page
  if (hero.x >= canvas.width - 32) {
    hero.x = canvas.width - 32;
  } else if (hero.x <= 0) {
    hero.x = 0;
  }

  if (hero.y >= canvas.height - 32) {
    hero.y = canvas.height - 32;
  } else if (hero.y <= 0) {
    hero.y = 0;
  }

  // Collision
  if (hero.x <= (kitty.x + 32) && kitty.x <= (hero.x + 32) && hero.y <= (kitty.y + 32) && kitty.y <= (hero.y + 32)) {
    ++kittyCaught;
    thenSwitch = nowSwitch;
    reset();
  }

  ctx.save;
  ctx.scale(-1, 1);
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (kittyReady) {
    ctx.drawImage(kittyImage, kitty.x, kitty.y);
  }

  ctx.fillStyle = "#EEE";
  ctx.font = "24px Ubuntu";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Kitties caught : " + kittyCaught, 32, 32);
  ctx.fillText("Lives : " + lives, 365, 32);
  ctx.fillText("Timer : " + parseInt(countDown / 100), 32, 64);
};

var gameOver = function () {
  document.write("Game Over. Kitties only have nine lives. You caught " + kittyCaught + " kitties.");
};

var main = function () {
  now = Date.now();
  var delta = now - then;

  nowSwitch = Date.now();

  update(delta / 1100);

  countDown = nowSwitch - thenSwitch;

  if (countDown >= 1000) {
    lives--;
    if (lives ==  0) {
      gameOver();
    }
    thenSwitch = nowSwitch;
    reset();
  }

  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Initalized Variables
var then, thenSwitch, nowSwitch;
var countDown;
var lives;

var start = function() {
  then = thenSwitch = nowSwitch = Date.now();
  reset();
  countDown = 0;
  lives = 9;
  kittyCaught = 0;
  //hero.x = (canvas.width / 2) - 16;
  //hero.y = (canvas.height / 2) - 16;
  main();
}

start();
<commit_msg>Update canvas.js<commit_after>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.tabIndex = 1;
canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = "../image/png/spaceCat.png";

// Kitty Image
var kittyReady = false;
var kittyImage = new Image();
kittyImage.onload = function () {
  kittyReady = true;
};
kittyImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var kitty = {
  x: 0,
  y: 0
};
var kittyCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
  e.preventDefault();
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = (canvas.width / 2) - 16;
  hero.y = (canvas.height / 2) - 16;

  kitty.x = 32 + (Math.random() * (canvas.width - 64));
  kitty.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Stop from going off the page
  if (hero.x >= canvas.width - 32) {
    hero.x = canvas.width - 32;
  } else if (hero.x <= 0) {
    hero.x = 0;
  }

  if (hero.y >= canvas.height - 32) {
    hero.y = canvas.height - 32;
  } else if (hero.y <= 0) {
    hero.y = 0;
  }

  // Collision
  if (hero.x <= (kitty.x + 32) && kitty.x <= (hero.x + 32) && hero.y <= (kitty.y + 32) && kitty.y <= (hero.y + 32)) {
    ++kittyCaught;
    thenSwitch = nowSwitch;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (kittyReady) {
    ctx.drawImage(kittyImage, kitty.x, kitty.y);
  }

  ctx.fillStyle = "#EEE";
  ctx.font = "24px Ubuntu";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Kitties caught : " + kittyCaught, 32, 32);
  ctx.fillText("Lives : " + lives, 365, 32);
  ctx.fillText("Timer : " + parseInt(countDown / 100), 32, 64);
};

var gameOver = function () {
  document.write("Game Over. Kitties only have nine lives. You caught " + kittyCaught + " kitties.");
};

var main = function () {
  now = Date.now();
  var delta = now - then;

  nowSwitch = Date.now();

  update(delta / 1100);

  countDown = nowSwitch - thenSwitch;

  if (countDown >= 1000) {
    lives--;
    if (lives ==  0) {
      gameOver();
    }
    thenSwitch = nowSwitch;
    reset();
  }

  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Initalized Variables
var then, thenSwitch, nowSwitch;
var countDown;
var lives;

var start = function() {
  then = thenSwitch = nowSwitch = Date.now();
  reset();
  countDown = 0;
  lives = 9;
  kittyCaught = 0;
  //hero.x = (canvas.width / 2) - 16;
  //hero.y = (canvas.height / 2) - 16;
  main();
}

start();
<|endoftext|>


<commit_before>var fs = require("fs"),
    path = require("path");

module.exports = function(bot, db) {
    //cache all the commands here by auto requiring them and passing the bot
    //supports directories no matter how deep you go. twss
    var commands = {},
        cmd = process.cwd() + "/bot/commands";
    var walk = function(dir) {
        fs.readdirSync(dir).forEach(function(file) {
            var _path = path.resolve(dir, file);
            fs.stat(_path, function(err, stat) {
                if (stat && stat.isDirectory()) {
                    walk(_path);
                } else {
                    if (file.indexOf(".js") > -1) {
                        // add commands set in file if they exist
                        if(typeof(require(_path).extraCommands) !== "undefined"){
                            if(Array.isArray(require(_path).extraCommands)){
                                // add each command in array into overall commands
                                require(_path).extraCommands.forEach(function(command){
                                    commands[command] = require(_path);
                                });
                            }
                            else {
                                throw new TypeError("Invalid extraCommands export for file: " + _path);
                            }
                        }

                        commands[file.split(".")[0]] = require(_path);
                    }

                }
            });
        });
    };
    walk(cmd);
    bot.on("chat-message", function(data) {
        var cmd = data.message,
            //split the whole message words into tokens
            tokens = cmd.split(" "),
            // array of the command triggers
            parsedCommands = [];
        //command handler
        tokens.forEach(function(token) {
            if (token.substr(0, 1) === "!" && parsedCommands.indexOf(token.substr(1)) == -1) {
                // add the command used to the data sent from the chat to be used later
                data.trigger = token.substr(1).toLowerCase();
                parsedCommands.push(data.trigger);
                //if very first token, it's a command and we can grab the
                //params (if any) and add to the data sent from chat
                if (tokens.indexOf(token) === 0) {
                    //the params are an array of the remaining tokens
                    data.params = tokens.slice(1);
                    //execute the command
                    if (typeof(commands[data.trigger]) !== "undefined") {
                        //passes the bot, db, and the data to the command
                        commands[data.trigger](bot, db, data);
                    }
                }
            }
        });
    });
};
<commit_msg>Code Update - Improved Performance<commit_after>var fs = require("fs"),
    path = require("path");

module.exports = function(bot, db) {
    //cache all the commands here by auto requiring them and passing the bot
    //supports directories no matter how deep you go. twss
    var commands = {},
        cmd = process.cwd() + "/bot/commands";
    var walk = function(dir) {
        fs.readdirSync(dir).forEach(function(file) {
            var _path = path.resolve(dir, file);
            fs.stat(_path, function(err, stat) {
                if (stat && stat.isDirectory()) {
                    walk(_path);
                } else {
                    if (file.indexOf(".js") > -1) {
                        // add commands set in file if they exist
                        if(typeof(require(_path).extraCommands) !== "undefined"){
                            if(Array.isArray(require(_path).extraCommands)){
                                // add each command in array into overall commands
                                require(_path).extraCommands.forEach(function(command){
                                    commands[command] = require(_path);
                                });
                            }
                            else {
                                throw new TypeError("Invalid extraCommands export for file: " + _path);
                            }
                        }

                        commands[file.split(".")[0]] = require(_path);
                    }

                }
            });
        });
    };
    walk(cmd);
    bot.on("chat-message", function(data) {
        var cmd = data.message,
            //split the whole message words into tokens
            tokens = cmd.split(" "),
            // array of the command triggers
            parsedCommands = [];
        //command handler
        tokens.forEach(function(token) {
            if (token.charAt(0) === "!" && parsedCommands.indexOf(token.substr(1)) == -1) {
                // add the command used to the data sent from the chat to be used later
                data.trigger = token.substr(1).toLowerCase();
                parsedCommands.push(data.trigger);
                //if very first token, it's a command and we can grab the
                //params (if any) and add to the data sent from chat
                if (tokens.indexOf(token) === 0) {
                    //the params are an array of the remaining tokens
                    data.params = tokens.slice(1);
                    //execute the command
                    if (typeof(commands[data.trigger]) !== "undefined") {
                        //passes the bot, db, and the data to the command
                        commands[data.trigger](bot, db, data);
                    }
                }
            }
        });
    });
};
<|endoftext|>


<commit_before>/*
  Solving Sol #56 (1970)

  A square is divided horizontally and vertically into four equal parts, each with lines in four directions superimposed progressively.
 */

function onResize(event) {
  draw();
}

// https://coolors.co/f0f3bd-02c39a-00a896-028090-05668d
var PALETTE1 = [
  "#F0F3BD",
  "#02C39A",
  "#00A896",
  "#028090",
  "#05668D"
].reverse();
var PALETTE2 = ["#9c89b8", "#f0a6ca", "#efc3e6", "#f0e6ef", "#b8bedd"];
// https://coolors.co/b80c09-0b4f6c-01baef-fbfbff-040f16
var PALETTE3 = "ffffea-d8d8d8-ffed66-ff5e5b-00cecb".split("-").map(function(c) {
  return "#" + c;
});
var COLORS = PALETTE3;

var canvasBg = COLORS[0];
var squareBg = canvasBg;
var lineColor = "#05668D";

function direction(angle) {
  return new Point(Math.cos(angle), Math.sin(angle));
}

function draw() {
  project.clear();

  // background
  new Path.Rectangle(view.bounds).fillColor = canvasBg;

  var phi = (1 + Math.sqrt(5)) / 2;
  var height = Math.min(view.size.width, view.size.height) / phi / 2;

  var directionSW = direction(Math.PI / 12);
  var directionNW = direction((2 * Math.PI) / 12);
  var directionNE = direction((3 * Math.PI) / 12);
  var directionSE = direction((4 * Math.PI) / 12);

  var topLeft = view.center - height;
  var pointSW = topLeft + new Point(0, height);
  var pointNW = topLeft + new Point(0, 0);
  var pointNE = topLeft + new Point(height, 0);
  var pointSE = topLeft + new Point(height, height);

  // Entire square
  var wholeSquare = new Path.Rectangle(new Rectangle(topLeft, height * 2));
  wholeSquare.fillColor = squareBg;

  // South west
  fillSquareWithLines(pointSW, height, directionSW, COLORS[1]);

  // North west
  fillSquareWithLines(pointNW, height, directionSW, COLORS[1]);
  fillSquareWithLines(pointNW, height, directionNW, COLORS[2]);

  // North east
  fillSquareWithLines(pointNE, height, directionSW, COLORS[1]);
  fillSquareWithLines(pointNE, height, directionNW, COLORS[2]);
  fillSquareWithLines(pointNE, height, directionNE, COLORS[3]);

  // South east
  fillSquareWithLines(pointSE, height, directionSW, COLORS[1]);
  fillSquareWithLines(pointSE, height, directionNW, COLORS[2]);
  fillSquareWithLines(pointSE, height, directionNE, COLORS[3]);
  fillSquareWithLines(pointSE, height, directionSE, COLORS[4]);
}

function band(start, end, width) {
  var direction = end - start;
  var orthogonal = new Point(direction.y, -direction.x).normalize();
  var bandPath = new Path();
  bandPath.add(start + (orthogonal * width) / 2);
  bandPath.add(end + (orthogonal * width) / 2);
  bandPath.add(end - (orthogonal * width) / 2);
  bandPath.add(start - (orthogonal * width) / 2);
  bandPath.closed = true;

  return bandPath;
}

function fillSquareWithLines(
  corner, // Point
  height, // Number
  direction, // Vector (Point),
  color
) {
  // The ratio between line width and line spacing
  var ratio = 1 / 3;
  var lineCount = 12;
  var strokeWidth = (ratio * height) / lineCount;
  var spacing = ((1 - ratio) * height) / lineCount; //px

  var size = new Size(height, height);
  var square = new Rectangle(corner, size);

  var diagonalSize = Math.sqrt(2) * height * 2;
  var orthogonal = new Point(direction.y, -direction.x).normalize();
  var center = corner + height / 2;

  var squarePath = new Path.Rectangle(square);
  squarePath.strokeWidth = strokeWidth;
  squarePath.strokeColor = color;

  var i = 0;

  function drawBand(offset) {
    var lineCenter = center + orthogonal * offset;
    var lineStart = lineCenter - direction.normalize(diagonalSize / 2);
    var lineEnd = lineCenter + direction.normalize(diagonalSize / 2);

    var bandPath = band(lineStart, lineEnd, strokeWidth);
    var segmentPath = bandPath.intersect(squarePath);
    segmentPath.fillColor = color;
  }

  do {
    var offset = i * (spacing + strokeWidth);
    drawBand(offset);
    drawBand(-offset);
    i++;
  } while (offset <= diagonalSize / 2);
}
<commit_msg>Some other colors<commit_after>/*
  Solving Sol #56 (1970)

  A square is divided horizontally and vertically into four equal parts, each with lines in four directions superimposed progressively.
 */

function onResize(event) {
  draw();
}

// https://coolors.co/f0f3bd-02c39a-00a896-028090-05668d
var PALETTE1 = [
  "#F0F3BD",
  "#02C39A",
  "#00A896",
  "#028090",
  "#05668D"
].reverse();
var PALETTE2 = ["#9c89b8", "#f0a6ca", "#efc3e6", "#f0e6ef", "#b8bedd"];
// https://coolors.co/b80c09-0b4f6c-01baef-fbfbff-040f16
var PALETTE3 = "fff39d-264653-2a9d8f-f4a261-ff5e5b".split("-").map(function(c) {
  return "#" + c;
});
var COLORS = PALETTE3;

var canvasBg = COLORS[0];
var squareBg = canvasBg;
var lineColor = "#05668D";

function direction(angle) {
  return new Point(Math.cos(angle), Math.sin(angle));
}

function draw() {
  project.clear();

  // background
  new Path.Rectangle(view.bounds).fillColor = canvasBg;

  var phi = (1 + Math.sqrt(5)) / 2;
  var height = Math.min(view.size.width, view.size.height) / phi / 2;

  var directionSW = direction(Math.PI / 12);
  var directionNW = direction((2 * Math.PI) / 12);
  var directionNE = direction((3 * Math.PI) / 12);
  var directionSE = direction((4 * Math.PI) / 12);

  var topLeft = view.center - height;
  var pointSW = topLeft + new Point(0, height);
  var pointNW = topLeft + new Point(0, 0);
  var pointNE = topLeft + new Point(height, 0);
  var pointSE = topLeft + new Point(height, height);

  // Entire square
  var wholeSquare = new Path.Rectangle(new Rectangle(topLeft, height * 2));
  wholeSquare.fillColor = squareBg;

  // South west
  fillSquareWithLines(pointSW, height, directionSW, COLORS[1]);

  // North west
  fillSquareWithLines(pointNW, height, directionSW, COLORS[1]);
  fillSquareWithLines(pointNW, height, directionNW, COLORS[2]);

  // North east
  fillSquareWithLines(pointNE, height, directionSW, COLORS[1]);
  fillSquareWithLines(pointNE, height, directionNW, COLORS[2]);
  fillSquareWithLines(pointNE, height, directionNE, COLORS[3]);

  // South east
  fillSquareWithLines(pointSE, height, directionSW, COLORS[1]);
  fillSquareWithLines(pointSE, height, directionNW, COLORS[2]);
  fillSquareWithLines(pointSE, height, directionNE, COLORS[3]);
  fillSquareWithLines(pointSE, height, directionSE, COLORS[4]);
}

function band(start, end, width) {
  var direction = end - start;
  var orthogonal = new Point(direction.y, -direction.x).normalize();
  var bandPath = new Path();
  bandPath.add(start + (orthogonal * width) / 2);
  bandPath.add(end + (orthogonal * width) / 2);
  bandPath.add(end - (orthogonal * width) / 2);
  bandPath.add(start - (orthogonal * width) / 2);
  bandPath.closed = true;

  return bandPath;
}

function fillSquareWithLines(
  corner, // Point
  height, // Number
  direction, // Vector (Point),
  color
) {
  // The ratio between line width and line spacing
  var ratio = 1 / 3;
  var lineCount = 12;
  var strokeWidth = (ratio * height) / lineCount;
  var spacing = ((1 - ratio) * height) / lineCount; //px

  var size = new Size(height, height);
  var square = new Rectangle(corner, size);

  var diagonalSize = Math.sqrt(2) * height * 2;
  var orthogonal = new Point(direction.y, -direction.x).normalize();
  var center = corner + height / 2;

  var squarePath = new Path.Rectangle(square);
  squarePath.strokeWidth = strokeWidth;
  squarePath.strokeColor = color;

  var i = 0;

  function drawBand(offset) {
    var lineCenter = center + orthogonal * offset;
    var lineStart = lineCenter - direction.normalize(diagonalSize / 2);
    var lineEnd = lineCenter + direction.normalize(diagonalSize / 2);

    var bandPath = band(lineStart, lineEnd, strokeWidth);
    var segmentPath = bandPath.intersect(squarePath);
    segmentPath.fillColor = color;
  }

  do {
    var offset = i * (spacing + strokeWidth);
    drawBand(offset);
    drawBand(-offset);
    i++;
  } while (offset <= diagonalSize / 2);
}
<|endoftext|>