<commit_before>/* global before beforeEach window document describe it */
import sinon from 'sinon';
import { expect } from 'chai';
import {
  showDropDown,
  hideAllDropDowns,
  bindUIEvents,
  SecondaryNavigation,
} from '../components/secondary-navigation';

describe('secondary nav tests', () => {
  let nav;
  let navItem1;
  let navItem2;
  let navItem3;
  let subNav1;
  let subNavContainer1;
  let subNav2;
  let subNavContainer2;
  let event;

  beforeEach(() => {
    nav = document.createElement('ul');
    nav.setAttribute('data-sprk-navigation', 'secondary');

    navItem1 = document.createElement('li');
    navItem2 = document.createElement('li');
    navItem3 = document.createElement('li');

    sinon.spy(navItem1, 'addEventListener');
    sinon.spy(navItem2, 'addEventListener');
    sinon.spy(navItem3, 'addEventListener');

    subNavContainer1 = document.createElement('div');
    subNavContainer1.classList.add('sprk-c-SecondaryNavigation__sub-menu-container');
    subNavContainer1.classList.add('sprk-u-Display--none');

    subNavContainer2 = document.createElement('div');
    subNavContainer2.classList.add('sprk-c-SecondaryNavigation__sub-menu-container');
    subNavContainer2.classList.add('sprk-u-Display--none');

    subNav1 = document.createElement('ul');
    subNav1.classList.add('sprk-c-SecondaryNavigation--sub');

    subNav2 = document.createElement('ul');
    subNav2.classList.add('sprk-c-SecondaryNavigation--sub', 'sprk-u-Display--none');

    subNavContainer1.appendChild(subNav1);
    subNavContainer2.appendChild(subNav2);

    navItem1.appendChild(subNavContainer1);
    navItem3.appendChild(subNavContainer2);

    nav.appendChild(navItem1);
    nav.appendChild(navItem2);
    nav.appendChild(navItem3);

    document.body.appendChild(nav);
  });

  it('should remove the hidden class from the subNav inside', () => {
    showDropDown(navItem1);
    expect(subNav1.classList.contains('sprk-u-Display--none')).eql(false);
  });

  it('should do nothing if theres no subnav', () => {
    showDropDown(navItem2);
    expect(subNavContainer1.classList.contains('sprk-u-Display--none')).eql(true);
    expect(subNavContainer2.classList.contains('sprk-u-Display--none')).eql(true);
  });

  it('should bind the focusin event', () => {
    bindUIEvents(navItem1);
    expect(navItem1.addEventListener.getCall(0).args[0]).eql('focusin');
  });

  it('should hide all navs and show one on focusin', () => {
    bindUIEvents(navItem1);
    bindUIEvents(navItem2);
    bindUIEvents(navItem3);

    event = new window.Event('focusin');
    navItem3.dispatchEvent(event);

    expect(subNavContainer1.classList.contains('sprk-u-Display--none')).eql(true);
    expect(subNavContainer2.classList.contains('sprk-u-Display--none')).eql(false);
  });

  it('should do nothing if theres no sub nav on focusin', () => {
    bindUIEvents(navItem2);

    event = new window.Event('focusin');
    navItem2.dispatchEvent(event);
    expect(navItem2.classList.contains('sprk-c-SecondaryNavigation__item--open')).eql(false);
  });

  it('should bind the mouseenter event', () => {
    bindUIEvents(navItem1);
    expect(navItem1.addEventListener.getCall(1).args[0]).eql('mouseenter');
  });

  it('should do nothing if theres no sub nav on mouseenter', () => {
    bindUIEvents(navItem2);

    event = new window.Event('mouseenter');
    navItem2.dispatchEvent(event);
    expect(navItem2.classList.contains('sprk-c-SecondaryNavigation__item--open')).eql(false);
  });

  it('should hide all navs and show one on mouseenter', () => {
    bindUIEvents(navItem1);
    bindUIEvents(navItem2);
    bindUIEvents(navItem3);

    event = new window.Event('mouseenter');
    navItem3.dispatchEvent(event);

    expect(subNavContainer1.classList.contains('sprk-u-Display--none')).eql(true);
    expect(subNavContainer2.classList.contains('sprk-u-Display--none')).eql(false);
  });

  it('should bind the mouseleave event', () => {
    bindUIEvents(navItem1);
    expect(navItem1.addEventListener.getCall(2).args[0]).eql('mouseleave');
  });

  it('should do nothing if theres no sub nav on mouseleave', () => {
    bindUIEvents(navItem2);

    event = new window.Event('mouseleave');
    navItem2.dispatchEvent(event);
    expect(navItem2.classList.contains('sprk-c-SecondaryNavigation__item--open')).eql(false);
  });

  it('should hide all navs and show one on mouseleave', () => {
    bindUIEvents(navItem1);
    bindUIEvents(navItem2);
    bindUIEvents(navItem3);

    event = new window.Event('mouseleave');
    navItem3.dispatchEvent(event);

    expect(subNavContainer1.classList.contains('sprk-u-Display--none')).eql(true);
    expect(subNavContainer2.classList.contains('sprk-u-Display--none')).eql(true);
  });

  it('should call getElements once with the correct selector', () => {
    sinon.spy(document, 'querySelectorAll');
    SecondaryNavigation();
    expect(document.querySelectorAll.getCall(0).args[0]).eql('[data-sprk-navigation="secondary"] > .sprk-c-SecondaryNavigation__item');
  });
});

describe('hide all navigation tests', () => {
  let nav;
  let navItem1;
  let navItem2;
  let navItem3;
  let subNav1;
  let subNav2;

  before(() => {
    nav = document.createElement('ul');
    navItem1 = document.createElement('li');
    navItem1.setAttribute('aria-expanded', 'true');
    navItem2 = document.createElement('li');
    navItem2.setAttribute('aria-expanded', 'true');
    navItem3 = document.createElement('li');

    subNav1 = document.createElement('ul');
    subNav1.classList.add('sprk-c-SecondaryNavigation--sub');

    subNav2 = document.createElement('ul');
    subNav2.classList.add('sprk-c-SecondaryNavigation--sub');

    navItem1.appendChild(subNav1);
    navItem3.appendChild(subNav2);

    nav.appendChild(navItem1);
    nav.appendChild(navItem2);
    nav.appendChild(navItem3);

    hideAllDropDowns(
      nav.querySelectorAll('.sprk-c-SecondaryNavigation--sub'),
      nav.querySelectorAll('[aria-expanded]'),
    );
  });

  it('should add the hidden class to the sub navs and set aria-expanded', () => {
    expect(subNav1.classList.contains('sprk-u-Display--none')).eql(true);
    expect(subNav2.classList.contains('sprk-u-Display--none')).eql(true);
  });

  it('should set aria-expanded on nav items to false', () => {
    expect(navItem1.getAttribute('aria-expanded') === 'false').eql(true);
    expect(navItem2.getAttribute('aria-expanded') === 'false').eql(true);
  });
});
<commit_msg>update tests<commit_after>/* global before beforeEach window document describe it afterEach */
import sinon from 'sinon';
import { expect } from 'chai';
import {
  showDropDown,
  hideAllDropDowns,
  bindUIEvents,
  SecondaryNavigation,
} from '../components/secondary-navigation';

describe('secondary nav tests', () => {
  let nav;
  let navItem1;
  let navItem2;
  let navItem3;
  let subNav1;
  let subNavContainer1;
  let subNav2;
  let subNavContainer2;
  let event;

  beforeEach(() => {
    nav = document.createElement('ul');
    nav.setAttribute('data-sprk-navigation', 'secondary');

    navItem1 = document.createElement('li');
    navItem2 = document.createElement('li');
    navItem3 = document.createElement('li');

    sinon.spy(navItem1, 'addEventListener');
    sinon.spy(navItem2, 'addEventListener');
    sinon.spy(navItem3, 'addEventListener');
    sinon.spy(document, 'querySelectorAll');

    subNavContainer1 = document.createElement('div');
    subNavContainer1.classList.add('sprk-c-SecondaryNavigation__sub-menu-container');
    subNavContainer1.classList.add('sprk-u-Display--none');

    subNavContainer2 = document.createElement('div');
    subNavContainer2.classList.add('sprk-c-SecondaryNavigation__sub-menu-container');
    subNavContainer2.classList.add('sprk-u-Display--none');

    subNav1 = document.createElement('ul');
    subNav1.classList.add('sprk-c-SecondaryNavigation--sub');

    subNav2 = document.createElement('ul');
    subNav2.classList.add('sprk-c-SecondaryNavigation--sub', 'sprk-u-Display--none');

    subNavContainer1.appendChild(subNav1);
    subNavContainer2.appendChild(subNav2);

    navItem1.appendChild(subNavContainer1);
    navItem3.appendChild(subNavContainer2);

    nav.appendChild(navItem1);
    nav.appendChild(navItem2);
    nav.appendChild(navItem3);

    document.body.appendChild(nav);
  });

  afterEach(() => {
    document.querySelectorAll.restore();
  });

  it('should remove the hidden class from the subNav inside', () => {
    showDropDown(navItem1);
    expect(subNav1.classList.contains('sprk-u-Display--none')).eql(false);
  });

  it('should do nothing if theres no subnav', () => {
    showDropDown(navItem2);
    expect(subNavContainer1.classList.contains('sprk-u-Display--none')).eql(true);
    expect(subNavContainer2.classList.contains('sprk-u-Display--none')).eql(true);
  });

  it('should bind the focusin event', () => {
    bindUIEvents(navItem1);
    expect(navItem1.addEventListener.getCall(0).args[0]).eql('focusin');
  });

  it('should hide all navs and show one on focusin', () => {
    bindUIEvents(navItem1);
    bindUIEvents(navItem2);
    bindUIEvents(navItem3);

    event = new window.Event('focusin');
    navItem3.dispatchEvent(event);

    expect(subNavContainer1.classList.contains('sprk-u-Display--none')).eql(true);
    expect(subNavContainer2.classList.contains('sprk-u-Display--none')).eql(false);
  });

  it('should do nothing if theres no sub nav on focusin', () => {
    bindUIEvents(navItem2);

    event = new window.Event('focusin');
    navItem2.dispatchEvent(event);
    expect(navItem2.classList.contains('sprk-c-SecondaryNavigation__item--open')).eql(false);
  });

  it('should bind the mouseenter event', () => {
    bindUIEvents(navItem1);
    expect(navItem1.addEventListener.getCall(1).args[0]).eql('mouseenter');
  });

  it('should do nothing if theres no sub nav on mouseenter', () => {
    bindUIEvents(navItem2);

    event = new window.Event('mouseenter');
    navItem2.dispatchEvent(event);
    expect(navItem2.classList.contains('sprk-c-SecondaryNavigation__item--open')).eql(false);
  });

  it('should hide all navs and show one on mouseenter', () => {
    bindUIEvents(navItem1);
    bindUIEvents(navItem2);
    bindUIEvents(navItem3);

    event = new window.Event('mouseenter');
    navItem3.dispatchEvent(event);

    expect(subNavContainer1.classList.contains('sprk-u-Display--none')).eql(true);
    expect(subNavContainer2.classList.contains('sprk-u-Display--none')).eql(false);
  });

  it('should bind the mouseleave event', () => {
    bindUIEvents(navItem1);
    expect(navItem1.addEventListener.getCall(2).args[0]).eql('mouseleave');
  });

  it('should do nothing if theres no sub nav on mouseleave', () => {
    bindUIEvents(navItem2);

    event = new window.Event('mouseleave');
    navItem2.dispatchEvent(event);
    expect(navItem2.classList.contains('sprk-c-SecondaryNavigation__item--open')).eql(false);
  });

  it('should hide all navs and show one on mouseleave', () => {
    bindUIEvents(navItem1);
    bindUIEvents(navItem2);
    bindUIEvents(navItem3);

    event = new window.Event('mouseleave');
    navItem3.dispatchEvent(event);

    expect(subNavContainer1.classList.contains('sprk-u-Display--none')).eql(true);
    expect(subNavContainer2.classList.contains('sprk-u-Display--none')).eql(true);
  });

  it('should call getElements once with the correct selector', () => {
    SecondaryNavigation();
    expect(document.querySelectorAll.getCall(0).args[0]).eql('[data-sprk-navigation="secondary"] > .sprk-c-SecondaryNavigation__item');
  });
});

describe('hide all navigation tests', () => {
  let nav;
  let navItem1;
  let navItem2;
  let navItem3;
  let subNav1;
  let subNav2;

  before(() => {
    nav = document.createElement('ul');
    navItem1 = document.createElement('li');
    navItem1.setAttribute('aria-expanded', 'true');
    navItem2 = document.createElement('li');
    navItem2.setAttribute('aria-expanded', 'true');
    navItem3 = document.createElement('li');

    subNav1 = document.createElement('ul');
    subNav1.classList.add('sprk-c-SecondaryNavigation--sub');

    subNav2 = document.createElement('ul');
    subNav2.classList.add('sprk-c-SecondaryNavigation--sub');

    navItem1.appendChild(subNav1);
    navItem3.appendChild(subNav2);

    nav.appendChild(navItem1);
    nav.appendChild(navItem2);
    nav.appendChild(navItem3);

    hideAllDropDowns(
      nav.querySelectorAll('.sprk-c-SecondaryNavigation--sub'),
      nav.querySelectorAll('[aria-expanded]'),
    );
  });

  it('should add the hidden class to the sub navs and set aria-expanded', () => {
    expect(subNav1.classList.contains('sprk-u-Display--none')).eql(true);
    expect(subNav2.classList.contains('sprk-u-Display--none')).eql(true);
  });

  it('should set aria-expanded on nav items to false', () => {
    expect(navItem1.getAttribute('aria-expanded') === 'false').eql(true);
    expect(navItem2.getAttribute('aria-expanded') === 'false').eql(true);
  });
});
<|endoftext|>


<commit_before>var bcoin = require('../../bcoin');
var constants = require('./constants');
var utils = bcoin.utils;
var assert = utils.assert;

var writeU32 = utils.writeU32;
var writeAscii = utils.writeAscii;

function Framer() {
  if (!(this instanceof Framer))
    return new Framer();
}
module.exports = Framer;

Framer.prototype.header = function header(cmd, payload) {
  assert(cmd.length < 12);
  assert(payload.length <= 0xffffffff);

  var h = new Array(24);

  // Magic value
  writeU32(h, constants.magic, 0);

  // Command
  var len = writeAscii(h, cmd, 4);
  for (var i = 4 + len; i < 4 + 12; i++)
    h[i] = 0;

  // Payload length
  writeU32(h, payload.length, 16);

  // Checksum
  utils.copy(utils.checksum(payload), h, 20);

  return h;
};

Framer.prototype.packet = function packet(cmd, payload) {
  var h = this.header(cmd, payload);
  return h.concat(payload);
};

Framer.prototype._addr = function addr(buf, off) {
  writeU32(buf, 1, off);
  writeU32(buf, 0, off + 4);
  writeU32(buf, 0, off + 8);
  writeU32(buf, 0, off + 12);
  writeU32(buf, 0xffff0000, off + 16);
  writeU32(buf, 0, off + 20);
  buf[off + 24] = 0;
  buf[off + 25] = 0;
};

Framer.prototype.version = function version(packet) {
  var p = new Array(86);

  if (!packet)
    packet = {};

  // Version
  writeU32(p, constants.version, 0);

  // Services
  writeU32(p, constants.services.network, 4);
  writeU32(p, 0, 8);

  // Timestamp
  var ts = ((+new Date()) / 1000) | 0;
  writeU32(p, ts, 12);
  writeU32(p, 0, 16);

  // Remote and local addresses
  this._addr(p, 20);
  this._addr(p, 46);

  // Nonce, very dramatic
  writeU32(p, (Math.random() * 0xffffffff) | 0, 72);
  writeU32(p, (Math.random() * 0xffffffff) | 0, 76);

  // No user-agent
  p[80] = 0;

  // Start height
  writeU32(p, packet.height, 81);

  // Relay
  p[85] = packet.relay ? 1 : 0;

  return this.packet('version', p);
};

Framer.prototype.verack = function verack() {
  return this.packet('verack', []);
};

function varint(arr, value, off) {
  if (!off)
    off = 0;
  if (value < 0xfd) {
    arr[off] = value;
    return 1;
  } else if (value <= 0xffff) {
    arr[off] = 0xfd;
    arr[off + 1] = value & 0xff;
    arr[off + 2] = value >>> 8;
    return 3;
  } else if (value <= 0xffffffff) {
    arr[off] = 0xfd;
    arr[off + 3] = value & 0xff;
    arr[off + 4] = (value >>> 8) & 0xff;
    arr[off + 5] = (value >>> 16) & 0xff;
    arr[off + 6] = value >>> 24;
    return 5;
  } else {
    throw new Error('64bit varint not supported yet');
  }
}

Framer.prototype._inv = function _inv(command, items) {
  var res = [];
  var off = varint(res, items.length, 0);
  assert(items.length <= 50000);

  for (var i = 0; i < items.length; i++) {
    // Type
    off += writeU32(res, constants.inv[items[i].type], off);

    // Hash
    var hash = items[i].hash;
    if (typeof hash === 'string')
      hash = utils.toArray(hash, 'hex');
    assert.equal(hash.length, 32);
    res = res.concat(hash);

    off += hash.length;
  }

  return this.packet(command, res);
};

Framer.prototype.inv = function inv(items) {
  return this._inv('inv', items);
};

Framer.prototype.getData = function getData(items) {
  return this._inv('getdata', items);
};

Framer.prototype.notFound = function notFound(items) {
  return this._inv('notfound', items);
};

Framer.prototype.ping = function ping(nonce) {
  return this.packet('ping', nonce);
};

Framer.prototype.pong = function pong(nonce) {
  return this.packet('pong', nonce.slice(0, 8));
};

Framer.prototype.filterLoad = function filterLoad(bloom, update) {
  var filter = bloom.toArray();
  var before = [];
  varint(before, filter.length, 0);

  var after = new Array(9);

  // Number of hash functions
  writeU32(after, bloom.n, 0);

  // nTweak
  writeU32(after, bloom.tweak, 4);

  // nFlags
  after[8] = constants.filterFlags[update];

  var r = this.packet('filterload', before.concat(filter, after));
  return r;
};

Framer.prototype.filterClear = function filterClear() {
  return this.packet('filterclear', []);
};

Framer.prototype.getBlocks = function getBlocks(hashes, stop) {
  var p = [];
  writeU32(p, constants.version, 0);
  var off = 4 + varint(p, hashes.length, 4);
  p.length = off + 32 * (hashes.length + 1);

  for (var i = 0; i < hashes.length; i++) {
    var hash = hashes[i];
    if (typeof hash === 'string')
      hash = utils.toArray(hash, 'hex');
    var len = utils.copy(hash, p, off);
    for (; len < 32; len++)
      p[off + len] = 0;
    off += len;
  }

  if (stop) {
    stop = utils.toArray(stop, 'hex');
    var len = utils.copy(stop, p, off);
  } else {
    var len = 0;
  }
  for (; len < 32; len++)
    p[off + len] = 0;
  assert.equal(off + len, p.length);

  return this.packet('getblocks', p);
};

Framer.tx = function tx(tx) {
  var p = [];
  var off = writeU32(p, tx.version, 0);
  off += varint(p, tx.inputs.length, off);

  for (var i = 0; i < tx.inputs.length; i++) {
    var input = tx.inputs[i];

    off += utils.copy(utils.toArray(input.out.hash, 'hex'), p, off, true);
    off += writeU32(p, input.out.index, off);

    var s = bcoin.script.encode(input.script);
    off += varint(p, s.length, off);
    off += utils.copy(s, p, off, true);

    off += writeU32(p, input.seq, off);
  }

  off += varint(p, tx.outputs.length, off);
  for (var i = 0; i < tx.outputs.length; i++) {
    var output = tx.outputs[i];

    // Put LE value
    var value = output.value.toArray().slice().reverse();
    assert(value.length <= 8);
    off += utils.copy(value, p, off, true);
    for (var j = value.length; j < 8; j++, off++)
      p[off] = 0;

    var s = bcoin.script.encode(output.script);
    off += varint(p, s.length, off);
    off += utils.copy(s, p, off, true);
  }
  off += writeU32(p, tx.lock, off);

  return p;
};
<commit_msg>framer: add tx, block, and merkleblock packet sending to the framer.<commit_after>var bcoin = require('../../bcoin');
var constants = require('./constants');
var utils = bcoin.utils;
var assert = utils.assert;

var writeU32 = utils.writeU32;
var writeAscii = utils.writeAscii;

function Framer() {
  if (!(this instanceof Framer))
    return new Framer();
}
module.exports = Framer;

Framer.prototype.header = function header(cmd, payload) {
  assert(cmd.length < 12);
  assert(payload.length <= 0xffffffff);

  var h = new Array(24);

  // Magic value
  writeU32(h, constants.magic, 0);

  // Command
  var len = writeAscii(h, cmd, 4);
  for (var i = 4 + len; i < 4 + 12; i++)
    h[i] = 0;

  // Payload length
  writeU32(h, payload.length, 16);

  // Checksum
  utils.copy(utils.checksum(payload), h, 20);

  return h;
};

Framer.prototype.packet = function packet(cmd, payload) {
  var h = this.header(cmd, payload);
  return h.concat(payload);
};

Framer.prototype._addr = function addr(buf, off) {
  writeU32(buf, 1, off);
  writeU32(buf, 0, off + 4);
  writeU32(buf, 0, off + 8);
  writeU32(buf, 0, off + 12);
  writeU32(buf, 0xffff0000, off + 16);
  writeU32(buf, 0, off + 20);
  buf[off + 24] = 0;
  buf[off + 25] = 0;
};

Framer.prototype.version = function version(packet) {
  var p = new Array(86);

  if (!packet)
    packet = {};

  // Version
  writeU32(p, constants.version, 0);

  // Services
  writeU32(p, constants.services.network, 4);
  writeU32(p, 0, 8);

  // Timestamp
  var ts = ((+new Date()) / 1000) | 0;
  writeU32(p, ts, 12);
  writeU32(p, 0, 16);

  // Remote and local addresses
  this._addr(p, 20);
  this._addr(p, 46);

  // Nonce, very dramatic
  writeU32(p, (Math.random() * 0xffffffff) | 0, 72);
  writeU32(p, (Math.random() * 0xffffffff) | 0, 76);

  // No user-agent
  p[80] = 0;

  // Start height
  writeU32(p, packet.height, 81);

  // Relay
  p[85] = packet.relay ? 1 : 0;

  return this.packet('version', p);
};

Framer.prototype.verack = function verack() {
  return this.packet('verack', []);
};

function varint(arr, value, off) {
  if (!off)
    off = 0;
  if (value < 0xfd) {
    arr[off] = value;
    return 1;
  } else if (value <= 0xffff) {
    arr[off] = 0xfd;
    arr[off + 1] = value & 0xff;
    arr[off + 2] = value >>> 8;
    return 3;
  } else if (value <= 0xffffffff) {
    arr[off] = 0xfd;
    arr[off + 3] = value & 0xff;
    arr[off + 4] = (value >>> 8) & 0xff;
    arr[off + 5] = (value >>> 16) & 0xff;
    arr[off + 6] = value >>> 24;
    return 5;
  } else {
    throw new Error('64bit varint not supported yet');
  }
}

Framer.prototype._inv = function _inv(command, items) {
  var res = [];
  var off = varint(res, items.length, 0);
  assert(items.length <= 50000);

  for (var i = 0; i < items.length; i++) {
    // Type
    off += writeU32(res, constants.inv[items[i].type], off);

    // Hash
    var hash = items[i].hash;
    if (typeof hash === 'string')
      hash = utils.toArray(hash, 'hex');
    assert.equal(hash.length, 32);
    res = res.concat(hash);

    off += hash.length;
  }

  return this.packet(command, res);
};

Framer.prototype.inv = function inv(items) {
  return this._inv('inv', items);
};

Framer.prototype.getData = function getData(items) {
  return this._inv('getdata', items);
};

Framer.prototype.notFound = function notFound(items) {
  return this._inv('notfound', items);
};

Framer.prototype.ping = function ping(nonce) {
  return this.packet('ping', nonce);
};

Framer.prototype.pong = function pong(nonce) {
  return this.packet('pong', nonce.slice(0, 8));
};

Framer.prototype.filterLoad = function filterLoad(bloom, update) {
  var filter = bloom.toArray();
  var before = [];
  varint(before, filter.length, 0);

  var after = new Array(9);

  // Number of hash functions
  writeU32(after, bloom.n, 0);

  // nTweak
  writeU32(after, bloom.tweak, 4);

  // nFlags
  after[8] = constants.filterFlags[update];

  var r = this.packet('filterload', before.concat(filter, after));
  return r;
};

Framer.prototype.filterClear = function filterClear() {
  return this.packet('filterclear', []);
};

Framer.prototype.getBlocks = function getBlocks(hashes, stop) {
  var p = [];
  writeU32(p, constants.version, 0);
  var off = 4 + varint(p, hashes.length, 4);
  p.length = off + 32 * (hashes.length + 1);

  for (var i = 0; i < hashes.length; i++) {
    var hash = hashes[i];
    if (typeof hash === 'string')
      hash = utils.toArray(hash, 'hex');
    var len = utils.copy(hash, p, off);
    for (; len < 32; len++)
      p[off + len] = 0;
    off += len;
  }

  if (stop) {
    stop = utils.toArray(stop, 'hex');
    var len = utils.copy(stop, p, off);
  } else {
    var len = 0;
  }
  for (; len < 32; len++)
    p[off + len] = 0;
  assert.equal(off + len, p.length);

  return this.packet('getblocks', p);
};

Framer.tx = function tx(tx) {
  var p = [];
  var off = writeU32(p, tx.version, 0);
  off += varint(p, tx.inputs.length, off);

  for (var i = 0; i < tx.inputs.length; i++) {
    var input = tx.inputs[i];

    off += utils.copy(utils.toArray(input.out.hash, 'hex'), p, off, true);
    off += writeU32(p, input.out.index, off);

    var s = bcoin.script.encode(input.script);
    off += varint(p, s.length, off);
    off += utils.copy(s, p, off, true);

    off += writeU32(p, input.seq, off);
  }

  off += varint(p, tx.outputs.length, off);
  for (var i = 0; i < tx.outputs.length; i++) {
    var output = tx.outputs[i];

    // Put LE value
    var value = output.value.toArray().slice().reverse();
    assert(value.length <= 8);
    off += utils.copy(value, p, off, true);
    for (var j = value.length; j < 8; j++, off++)
      p[off] = 0;

    var s = bcoin.script.encode(output.script);
    off += varint(p, s.length, off);
    off += utils.copy(s, p, off, true);
  }
  off += writeU32(p, tx.lock, off);

  return p;
};

Framer.prototype.tx = function tx(tx) {
  return this.packet('tx', Framer.tx(tx));
};

Framer.block = function _block(block, type) {
  var p = [];
  var off = 0;

  off += writeU32(p, constants.version, off);

  // prev_block
  util.toArray(block.prevBlock, 'hex').forEach(function(ch) {
    p[off++] = ch;
  });

  // merkle_root
  util.toArray(block.merkleRoot, 'hex').forEach(function(ch) {
    p[off++] = ch;
  });

  // timestamp
  off += writeU32(p, block.ts, off);

  // bits
  off += writeU32(p, block.bits, off);

  // nonce
  off += writeU32(p, block.nonce, off);

  // txn_count
  off += varint(p, block.totalTX, off);

  if (type === 'merkleblock') {
    // hash count
    off += varint(p, block.hashes.length, off);
    // hashes
    block.hashes.forEach(function(hash) {
      utils.toArray(hash, 'hex').forEach(function(ch) {
        p[off++] = ch;
      });
    });
    // flag count
    off += varint(p, block.flags.length, off);
    // flags
    block.flags.forEach(function(flag) {
      p[off++] = flag;
    });
  }

  return p;
};

Framer.prototype.block = function _block(block) {
  return this.packet(Framer.block(block, 'block'));
};

Framer.prototype.merkleBlock = function merkleBlock(block) {
  // XXX Technically we're also supposed to send `tx` packets accompanying the
  // merkleblock here if we have them, as per the offical bitcoin client.
  return this.packet(Framer.block(block, 'merkleblock'));
};
<|endoftext|>


<commit_before>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

/**
 *  EditText.js
 *  Spreadsheet Editor
 *
 *  Created by Alexander Yuzhin on 12/21/16
 *  Copyright (c) 2018 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'text!spreadsheeteditor/mobile/app/template/EditText.template',
    'jquery',
    'underscore',
    'backbone',
    'common/mobile/lib/component/ThemeColorPalette',
    'common/mobile/lib/component/HsbColorPicker'
], function (editTemplate, $, _, Backbone) {
    'use strict';

    SSE.Views.EditText = Backbone.View.extend(_.extend((function() {
        // private
        var _fontsArray = [];
        return {
            // el: '.view-main',

            template: _.template(editTemplate),

            events: {
            },

            initialize: function () {
                Common.NotificationCenter.on('editcontainer:show', _.bind(this.initEvents, this));
                Common.NotificationCenter.on('fonts:load', _.bind(this.onApiFontsLoad, this));
            },

            initEvents: function () {
                var me = this;

                me.updateItemHandlers();
                me.initControls();
            },

            // Render layout
            render: function () {
                this.layout = $('
').append(this.template({
                    android : Common.SharedSettings.get('android'),
                    phone   : Common.SharedSettings.get('phone'),
                    scope   : this
                }));

                return this;
            },

            rootLayout: function () {
                if (this.layout) {
                    return this.layout
                        .find('#edit-text-root')
                        .html();
                }

                return '';
            },

            initControls: function () {
                //
            },

            updateItemHandlers: function () {
                var selectorsDynamicPage = [
                    '#edit-text'
                ].map(function (selector) {
                    return selector + ' a.item-link[data-page]';
                }).join(', ');

                $(selectorsDynamicPage).single('click', _.bind(this.onItemClick, this));
                $('#font-color').single('click', _.bind(this.showFontColor, this));
            },

            showPage: function (templateId, suspendEvent) {
                var rootView = SSE.getController('EditContainer').rootView;

                if (rootView && this.layout) {
                    var $content = this.layout.find(templateId);

                    // Android fix for navigation
                    if (Framework7.prototype.device.android) {
                        $content.find('.page').append($content.find('.navbar'));
                    }

                    rootView.router.load({
                        content: $content.html()
                    });

                    if (suspendEvent !== true) {
                        this.fireEvent('page:show', [this, templateId]);
                    }

                    this.initEvents();
                }
            },

            showFontColor: function () {
                var me = this;
                var page = '#edit-text-color';
                this.showPage(page, true);

                this.paletteTextColor = new Common.UI.ThemeColorPalette({
                    el: $('.page[data-page=edit-text-color] .page-content'),
                    transparent: true
                });
                this.paletteTextColor.on('customcolor', function () {
                    me.showCustomFillColor();
                });
                var template = _.template(['
',
                    '
',
                    '
',
                    '',
                    '
',
                    '
',
                    '
<%= scope.textAddCustomColor %>
',
                    '
',
                    '
',
                    '',
                    '
',
                    '
',
                    '
'].join(''));
                $('.page[data-page=edit-text-color] .page-content').append(template({scope: this}));
                $('#edit-text-add-custom-fill-color').single('click', _.bind(this.showCustomTextColor, this));

                Common.Utils.addScrollIfNeed('.page[data-page=edit-text]', '.page[data-page=edit-text] .page-content');
                this.fireEvent('page:show', [this, page]);
            },

            showCustomTextColor: function () {
                var me = this,
                    selector = '#edit-text-custom-color-view';
                me.showPage(selector, true);

                me.customTextColorPicker = new Common.UI.HsbColorPicker({
                    el: $('.page[data-page=edit-text-custom-color] .page-content'),
                    color: me.paletteTextColor.currentColor
                });
                me.customTextColorPicker.on('addcustomcolor', function (colorPicker, color) {
                    me.paletteTextColor.addNewDynamicColor(colorPicker, color);
                    SSE.getController('EditContainer').rootView.router.back();
                });

                me.fireEvent('page:show', [me, selector]);
            },

            renderFonts: function () {
                var me = this,
                    $template = $(
                        '
' +
                            '
' +
                                '' +
                                    '<input type="radio" name="font-name" value="{{name}}">' +
                                        (Framework7.prototype.device.android ? '

' : '') +
                                    '
' +
                                        '
{{name}}
' +
                                    '
' +
                                '' +
                            '
' +
                        '
'
                    );

                uiApp.virtualList('#font-list.virtual-list', {
                    items: _fontsArray,
                    template: $template.html(),
                    onItemsAfterInsert: function (list, fragment) {
                        var fontInfo = SSE.getController('EditText').getFontInfo();
                        $('#font-list input[name=font-name]').val([fontInfo.name]);

                        $('#font-list li').single('click', _.buffered(function (e) {
                            me.fireEvent('font:click', [me, e]);
                        }, 100));
                    }
                });
            },

            onItemClick: function (e) {
                var $target = $(e.currentTarget),
                    page = $target.data('page');

                if (page && page.length > 0 ) {
                    this.showPage(page);
                }
            },

            onApiFontsLoad: function (fonts, selcted) {
                _fontsArray = fonts;
            },

            textBack: 'Back',
            textFonts: 'Fonts',
            textTextColor: 'Text Color',
            textFillColor: 'Fill Color',
            textSize: 'Size',
            textCharacterBold: 'B',
            textCharacterItalic: 'I',
            textCharacterUnderline: 'U',
            textAddCustomColor: 'Add Custom Color',
            textCustomColor: 'Custom Color'
        }
    })(), SSE.Views.EditText || {}))
});<commit_msg>[SSE mobile] Fix bug 44356 (#323)<commit_after>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

/**
 *  EditText.js
 *  Spreadsheet Editor
 *
 *  Created by Alexander Yuzhin on 12/21/16
 *  Copyright (c) 2018 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'text!spreadsheeteditor/mobile/app/template/EditText.template',
    'jquery',
    'underscore',
    'backbone',
    'common/mobile/lib/component/ThemeColorPalette',
    'common/mobile/lib/component/HsbColorPicker'
], function (editTemplate, $, _, Backbone) {
    'use strict';

    SSE.Views.EditText = Backbone.View.extend(_.extend((function() {
        // private
        var _fontsArray = [];
        return {
            // el: '.view-main',

            template: _.template(editTemplate),

            events: {
            },

            initialize: function () {
                Common.NotificationCenter.on('editcontainer:show', _.bind(this.initEvents, this));
                Common.NotificationCenter.on('fonts:load', _.bind(this.onApiFontsLoad, this));
            },

            initEvents: function () {
                var me = this;

                me.updateItemHandlers();
                me.initControls();
            },

            // Render layout
            render: function () {
                this.layout = $('
').append(this.template({
                    android : Common.SharedSettings.get('android'),
                    phone   : Common.SharedSettings.get('phone'),
                    scope   : this
                }));

                return this;
            },

            rootLayout: function () {
                if (this.layout) {
                    return this.layout
                        .find('#edit-text-root')
                        .html();
                }

                return '';
            },

            initControls: function () {
                //
            },

            updateItemHandlers: function () {
                var selectorsDynamicPage = [
                    '#edit-text'
                ].map(function (selector) {
                    return selector + ' a.item-link[data-page]';
                }).join(', ');

                $(selectorsDynamicPage).single('click', _.bind(this.onItemClick, this));
                $('#font-color').single('click', _.bind(this.showFontColor, this));
            },

            showPage: function (templateId, suspendEvent) {
                var rootView = SSE.getController('EditContainer').rootView;

                if (rootView && this.layout) {
                    var $content = this.layout.find(templateId);

                    // Android fix for navigation
                    if (Framework7.prototype.device.android) {
                        $content.find('.page').append($content.find('.navbar'));
                    }

                    rootView.router.load({
                        content: $content.html()
                    });

                    if (suspendEvent !== true) {
                        this.fireEvent('page:show', [this, templateId]);
                    }

                    this.initEvents();
                }
            },

            showFontColor: function () {
                var me = this;
                var page = '#edit-text-color';
                this.showPage(page, true);

                this.paletteTextColor = new Common.UI.ThemeColorPalette({
                    el: $('.page[data-page=edit-text-color] .page-content'),
                    transparent: true
                });
                this.paletteTextColor.on('customcolor', function () {
                    me.showCustomTextColor();
                });
                var template = _.template(['
',
                    '
',
                    '
',
                    '',
                    '
',
                    '
',
                    '
<%= scope.textAddCustomColor %>
',
                    '
',
                    '
',
                    '',
                    '
',
                    '
',
                    '
'].join(''));
                $('.page[data-page=edit-text-color] .page-content').append(template({scope: this}));
                $('#edit-text-add-custom-fill-color').single('click', _.bind(this.showCustomTextColor, this));

                Common.Utils.addScrollIfNeed('.page[data-page=edit-text]', '.page[data-page=edit-text] .page-content');
                this.fireEvent('page:show', [this, page]);
            },

            showCustomTextColor: function () {
                var me = this,
                    selector = '#edit-text-custom-color-view';
                me.showPage(selector, true);

                me.customTextColorPicker = new Common.UI.HsbColorPicker({
                    el: $('.page[data-page=edit-text-custom-color] .page-content'),
                    color: me.paletteTextColor.currentColor
                });
                me.customTextColorPicker.on('addcustomcolor', function (colorPicker, color) {
                    me.paletteTextColor.addNewDynamicColor(colorPicker, color);
                    SSE.getController('EditContainer').rootView.router.back();
                });

                me.fireEvent('page:show', [me, selector]);
            },

            renderFonts: function () {
                var me = this,
                    $template = $(
                        '
' +
                            '
' +
                                '' +
                                    '<input type="radio" name="font-name" value="{{name}}">' +
                                        (Framework7.prototype.device.android ? '

' : '') +
                                    '
' +
                                        '
{{name}}
' +
                                    '
' +
                                '' +
                            '
' +
                        '
'
                    );

                uiApp.virtualList('#font-list.virtual-list', {
                    items: _fontsArray,
                    template: $template.html(),
                    onItemsAfterInsert: function (list, fragment) {
                        var fontInfo = SSE.getController('EditText').getFontInfo();
                        $('#font-list input[name=font-name]').val([fontInfo.name]);

                        $('#font-list li').single('click', _.buffered(function (e) {
                            me.fireEvent('font:click', [me, e]);
                        }, 100));
                    }
                });
            },

            onItemClick: function (e) {
                var $target = $(e.currentTarget),
                    page = $target.data('page');

                if (page && page.length > 0 ) {
                    this.showPage(page);
                }
            },

            onApiFontsLoad: function (fonts, selcted) {
                _fontsArray = fonts;
            },

            textBack: 'Back',
            textFonts: 'Fonts',
            textTextColor: 'Text Color',
            textFillColor: 'Fill Color',
            textSize: 'Size',
            textCharacterBold: 'B',
            textCharacterItalic: 'I',
            textCharacterUnderline: 'U',
            textAddCustomColor: 'Add Custom Color',
            textCustomColor: 'Custom Color'
        }
    })(), SSE.Views.EditText || {}))
});<|endoftext|>


<commit_before>// Licensed to Cloudera, Inc. under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

nv.models.growingPie = function() {
  "use strict";
  //============================================================
  // Public Variables with Default Settings
  //------------------------------------------------------------

  var margin = {top: 0, right: 0, bottom: 0, left: 0}
    , width = 500
    , height = 500
    , getX = function(d) { return d.x }
    , getY = function(d) { return d.y }
    , getDescription = function(d) { return d.description }
    , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
    , color = nv.utils.defaultColor()
    , valueFormat = d3.format(',.2f')
    , showLabels = true
    , pieLabelsOutside = true
    , donutLabelsOutside = false
    , labelType = "key"
    , labelThreshold = .02 //if slice percentage is under this, don't show label
    , donut = false
    , labelSunbeamLayout = false
    , startAngle = false
    , endAngle = false
    , donutRatio = 0.5
    , selectSlices = null
    , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout')
    ;

  //============================================================

  function chart(selection) {
    selection.each(function(data) {
      var availableWidth = width - margin.left - margin.right,
          availableHeight = height - margin.top - margin.bottom,
          radius = Math.min(availableWidth, availableHeight) / 2,
          arcRadius = radius-(radius / 5),
          container = d3.select(this);

      //------------------------------------------------------------
      // Setup containers and skeleton of chart

      //var wrap = container.selectAll('.nv-wrap.nv-pie').data([data]);
      var wrap = container.selectAll('.nv-wrap.nv-pie').data(data);
      var wrapEnter = wrap.enter().append('g').attr('class','nvd3 nv-wrap nv-pie nv-chart-' + id);
      var gEnter = wrapEnter.append('g');
      var g = wrap.select('g');

      gEnter.append('g').attr('class', 'nv-pie');
      gEnter.append('g').attr('class', 'nv-pieLabels');

      wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
      g.select('.nv-pie').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');
      g.select('.nv-pieLabels').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');

      //------------------------------------------------------------

      container
          .on('click', function(d,i) {
              dispatch.chartClick({
                  data: d,
                  index: i,
                  pos: d3.event,
                  id: id
              });
          });

      var arc = d3.svg.arc()
                  .outerRadius(arcRadius);

      var arcOver = d3.svg.arc()
                  .outerRadius(arcRadius + 10);

      if (startAngle) arc.startAngle(startAngle)
      if (endAngle) arc.endAngle(endAngle);
      if (donut) arc.innerRadius(radius * donutRatio);

      // Setup the Pie chart and choose the data element
      var pie = d3.layout.pie()
          .sort(null)
          .value(function(d) { return d.disabled ? 0 : getY(d) });

      var slices = wrap.select('.nv-pie').selectAll('.nv-slice')
          .data(pie).classed('selected', false);

      var pieLabels = wrap.select('.nv-pieLabels').selectAll('.nv-label')
          .data(pie);

      slices.exit().remove();
      pieLabels.exit().remove();

      selectSlices = function(selected) {
        $(selected).each(function(cnt, item){
          slices.each(function(d, i) {
            if ((typeof d.data.obj.from != "undefined" && d.data.obj.from == item) || d.data.obj.value == item) {
              d3.select(this).classed('selected', true);
              d3.select(this).select("path").transition().duration(100).attr("d", arcOver);
            }
          });
        });
      };

      var ae = slices.enter().append('g')
              .attr('class', 'nv-slice')
              .on('mouseover', function(d,i){
                d3.select(this).select("path").transition().duration(100).attr("d", arcOver);
                d3.select(this).classed('hover', true);
                dispatch.elementMouseover({
                    label: getX(d.data),
                    value: getY(d.data),
                    point: d.data,
                    pointIndex: i,
                    pos: [d3.event.pageX, d3.event.pageY],
                    id: id
                });
              })
              .on('mouseout', function(d,i){
                if (!d3.select(this).classed('selected')){
                  d3.select(this).select("path").transition().duration(100).attr("d", arc);
                }
                d3.select(this).classed('hover', false);
                dispatch.elementMouseout({
                    label: getX(d.data),
                    value: getY(d.data),
                    point: d.data,
                    index: i,
                    id: id
                });
              })
              .on('click', function(d,i) {
                d3.select(this).select("path").transition().duration(100).attr("d", arcOver);
                dispatch.elementClick({
                    label: getX(d.data),
                    value: getY(d.data),
                    point: d.data,
                    index: i,
                    pos: d3.event,
                    id: id
                });
                d3.event.stopPropagation();
              })
              .on('dblclick', function(d,i) {
                d3.select(this).select("path").transition().duration(100).attr("d", arc);
                dispatch.elementDblClick({
                    label: getX(d.data),
                    value: getY(d.data),
                    point: d.data,
                    index: i,
                    pos: d3.event,
                    id: id
                });
                d3.event.stopPropagation();
              });

        slices
            .attr('fill', function(d,i) { return d.data.color || color(d,i) })
            .attr('stroke', function(d,i) { return d.data.color || color(d,i) });

        var paths = ae.append('path')
            .each(function(d) { this._current = d; });
            //.attr('d', arc);

        slices.select('path')
          .transition()
            .attr('d', arc)
            .attrTween('d', arcTween);

        if (showLabels) {
          // This does the normal label
          var labelsArc = d3.svg.arc().innerRadius(0);

          if (pieLabelsOutside){ labelsArc = arc; }

          if (donutLabelsOutside) { labelsArc = d3.svg.arc().outerRadius(arc.outerRadius()); }

          pieLabels.enter().append("g").classed("nv-label",true)
            .each(function(d,i) {
                if (d.value > 0) {
                  var group = d3.select(this);

                  group
                    .attr('transform', function(d) {
                         if (labelSunbeamLayout) {
                           d.outerRadius = arcRadius + 10; // Set Outer Coordinate
                           d.innerRadius = arcRadius + 15; // Set Inner Coordinate
                           var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
                           if ((d.startAngle+d.endAngle)/2 < Math.PI) {
                             rotateAngle -= 90;
                           } else {
                             rotateAngle += 90;
                           }
                           return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')';
                         } else {
                           d.outerRadius = radius + 10; // Set Outer Coordinate
                           d.innerRadius = radius + 15; // Set Inner Coordinate
                           return 'translate(' + labelsArc.centroid(d) + ')'
                         }
                    });

                  group.append('rect')
                      .style('stroke', '#fff')
                      .style('fill', '#fff')
                      .attr("rx", 3)
                      .attr("ry", 3);

                  group.append('text')
                      .style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned
                      .style('fill', '#000')
                }

            });

          var labelLocationHash = {};
          var avgHeight = 14;
          var avgWidth = 140;
          var createHashKey = function(coordinates) {

              return Math.floor(coordinates[0]/avgWidth) * avgWidth + ',' + Math.floor(coordinates[1]/avgHeight) * avgHeight;
          };
          pieLabels.transition()
                .attr('transform', function(d) {
                if (d.value > 0) {
                  if (labelSunbeamLayout) {
                      d.outerRadius = arcRadius + 10; // Set Outer Coordinate
                      d.innerRadius = arcRadius + 15; // Set Inner Coordinate
                      var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
                      if ((d.startAngle+d.endAngle)/2 < Math.PI) {
                        rotateAngle -= 90;
                      } else {
                        rotateAngle += 90;
                      }
                      return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')';
                    } else {
                      d.outerRadius = radius + 10; // Set Outer Coordinate
                      d.innerRadius = radius + 15; // Set Inner Coordinate

                      /*
                      Overlapping pie labels are not good. What this attempts to do is, prevent overlapping.
                      Each label location is hashed, and if a hash collision occurs, we assume an overlap.
                      Adjust the label's y-position to remove the overlap.
                      */
                      var center = labelsArc.centroid(d);
                      var hashKey = createHashKey(center);
                      if (labelLocationHash[hashKey]) {
                        center[1] -= avgHeight;
                      }
                      labelLocationHash[createHashKey(center)] = true;
                      return 'translate(' + center + ')'
                    }
                  }
                });
          pieLabels.select(".nv-label text")
                .style('text-anchor', function(d){
                  if (d.value > 0) {
                    if (labelSunbeamLayout) {
                      return ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end'); //center the text on it's origin or begin/end if orthogonal aligned
                    }
                    else {
                       return 'middle';
                    }
                  }
                })
                .text(function(d, i) {
                  if (d.value > 0) {
                    var percent = (d.endAngle - d.startAngle) / (2 * Math.PI);
                    var labelTypes = {
                      "key": getX(d.data),
                      "value": getY(d.data),
                      "percent": d3.format('%')(percent)
                    };
                    return (d.value && percent > labelThreshold) ? labelTypes[labelType] : '';
                  }
                  else {
                    return '';
                  }
                });
        }

        // Computes the angle of an arc, converting from radians to degrees.
        function angle(d) {
          var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
          return a > 90 ? a - 180 : a;
        }

        function arcTween(a) {
          a.endAngle = isNaN(a.endAngle) ? 0 : a.endAngle;
          a.startAngle = isNaN(a.startAngle) ? 0 : a.startAngle;
          if (!donut) a.innerRadius = 0;
          var i = d3.interpolate(this._current, a);
          this._current = i(0);
          return function(t) {
            return arc(i(t));
          };
        }

        function tweenPie(b) {
          b.innerRadius = 0;
          var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
          return function(t) {
              return arc(i(t));
          };
        }

    });

    return chart;
  }

  //============================================================
  // Expose Public Variables
  //------------------------------------------------------------

  chart.dispatch = dispatch;
  chart.options = nv.utils.optionsFunc.bind(chart);

  chart.margin = function(_) {
    if (!arguments.length) return margin;
    margin.top    = typeof _.top    != 'undefined' ? _.top    : margin.top;
    margin.right  = typeof _.right  != 'undefined' ? _.right  : margin.right;
    margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
    margin.left   = typeof _.left   != 'undefined' ? _.left   : margin.left;
    return chart;
  };

  chart.width = function(_) {
    if (!arguments.length) return width;
    width = _;
    return chart;
  };

  chart.height = function(_) {
    if (!arguments.length) return height;
    height = _;
    return chart;
  };

  chart.values = function(_) {
    nv.log("pie.values() is no longer supported.");
    return chart;
  };

  chart.x = function(_) {
    if (!arguments.length) return getX;
    getX = _;
    return chart;
  };

  chart.y = function(_) {
    if (!arguments.length) return getY;
    getY = d3.functor(_);
    return chart;
  };

  chart.description = function(_) {
    if (!arguments.length) return getDescription;
    getDescription = _;
    return chart;
  };

  chart.showLabels = function(_) {
    if (!arguments.length) return showLabels;
    showLabels = _;
    return chart;
  };

  chart.labelSunbeamLayout = function(_) {
    if (!arguments.length) return labelSunbeamLayout;
    labelSunbeamLayout = _;
    return chart;
  };

  chart.donutLabelsOutside = function(_) {
    if (!arguments.length) return donutLabelsOutside;
    donutLabelsOutside = _;
    return chart;
  };

  chart.pieLabelsOutside = function(_) {
    if (!arguments.length) return pieLabelsOutside;
    pieLabelsOutside = _;
    return chart;
  };

  chart.labelType = function(_) {
    if (!arguments.length) return labelType;
    labelType = _;
    labelType = labelType || "key";
    return chart;
  };

  chart.donut = function(_) {
    if (!arguments.length) return donut;
    donut = _;
    return chart;
  };

  chart.donutRatio = function(_) {
    if (!arguments.length) return donutRatio;
    donutRatio = _;
    return chart;
  };

  chart.startAngle = function(_) {
    if (!arguments.length) return startAngle;
    startAngle = _;
    return chart;
  };

  chart.endAngle = function(_) {
    if (!arguments.length) return endAngle;
    endAngle = _;
    return chart;
  };

  chart.id = function(_) {
    if (!arguments.length) return id;
    id = _;
    return chart;
  };

  chart.color = function(_) {
    if (!arguments.length) return color;
    color = nv.utils.getColor(_);
    return chart;
  };

  chart.valueFormat = function(_) {
    if (!arguments.length) return valueFormat;
    valueFormat = _;
    return chart;
  };

  chart.labelThreshold = function(_) {
    if (!arguments.length) return labelThreshold;
    labelThreshold = _;
    return chart;
  };

  chart.selectSlices = function(args) {
    if (!arguments.length) return selectSlices;
    selectSlices(args);
    return chart;
  };
  //============================================================

  return chart;
}
<commit_msg>HUE-4304 [core] Pie slices shrink after wrong timing of resize of the pie<commit_after>// Licensed to Cloudera, Inc. under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

nv.models.growingPie = function() {
  "use strict";
  //============================================================
  // Public Variables with Default Settings
  //------------------------------------------------------------

  var margin = {top: 0, right: 0, bottom: 0, left: 0}
    , width = 500
    , height = 500
    , getX = function(d) { return d.x }
    , getY = function(d) { return d.y }
    , getDescription = function(d) { return d.description }
    , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
    , color = nv.utils.defaultColor()
    , valueFormat = d3.format(',.2f')
    , showLabels = true
    , pieLabelsOutside = true
    , donutLabelsOutside = false
    , labelType = "key"
    , labelThreshold = .02 //if slice percentage is under this, don't show label
    , donut = false
    , labelSunbeamLayout = false
    , startAngle = false
    , endAngle = false
    , donutRatio = 0.5
    , selectSlices = null
    , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout')
    ;

  //============================================================

  function chart(selection) {
    selection.each(function(data) {
      var availableWidth = width - margin.left - margin.right,
          availableHeight = height - margin.top - margin.bottom,
          radius = Math.min(availableWidth, availableHeight) / 2,
          arcRadius = radius-(radius / 5),
          container = d3.select(this);

      //------------------------------------------------------------
      // Setup containers and skeleton of chart

      //var wrap = container.selectAll('.nv-wrap.nv-pie').data([data]);
      var wrap = container.selectAll('.nv-wrap.nv-pie').data(data);
      var wrapEnter = wrap.enter().append('g').attr('class','nvd3 nv-wrap nv-pie nv-chart-' + id);
      var gEnter = wrapEnter.append('g');
      var g = wrap.select('g');

      gEnter.append('g').attr('class', 'nv-pie');
      gEnter.append('g').attr('class', 'nv-pieLabels');

      wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
      g.select('.nv-pie').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');
      g.select('.nv-pieLabels').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');

      //------------------------------------------------------------

      container
          .on('click', function(d,i) {
              dispatch.chartClick({
                  data: d,
                  index: i,
                  pos: d3.event,
                  id: id
              });
          });

      function updateVariables() {
        availableWidth = width - margin.left - margin.right;
        availableHeight = height - margin.top - margin.bottom;
        radius = Math.min(availableWidth, availableHeight) / 2;
        arcRadius = radius-(radius / 5);
      }

      var arcNormal = function() {
        updateVariables();
        return d3.svg.arc().outerRadius(arcRadius);
      }

      var arcOver = function() {
        updateVariables();
        return d3.svg.arc().outerRadius(arcRadius + 10);
      }

      if (startAngle) arcNormal().startAngle(startAngle)
      if (endAngle) arcNormal().endAngle(endAngle);
      if (donut) arcNormal().innerRadius(radius * donutRatio);

      // Setup the Pie chart and choose the data element
      var pie = d3.layout.pie()
          .sort(null)
          .value(function(d) { return d.disabled ? 0 : getY(d) });

      var slices = wrap.select('.nv-pie').selectAll('.nv-slice')
          .data(pie).classed('selected', false);

      var pieLabels = wrap.select('.nv-pieLabels').selectAll('.nv-label')
          .data(pie);

      slices.exit().remove();
      pieLabels.exit().remove();

      selectSlices = function(selected) {
        $(selected).each(function(cnt, item){
          slices.each(function(d, i) {
            if ((typeof d.data.obj.from != "undefined" && d.data.obj.from == item) || d.data.obj.value == item) {
              d3.select(this).classed('selected', true);
              d3.select(this).select("path").transition().duration(100).attr("d", arcOver());
            }
          });
        });
      };

      var ae = slices.enter().append('g')
              .attr('class', 'nv-slice')
              .on('mouseover', function(d,i){
                d3.select(this).select("path").transition().duration(100).attr("d", arcOver());
                d3.select(this).classed('hover', true);
                dispatch.elementMouseover({
                    label: getX(d.data),
                    value: getY(d.data),
                    point: d.data,
                    pointIndex: i,
                    pos: [d3.event.pageX, d3.event.pageY],
                    id: id
                });
              })
              .on('mouseout', function(d,i){
                if (!d3.select(this).classed('selected')){
                  d3.select(this).select("path").transition().duration(100).attr("d", arcNormal());
                }
                d3.select(this).classed('hover', false);
                dispatch.elementMouseout({
                    label: getX(d.data),
                    value: getY(d.data),
                    point: d.data,
                    index: i,
                    id: id
                });
              })
              .on('click', function(d,i) {
                d3.select(this).select("path").transition().duration(100).attr("d", arcOver());
                dispatch.elementClick({
                    label: getX(d.data),
                    value: getY(d.data),
                    point: d.data,
                    index: i,
                    pos: d3.event,
                    id: id
                });
                d3.event.stopPropagation();
              })
              .on('dblclick', function(d,i) {
                d3.select(this).select("path").transition().duration(100).attr("d", arcNormal());
                dispatch.elementDblClick({
                    label: getX(d.data),
                    value: getY(d.data),
                    point: d.data,
                    index: i,
                    pos: d3.event,
                    id: id
                });
                d3.event.stopPropagation();
              });

        slices
            .attr('fill', function(d,i) { return d.data.color || color(d,i) })
            .attr('stroke', function(d,i) { return d.data.color || color(d,i) });

        var paths = ae.append('path')
            .each(function(d) { this._current = d; });
            //.attr('d', arc);

        slices.select('path')
          .transition()
            .attr('d', arcNormal())
            .attrTween('d', arcTween);

        if (showLabels) {
          // This does the normal label
          var labelsArc = d3.svg.arc().innerRadius(0);

          if (pieLabelsOutside){ labelsArc = arcNormal(); }

          if (donutLabelsOutside) { labelsArc = d3.svg.arc().outerRadius(arc().outerRadius()); }

          pieLabels.enter().append("g").classed("nv-label",true)
            .each(function(d,i) {
                if (d.value > 0) {
                  var group = d3.select(this);

                  group
                    .attr('transform', function(d) {
                         if (labelSunbeamLayout) {
                           d.outerRadius = arcRadius + 10; // Set Outer Coordinate
                           d.innerRadius = arcRadius + 15; // Set Inner Coordinate
                           var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
                           if ((d.startAngle+d.endAngle)/2 < Math.PI) {
                             rotateAngle -= 90;
                           } else {
                             rotateAngle += 90;
                           }
                           return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')';
                         } else {
                           d.outerRadius = radius + 10; // Set Outer Coordinate
                           d.innerRadius = radius + 15; // Set Inner Coordinate
                           return 'translate(' + labelsArc.centroid(d) + ')'
                         }
                    });

                  group.append('rect')
                      .style('stroke', '#fff')
                      .style('fill', '#fff')
                      .attr("rx", 3)
                      .attr("ry", 3);

                  group.append('text')
                      .style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned
                      .style('fill', '#000')
                }

            });

          var labelLocationHash = {};
          var avgHeight = 14;
          var avgWidth = 140;
          var createHashKey = function(coordinates) {

              return Math.floor(coordinates[0]/avgWidth) * avgWidth + ',' + Math.floor(coordinates[1]/avgHeight) * avgHeight;
          };
          pieLabels.transition()
                .attr('transform', function(d) {
                if (d.value > 0) {
                  if (labelSunbeamLayout) {
                      d.outerRadius = arcRadius + 10; // Set Outer Coordinate
                      d.innerRadius = arcRadius + 15; // Set Inner Coordinate
                      var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
                      if ((d.startAngle+d.endAngle)/2 < Math.PI) {
                        rotateAngle -= 90;
                      } else {
                        rotateAngle += 90;
                      }
                      return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')';
                    } else {
                      d.outerRadius = radius + 10; // Set Outer Coordinate
                      d.innerRadius = radius + 15; // Set Inner Coordinate

                      /*
                      Overlapping pie labels are not good. What this attempts to do is, prevent overlapping.
                      Each label location is hashed, and if a hash collision occurs, we assume an overlap.
                      Adjust the label's y-position to remove the overlap.
                      */
                      var center = labelsArc.centroid(d);
                      var hashKey = createHashKey(center);
                      if (labelLocationHash[hashKey]) {
                        center[1] -= avgHeight;
                      }
                      labelLocationHash[createHashKey(center)] = true;
                      return 'translate(' + center + ')'
                    }
                  }
                });
          pieLabels.select(".nv-label text")
                .style('text-anchor', function(d){
                  if (d.value > 0) {
                    if (labelSunbeamLayout) {
                      return ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end'); //center the text on it's origin or begin/end if orthogonal aligned
                    }
                    else {
                       return 'middle';
                    }
                  }
                })
                .text(function(d, i) {
                  if (d.value > 0) {
                    var percent = (d.endAngle - d.startAngle) / (2 * Math.PI);
                    var labelTypes = {
                      "key": getX(d.data),
                      "value": getY(d.data),
                      "percent": d3.format('%')(percent)
                    };
                    return (d.value && percent > labelThreshold) ? labelTypes[labelType] : '';
                  }
                  else {
                    return '';
                  }
                });
        }

        // Computes the angle of an arc, converting from radians to degrees.
        function angle(d) {
          var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
          return a > 90 ? a - 180 : a;
        }

        function arcTween(a) {
          a.endAngle = isNaN(a.endAngle) ? 0 : a.endAngle;
          a.startAngle = isNaN(a.startAngle) ? 0 : a.startAngle;
          if (!donut) a.innerRadius = 0;
          var i = d3.interpolate(this._current, a);
          this._current = i(0);
          return function(t) {
            return arcNormal()(i(t));
          };
        }

        function tweenPie(b) {
          b.innerRadius = 0;
          var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
          return function(t) {
              return arcNormal()(i(t));
          };
        }

    });

    return chart;
  }

  //============================================================
  // Expose Public Variables
  //------------------------------------------------------------

  chart.dispatch = dispatch;
  chart.options = nv.utils.optionsFunc.bind(chart);

  chart.margin = function(_) {
    if (!arguments.length) return margin;
    margin.top    = typeof _.top    != 'undefined' ? _.top    : margin.top;
    margin.right  = typeof _.right  != 'undefined' ? _.right  : margin.right;
    margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
    margin.left   = typeof _.left   != 'undefined' ? _.left   : margin.left;
    return chart;
  };

  chart.width = function(_) {
    if (!arguments.length) return width;
    width = _;
    return chart;
  };

  chart.height = function(_) {
    if (!arguments.length) return height;
    height = _;
    return chart;
  };

  chart.values = function(_) {
    nv.log("pie.values() is no longer supported.");
    return chart;
  };

  chart.x = function(_) {
    if (!arguments.length) return getX;
    getX = _;
    return chart;
  };

  chart.y = function(_) {
    if (!arguments.length) return getY;
    getY = d3.functor(_);
    return chart;
  };

  chart.description = function(_) {
    if (!arguments.length) return getDescription;
    getDescription = _;
    return chart;
  };

  chart.showLabels = function(_) {
    if (!arguments.length) return showLabels;
    showLabels = _;
    return chart;
  };

  chart.labelSunbeamLayout = function(_) {
    if (!arguments.length) return labelSunbeamLayout;
    labelSunbeamLayout = _;
    return chart;
  };

  chart.donutLabelsOutside = function(_) {
    if (!arguments.length) return donutLabelsOutside;
    donutLabelsOutside = _;
    return chart;
  };

  chart.pieLabelsOutside = function(_) {
    if (!arguments.length) return pieLabelsOutside;
    pieLabelsOutside = _;
    return chart;
  };

  chart.labelType = function(_) {
    if (!arguments.length) return labelType;
    labelType = _;
    labelType = labelType || "key";
    return chart;
  };

  chart.donut = function(_) {
    if (!arguments.length) return donut;
    donut = _;
    return chart;
  };

  chart.donutRatio = function(_) {
    if (!arguments.length) return donutRatio;
    donutRatio = _;
    return chart;
  };

  chart.startAngle = function(_) {
    if (!arguments.length) return startAngle;
    startAngle = _;
    return chart;
  };

  chart.endAngle = function(_) {
    if (!arguments.length) return endAngle;
    endAngle = _;
    return chart;
  };

  chart.id = function(_) {
    if (!arguments.length) return id;
    id = _;
    return chart;
  };

  chart.color = function(_) {
    if (!arguments.length) return color;
    color = nv.utils.getColor(_);
    return chart;
  };

  chart.valueFormat = function(_) {
    if (!arguments.length) return valueFormat;
    valueFormat = _;
    return chart;
  };

  chart.labelThreshold = function(_) {
    if (!arguments.length) return labelThreshold;
    labelThreshold = _;
    return chart;
  };

  chart.selectSlices = function(args) {
    if (!arguments.length) return selectSlices;
    selectSlices(args);
    return chart;
  };
  //============================================================

  return chart;
}
<|endoftext|>


<commit_before>const OFFSET = 90;
class Car extends Phaser.Sprite {

  constructor(game, x, y, key, frame) {
    super(game, x, y, key, frame);
    this.game = game;

    this.cursors = game.input.keyboard.createCursorKeys();
    this.angle = OFFSET;

    //Enable physics on the player
    //game.physics.arcade.enable(this);
  }

  update() {
    this.body.velocity.x = 0;
    this.body.velocity.y = 0;
    this.body.angularVelocity = 0;

    if (this.cursors.left.isDown)
    {
        this.body.angularVelocity = -200;
    }
    else if (this.cursors.right.isDown)
    {
        this.body.angularVelocity = 200;
    }

    if (this.cursors.up.isDown)
    {
        this.body.velocity.copyFrom(this.game.physics.arcade.velocityFromAngle(this.angle - OFFSET, 300));
    }
  }
}

export default Car;<commit_msg>remove comments<commit_after>const OFFSET = 90;
class Car extends Phaser.Sprite {

  constructor(game, x, y, key, frame) {
    super(game, x, y, key, frame);
    this.game = game;

    this.cursors = game.input.keyboard.createCursorKeys();
    this.angle = OFFSET;
  }

  update() {
    this.body.velocity.x = 0;
    this.body.velocity.y = 0;
    this.body.angularVelocity = 0;

    if (this.cursors.left.isDown)
    {
        this.body.angularVelocity = -200;
    }
    else if (this.cursors.right.isDown)
    {
        this.body.angularVelocity = 200;
    }

    if (this.cursors.up.isDown)
    {
        this.body.velocity.copyFrom(this.game.physics.arcade.velocityFromAngle(this.angle - OFFSET, 300));
    }
  }
}

export default Car;<|endoftext|>


<commit_before>(function () {
  'use strict';

  var conversions, identifier, locale, options, units;

  conversions = [
    1000,
    60,
    60,
    24,
    30,
    12,
    100,
  ];
  identifier = {
    en: {
      past: ' ago',
      present: 'just now',
    },
    ja: {
      past: '前',
      present: 'たった今',
    },
  },
  locale = {
    en: {
      pluralable: true,
    },
    ja: {
      pluralable: false,
    },
  },
  options = {
    locale: 'en',
  };
  units = {
    en: [
      'second',
      'minute',
      'hour',
      'day',
      'month',
      'year',
    ],
    ja: [
      '秒',
      '分',
      '時間',
      '日',
      'か月',
      '年',
    ],
  };

  function _pluralize(target) {
    if (!locale[options.locale].pluralable) return target;

    return parseInt(target) > 1 ? target + 's' : target;
  }

  function relativize(params) {
    var delta;

    if (params !== undefined) for (var i = 0, k = Object.keys(params), l = k.length; i < l; i++) {
      options[k[i]] = params[k[i]];
    }

    delta = new Date() - this;

    for (var i = 0, l = conversions.length; i < l; i++) {
      delta = Math.floor(delta / conversions[i]);

      if (delta < conversions[i + 1]) {
        return i < 1 && 15 > Math.abs(delta)
            ? identifier[options.locale]['present']
            : _pluralize(delta + ' ' + units[options.locale][i], options.locale) + identifier[options.locale]['past'];
      }
    }
  }

  function toDate() {
    return new Date(Date.parse(this));
  }

  Object.defineProperties(Date.prototype, {
    relativize: {
      configurable: true,
      enumerable: false,
      writable: true,
      value: relativize,
    },
  });

  Object.defineProperties(String.prototype, {
    toDate: {
      configurable: true,
      enumerable: false,
      writable: true,
      value: toDate,
    },
  });
})();
<commit_msg>Fixed incorrect value for calculate the years<commit_after>(function () {
  'use strict';

  var conversions, identifier, locale, options, units;

  conversions = [
    1000,
    60,
    60,
    24,
    30.44,
    12,
    100,
  ];
  identifier = {
    en: {
      past: ' ago',
      present: 'just now',
    },
    ja: {
      past: '前',
      present: 'たった今',
    },
  },
  locale = {
    en: {
      pluralable: true,
    },
    ja: {
      pluralable: false,
    },
  },
  options = {
    locale: 'en',
  };
  units = {
    en: [
      'second',
      'minute',
      'hour',
      'day',
      'month',
      'year',
    ],
    ja: [
      '秒',
      '分',
      '時間',
      '日',
      'か月',
      '年',
    ],
  };

  function _pluralize(target) {
    if (!locale[options.locale].pluralable) return target;

    return parseInt(target) > 1 ? target + 's' : target;
  }

  function relativize(params) {
    var delta;

    if (params !== undefined) for (var i = 0, k = Object.keys(params), l = k.length; i < l; i++) {
      options[k[i]] = params[k[i]];
    }

    delta = new Date() - this;

    for (var i = 0, l = conversions.length; i < l; i++) {
      delta = Math.floor(delta / conversions[i]);

      if (delta < conversions[i + 1]) {
        return i < 1 && 15 > Math.abs(delta)
            ? identifier[options.locale]['present']
            : _pluralize(delta + ' ' + units[options.locale][i], options.locale) + identifier[options.locale]['past'];
      }
    }
  }

  function toDate() {
    return new Date(Date.parse(this));
  }

  Object.defineProperties(Date.prototype, {
    relativize: {
      configurable: true,
      enumerable: false,
      writable: true,
      value: relativize,
    },
  });

  Object.defineProperties(String.prototype, {
    toDate: {
      configurable: true,
      enumerable: false,
      writable: true,
      value: toDate,
    },
  });
})();
<|endoftext|>


<commit_before>const { isArray, mix } = require('../util');
const { delegateStyle } = require('../global');

module.exports = {
  getDefaultCfg() {
    return {
      updateEdge: true,
      delegate: true,
      delegateStyle: {}
    };
  },
  getEvents() {
    return {
      'node:dragstart': 'onDragStart',
      'node:drag': 'onDrag',
      'node:dragend': 'onDragEnd'
    };
  },
  onDragStart(e) {
    if (!this.shouldBegin.call(this, e)) {
      return;
    }
    this.target = e.item;
    this.origin = {
      x: e.clientX,
      y: e.clientY
    };
  },
  onDrag(e) {
    if (!this.origin) {
      return;
    }
    if (!this.get('shouldUpdate').call(this, e)) {
      return;
    }
    this._update(this.target, e);
  },
  onDragEnd(e) {
    if (!this.shouldEnd.call(this, e)) {
      return;
    }
    if (!this.origin) {
      return;
    }
    const delegateShape = e.item.get('delegateShape');
    if (delegateShape) {
      delegateShape.remove();
      this.target.set('delegateShape', null);
    }
    this._update(this.target, e, true);
    this.point = null;
    this.origin = null;
  },
  _update(item, e, force) {
    const origin = this.origin;
    const model = item.get('model');
    if (!this.point) {
      this.point = {
        x: model.x,
        y: model.y
      };
    }
    const x = e.clientX - origin.x + this.point.x;
    const y = e.clientY - origin.y + this.point.y;
    this.origin = { x: e.clientX, y: e.clientY };
    this.point = { x, y };
    if (this.delegate && !force) {
      this._updateDelegate(item, x, y);
      return;
    }
    if (this.get('updateEdge')) {
      this.graph.updateItem(item, { x, y });
    } else {
      item.update({ x, y });
      this.graph.paint();
    }
  },
  _updateDelegate(item, x, y) {
    const self = this;
    let shape = item.get('delegateShape');
    let size = item.get('model').size;
    if (!size) {
      const bbox = item.get('keyShape').getBBox();
      size = [ bbox.width, bbox.height ];
    }
    if (!isArray(size)) {
      size = [ size, size ];
    }
    if (!shape) {
      const parent = self.graph.get('group');
      const attrs = mix({}, delegateStyle, this.delegateStyle);
      shape = parent.addShape('rect', {
        attrs: {
          width: size[0],
          height: size[1],
          ...attrs
        }
      });
      shape.set('capture', false);
      item.set('delegateShape', shape);
    }
    // model上的x, y是相对于图形中心的，delegateShape是g实例，x,y是绝对坐标
    x -= size[0] / 2;
    y -= size[1] / 2;
    shape.attr({ x, y });
    this.graph.paint();
  }
};
<commit_msg>chore(drag-node): use updatePosition to update node itself<commit_after>const { isArray, mix } = require('../util');
const { delegateStyle } = require('../global');

module.exports = {
  getDefaultCfg() {
    return {
      updateEdge: true,
      delegate: true,
      delegateStyle: {}
    };
  },
  getEvents() {
    return {
      'node:dragstart': 'onDragStart',
      'node:drag': 'onDrag',
      'node:dragend': 'onDragEnd'
    };
  },
  onDragStart(e) {
    if (!this.shouldBegin.call(this, e)) {
      return;
    }
    this.target = e.item;
    this.origin = {
      x: e.clientX,
      y: e.clientY
    };
  },
  onDrag(e) {
    if (!this.origin) {
      return;
    }
    if (!this.get('shouldUpdate').call(this, e)) {
      return;
    }
    this._update(this.target, e);
  },
  onDragEnd(e) {
    if (!this.shouldEnd.call(this, e)) {
      return;
    }
    if (!this.origin) {
      return;
    }
    const delegateShape = e.item.get('delegateShape');
    if (delegateShape) {
      delegateShape.remove();
      this.target.set('delegateShape', null);
    }
    this._update(this.target, e, true);
    this.point = null;
    this.origin = null;
  },
  _update(item, e, force) {
    const origin = this.origin;
    const model = item.get('model');
    if (!this.point) {
      this.point = {
        x: model.x,
        y: model.y
      };
    }
    const x = e.clientX - origin.x + this.point.x;
    const y = e.clientY - origin.y + this.point.y;
    this.origin = { x: e.clientX, y: e.clientY };
    this.point = { x, y };
    if (this.delegate && !force) {
      this._updateDelegate(item, x, y);
      return;
    }
    if (this.get('updateEdge')) {
      this.graph.updateItem(item, { x, y });
    } else {
      item.updatePosition({ x, y });
      this.graph.paint();
    }
  },
  _updateDelegate(item, x, y) {
    const self = this;
    let shape = item.get('delegateShape');
    let size = item.get('model').size;
    if (!size) {
      const bbox = item.get('keyShape').getBBox();
      size = [ bbox.width, bbox.height ];
    }
    if (!isArray(size)) {
      size = [ size, size ];
    }
    if (!shape) {
      const parent = self.graph.get('group');
      const attrs = mix({}, delegateStyle, this.delegateStyle);
      shape = parent.addShape('rect', {
        attrs: {
          width: size[0],
          height: size[1],
          ...attrs
        }
      });
      shape.set('capture', false);
      item.set('delegateShape', shape);
    }
    // model上的x, y是相对于图形中心的，delegateShape是g实例，x,y是绝对坐标
    x -= size[0] / 2;
    y -= size[1] / 2;
    shape.attr({ x, y });
    this.graph.paint();
  }
};
<|endoftext|>


<commit_before>function _array_to_compact_imagedata(ar,w,h=null) {
	h = h || Math.ceil(ar.length / w / 4)
	var img = ctx.createImageData(w,h)
	for (var i=0; i<w*h*4; i++) {
		if (i<ar.length) {
			var v = ar[i]
			img.data[i] = v>0 ? 256-v : 0
		} else {
			img.data[i] = 1
		}
	}
	return img
}

function _compact_imagedate_to_array(img,n) {
	var ar = []
	for (var i=0; i<n; i++) {
		var v = img.data[i]
		ar.push(v>0 ? 256-v : 0)
	}
	return ar
}
<commit_msg>itsy - packed_array<commit_after>function _array_to_compact_imagedata(ar,w,h=null) {
	h = h || Math.ceil(ar.length / w / 4)
	var img = ctx.createImageData(w,h)
	for (var i=0; i<w*h*4; i++) {
		if (i<ar.length) {
			var v = ar[i]
			img.data[i] = v>0 ? 256-v : 0
		} else {
			img.data[i] = 1
		}
	}
	return img
}

function _compact_imagedate_to_array(img,n) {
	var ar = []
	for (var i=0; i<n; i++) {
		var v = img.data[i]
		ar.push(v>0 ? 256-v : 0)
	}
	return ar
}

function _array_to_packed_array(ar,max_v) {
	var out = []
	var n = 1
	var k = 0
	if (max_v==1) 				n=8
	if (max_v>1 && max_v<4) 	n=4
	if (max_v>3 && max_v<16) 	n=2

	var val = 0
	var j
	for (var i in ar) {
		j = i%n
		var v = max(0,min(ar[i],max_v))
		val |= v
		if (j==n-1) {
			out.push(val)
			val = 0
		} else {
			val <<= 8/n
		}
	}
	if (j != n-1) {
		out.push(val)
	}
	return out
}

function _packed_array_to_array(ar,max_v) {
	var out = []
	var m = 255
	var n = 1
	if (max_v==1) 				{n=8;m=1}
	if (max_v>1 && max_v<4) 	{n=4;m=3}
	if (max_v>3 && max_v<16) 	{n=2;m=15}

	for (var i in ar) {
		var batch = []
		var v = ar[i]
		for (var j=0; j<n; j++) {
			var val = v&m
			batch.unshift(val)
			v >>= 8/n
		}
		for (var j in batch) {
			out.push(batch[j])
		}
	}
	return out
}
<|endoftext|>