<commit_before>var ok = require('assert').ok,
    __slice = [].slice

function detach (cartridge) {
    var magazine = cartridge._magazine, cache = magazine._cache
    magazine.heft -= cartridge.heft
    cache.heft -= cartridge.heft
    delete cache._cache[cartridge._compoundKey]
    magazine.count--
    cache.count--
    unlink(cartridge)
}

function unlink (cartridge, prefix) {
    if (!prefix) {
        unlink(cartridge, 'cache')
        unlink(cartridge, 'magazine')
    } else {
        var prev = '_' + prefix + 'Previous'
        var next = '_' + prefix + 'Next'
        cartridge[prev][next] = cartridge[next]
        cartridge[next][prev] = cartridge[prev]
    }
}

function link (cartridge, previous, prefix) {
    var prev = '_' + prefix + 'Previous'
    var next = '_' + prefix + 'Next'
    cartridge[next] = previous[next]
    cartridge[prev] = previous
    cartridge[next][prev] = cartridge
    previous[next] = cartridge
}

function Cache (options) {
    options = options || {}

    this._clock = options.clock || function () {
        return Date.now()
    }

    var head = {}
    head._cachePrevious = head._cacheNext = head

    this._cache = {}
    this._head = head
    this._nextKey = 0

    this.count = 0
    this.holds = 0
    this.heft = 0
}

Cache.prototype.createMagazine = function () {
    var key = ':' + (++this._nextKey) + ':'
    return new Magazine(this, key)
}

Cache.prototype.purge = function () {
    return purge.call(this, '_cachePrevious', __slice.call(arguments))
}

Cache.prototype.expire = function (expired) {
    expire(this, expired)
}

function Magazine (cache, key) {
    var head = {}
    head._magazinePrevious = head._magazineNext = head

    this._cache = cache
    this._key = key
    this._head = head

    this.count = 0
    this.holds = 0
    this.heft = 0
}

Magazine.prototype.hold = function (key, defaultValue) {
    var compoundKey = this._key + key
    var cartridge = this._cache._cache[compoundKey]
    if (!cartridge) {
        if (typeof defaultValue == 'function') {
            defaultValue = defaultValue()
        }
        cartridge = this._cache._cache[compoundKey] =
            new Cartridge(this, key, defaultValue, compoundKey)
        this.count++
        this._cache.count++
    } else {
        unlink(cartridge)
    }
    link(cartridge, this._cache._head, 'cache')
    link(cartridge, this._head, 'magazine')
    cartridge.holds++
    this.holds++
    this._cache.holds++
    cartridge.when = this._cache._clock()
    return cartridge
}

Magazine.prototype.get = function (key) {
    var compoundKey = this._key + key
    var cartridge = this._cache._cache[compoundKey]
    if (!cartridge || !cartridge.holds) {
        throw new Error('attempt to get a cartridge not held')
    }
    return cartridge
}

function expire (collection, expired) {
    var purge = collection.purge()
    while (purge.cartridge && purge.cartridge.when <= expired) {
        purge.cartridge.remove()
        purge.next()
    }
    purge.release()
}

function purge (next, vargs) {
    var downTo, condition, gather, stop, head, iterator, cache, magazine
    if (vargs.length == 0) {
        return new Purge(this, next)
    }
    downTo = vargs.shift()
    if (typeof vargs[0] == 'function') {
        condition = vargs.shift()
    }
    if (Array.isArray(vargs[0])) {
        gather = vargs.shift()
    }
    condition || (condition = function () { return true })
    stop = downTo
    head = this._head
    iterator = head
    if (typeof downTo == 'number') {
        downTo = Math.max(downTo, -1)
        stop = function () { return this.heft <= downTo }.bind(this)
    }
    while (iterator[next] !== head && !stop(iterator[next])) {
        var cartridge = iterator[next]
        if (!cartridge.holds && condition(cartridge)) {
            magazine = cartridge._magazine, cache = magazine._cache
            if (gather) {
                gather.push(cartridge.value)
            }
            detach(cartridge)
        } else {
            iterator = cartridge
        }
    }
}

Magazine.prototype.purge = function () {
    return purge.call(this, '_magazinePrevious', __slice.call(arguments))
}

Magazine.prototype.expire = function (expired) {
    expire(this, expired)
}

function Cartridge (magazine, key, value, compoundKey) {
    this.key = key
    this.value = value

    this._magazine = magazine
    this._compoundKey = compoundKey

    this.heft = 0
    this.holds = 0
}

Cartridge.prototype.adjustHeft = function (heft) {
    this.heft += heft
    this._magazine.heft += heft
    this._magazine._cache.heft += heft
    return this
}

Cartridge.prototype.release = function () {
    if (!this.holds) {
        throw new Error('attempt to release a cartridge not held')
    }
    if (--this.holds == 0) {
        this._magazine.holds--
        this._magazine._cache.holds--
    }
}

Cartridge.prototype.remove = function () {
    if (this.holds != 1) {
        throw new Error('attempt to remove cartridge held by others')
    }
    detach(this)
}

function Purge (object, next) {
    this._object = object
    this._next = next
    this.cartridge = this._object._head
//    console.log(object, next, this.cartridge)
    this.next()
}

Purge.prototype.next = function () {
    do {
        this.cartridge = this.cartridge[this._next] === this._object._head
                       ? null : this.cartridge[this._next]
    } while (this.cartridge && this.cartridge.holds)
    if (this.cartridge) {
        this.cartridge.holds = 1
    }
}

Purge.prototype.release = function () {
    if (this.cartridge) {
        this.cartridge.release()
    }
}

module.exports = Cache
<commit_msg>Note on rename.<commit_after>var ok = require('assert').ok,
    __slice = [].slice // rename

function detach (cartridge) {
    var magazine = cartridge._magazine, cache = magazine._cache
    magazine.heft -= cartridge.heft
    cache.heft -= cartridge.heft
    delete cache._cache[cartridge._compoundKey]
    magazine.count--
    cache.count--
    unlink(cartridge)
}

function unlink (cartridge, prefix) {
    if (!prefix) {
        unlink(cartridge, 'cache')
        unlink(cartridge, 'magazine')
    } else {
        var prev = '_' + prefix + 'Previous'
        var next = '_' + prefix + 'Next'
        cartridge[prev][next] = cartridge[next]
        cartridge[next][prev] = cartridge[prev]
    }
}

function link (cartridge, previous, prefix) {
    var prev = '_' + prefix + 'Previous'
    var next = '_' + prefix + 'Next'
    cartridge[next] = previous[next]
    cartridge[prev] = previous
    cartridge[next][prev] = cartridge
    previous[next] = cartridge
}

function Cache (options) {
    options = options || {}

    this._clock = options.clock || function () {
        return Date.now()
    }

    var head = {}
    head._cachePrevious = head._cacheNext = head

    this._cache = {}
    this._head = head
    this._nextKey = 0

    this.count = 0
    this.holds = 0
    this.heft = 0
}

Cache.prototype.createMagazine = function () {
    var key = ':' + (++this._nextKey) + ':'
    return new Magazine(this, key)
}

Cache.prototype.purge = function () {
    return purge.call(this, '_cachePrevious', __slice.call(arguments))
}

Cache.prototype.expire = function (expired) {
    expire(this, expired)
}

function Magazine (cache, key) {
    var head = {}
    head._magazinePrevious = head._magazineNext = head

    this._cache = cache
    this._key = key
    this._head = head

    this.count = 0
    this.holds = 0
    this.heft = 0
}

Magazine.prototype.hold = function (key, defaultValue) {
    var compoundKey = this._key + key
    var cartridge = this._cache._cache[compoundKey]
    if (!cartridge) {
        if (typeof defaultValue == 'function') {
            defaultValue = defaultValue()
        }
        cartridge = this._cache._cache[compoundKey] =
            new Cartridge(this, key, defaultValue, compoundKey)
        this.count++
        this._cache.count++
    } else {
        unlink(cartridge)
    }
    link(cartridge, this._cache._head, 'cache')
    link(cartridge, this._head, 'magazine')
    cartridge.holds++
    this.holds++
    this._cache.holds++
    cartridge.when = this._cache._clock()
    return cartridge
}

Magazine.prototype.get = function (key) {
    var compoundKey = this._key + key
    var cartridge = this._cache._cache[compoundKey]
    if (!cartridge || !cartridge.holds) {
        throw new Error('attempt to get a cartridge not held')
    }
    return cartridge
}

function expire (collection, expired) {
    var purge = collection.purge()
    while (purge.cartridge && purge.cartridge.when <= expired) {
        purge.cartridge.remove()
        purge.next()
    }
    purge.release()
}

function purge (next, vargs) {
    var downTo, condition, gather, stop, head, iterator, cache, magazine
    if (vargs.length == 0) {
        return new Purge(this, next)
    }
    downTo = vargs.shift()
    if (typeof vargs[0] == 'function') {
        condition = vargs.shift()
    }
    if (Array.isArray(vargs[0])) {
        gather = vargs.shift()
    }
    condition || (condition = function () { return true })
    stop = downTo
    head = this._head
    iterator = head
    if (typeof downTo == 'number') {
        downTo = Math.max(downTo, -1)
        stop = function () { return this.heft <= downTo }.bind(this)
    }
    while (iterator[next] !== head && !stop(iterator[next])) {
        var cartridge = iterator[next]
        if (!cartridge.holds && condition(cartridge)) {
            magazine = cartridge._magazine, cache = magazine._cache
            if (gather) {
                gather.push(cartridge.value)
            }
            detach(cartridge)
        } else {
            iterator = cartridge
        }
    }
}

Magazine.prototype.purge = function () {
    return purge.call(this, '_magazinePrevious', __slice.call(arguments))
}

Magazine.prototype.expire = function (expired) {
    expire(this, expired)
}

function Cartridge (magazine, key, value, compoundKey) {
    this.key = key
    this.value = value

    this._magazine = magazine
    this._compoundKey = compoundKey

    this.heft = 0
    this.holds = 0
}

Cartridge.prototype.adjustHeft = function (heft) {
    this.heft += heft
    this._magazine.heft += heft
    this._magazine._cache.heft += heft
    return this
}

Cartridge.prototype.release = function () {
    if (!this.holds) {
        throw new Error('attempt to release a cartridge not held')
    }
    if (--this.holds == 0) {
        this._magazine.holds--
        this._magazine._cache.holds--
    }
}

Cartridge.prototype.remove = function () {
    if (this.holds != 1) {
        throw new Error('attempt to remove cartridge held by others')
    }
    detach(this)
}

function Purge (object, next) {
    this._object = object
    this._next = next
    this.cartridge = this._object._head
//    console.log(object, next, this.cartridge)
    this.next()
}

Purge.prototype.next = function () {
    do {
        this.cartridge = this.cartridge[this._next] === this._object._head
                       ? null : this.cartridge[this._next]
    } while (this.cartridge && this.cartridge.holds)
    if (this.cartridge) {
        this.cartridge.holds = 1
    }
}

Purge.prototype.release = function () {
    if (this.cartridge) {
        this.cartridge.release()
    }
}

module.exports = Cache
<|endoftext|>


<commit_before>'use strict';

var mocha = require('mocha'),
    sinon = require('sinon'),
    expect = require('chai').expect,
    rewire = require('rewire'),
    requestify = rewire('../lib/Requestify.js'),
    Q = require('q');

describe('Requestify', function() {

    afterEach(function() {
        requestify.responseEncoding('utf8');
    });

    describe('#responseEncoding()', function() {

        it('Should return utf8 by default', function() {
            expect(requestify.responseEncoding()).to.equal('utf8');
        });

        it('Should set the new encoding and return it on request', function() {
            requestify.responseEncoding('newEncoding');

            expect(requestify.responseEncoding()).to.equal('newEncoding');
        });
    });

    describe('#request()', function() {
        var httpStub,
            httpsStub;

        beforeEach(function() {
            httpStub = sinon.stub().returns({
                on: function() {},
                end: function() {}
            });

            httpsStub = sinon.stub().returns({
                on: function() {},
                end: function() {}
            });

            requestify.__set__('http', {
                request: httpStub
            });

            requestify.__set__('https', {
                request: httpsStub
            });

        });

        afterEach(function() {
            httpStub = null;
            httpsStub = null;
        });

        it('Should return a promise', function() {
            requestify.request('http://wix.com', {
                method: 'POST',
                dataType: 'json'
            });
        });

        it('Should call https module since the request is https: protocol', function() {
            requestify.request('https://wix.com', {
                method: 'POST'
            });

            expect(httpsStub.called).to.equal(true);
        });

        it('Should call http module since request is http: protocol', function() {
            requestify.request('http://wix.com', {
                method: 'POST'
            });

            expect(httpStub.called).to.equal(true);
        });

        it('Should return a promise object', function() {
            expect(requestify.request('https://wix.com', {
                method: 'POST'
            })).to.have.property('then');
        });
    });

    describe('Method specific public methods', function() {
        beforeEach(function() {
            requestify.request = sinon.stub();
        });

        afterEach(function() {
            requestify.request = null;
        });

        describe('#get()', function() {
            it('should call #request() with then given body and method GET', function() {
                requestify.get('http://www.wix.com', {
                    cookies: {
                        key: 'val'
                    }
                });

                expect(requestify.request.calledWith('http://www.wix.com', {
                    method: 'GET',
                    cookies: {
                        key: 'val'
                    }
                })).to.equal(true);
            });
        });

        describe('#post()', function() {
            it('should call #request() with then given body and method POST', function() {
                requestify.post('http://www.wix.com', {
                    foo: 'bar'
                }, {
                    cookies: {
                        key: 'val'
                    }
                });

                expect(requestify.request.calledWith('http://www.wix.com', {
                    method: 'POST',
                    cookies: {
                        key: 'val'
                    },
                    body: {
                        foo: 'bar'
                    }
                })).to.equal(true);
            });
        });

        describe('#put()', function() {
            it('should call #request() with then given body and method PUT', function() {
                requestify.put('http://www.wix.com', {
                    foo: 'bar'
                }, {
                    cookies: {
                        key: 'val'
                    }
                });

                expect(requestify.request.calledWith('http://www.wix.com', {
                    method: 'PUT',
                    cookies: {
                        key: 'val'
                    },
                    body: {
                        foo: 'bar'
                    }
                })).to.equal(true);
            });
        });

        describe('#del()', function() {
            it('should call #request() with then given body and method DELETE', function() {
                requestify.delete('http://www.wix.com', {
                    cookies: {
                        key: 'val'
                    }
                });

                expect(requestify.request.calledWith('http://www.wix.com', {
                    method: 'DELETE',
                    cookies: {
                        key: 'val'
                    }
                })).to.equal(true);
            });
        });

        describe('#head()', function() {
            it('should call #request() with then given body and method HEAD', function() {
                requestify.head('http://www.wix.com', {
                    body: {
                        key: 'val'
                    }
                });

                expect(requestify.request.calledWith('http://www.wix.com', {
                    method: 'HEAD',
                    body: {
                        key: 'val'
                    }
                })).to.equal(true);
            });
        });
    });
});<commit_msg>Added some tests to Requestify tests<commit_after>'use strict';

var mocha = require('mocha'),
    sinon = require('sinon'),
    expect = require('chai').expect,
    rewire = require('rewire'),
    requestify = rewire('../lib/Requestify.js'),
    Q = require('q');

describe('Requestify', function() {
    var cacheStub;

    afterEach(function() {
        requestify.responseEncoding('utf8');
    });

    beforeEach(function() {
        cacheStub = {
            setCacheTransporter: sinon.stub(),
            get: sinon.stub(),
            set: sinon.stub(),
            purge: sinon.stub(),
            isTransportAvailable: sinon.stub()
        };

        requestify.__set__('cache', cacheStub);
    });

    describe('#responseEncoding()', function() {

        it('Should return utf8 by default', function() {
            expect(requestify.responseEncoding()).to.equal('utf8');
        });

        it('Should set the new encoding and return it on request', function() {
            requestify.responseEncoding('newEncoding');

            expect(requestify.responseEncoding()).to.equal('newEncoding');
        });
    });

    describe('#request()', function() {
        var httpStub,
            httpsStub,
            cacheStub;

        beforeEach(function() {
            httpStub = sinon.stub().returns({
                on: function() {},
                end: function() {}
            });

            httpsStub = sinon.stub().returns({
                on: function() {},
                end: function() {}
            });

            requestify.__set__('http', {
                request: httpStub
            });

            requestify.__set__('https', {
                request: httpsStub
            });
        });

        afterEach(function() {
            httpStub = null;
            httpsStub = null;
        });

        it('Should return a promise', function() {
            requestify.request('http://wix.com', {
                method: 'POST',
                dataType: 'json'
            });
        });

        it('Should call https module since the request is https: protocol', function() {
            requestify.request('https://wix.com', {
                method: 'POST'
            });

            expect(httpsStub.called).to.equal(true);
        });

        it('Should call http module since request is http: protocol', function() {
            requestify.request('http://wix.com', {
                method: 'POST'
            });

            expect(httpStub.called).to.equal(true);
        });

        it('Should return a promise object', function() {
            expect(requestify.request('https://wix.com', {
                method: 'POST'
            })).to.have.property('then');
        });
    });

    describe('Method specific public methods', function() {
        beforeEach(function() {
            requestify.request = sinon.stub();
        });

        afterEach(function() {
            requestify.request = null;
        });

        describe('#get()', function() {
            it('should call #request() with then given body and method GET', function() {
                requestify.get('http://www.wix.com', {
                    cookies: {
                        key: 'val'
                    }
                });

                expect(requestify.request.calledWith('http://www.wix.com', {
                    method: 'GET',
                    cookies: {
                        key: 'val'
                    }
                })).to.equal(true);
            });
        });

        describe('#post()', function() {
            it('should call #request() with then given body and method POST', function() {
                requestify.post('http://www.wix.com', {
                    foo: 'bar'
                }, {
                    cookies: {
                        key: 'val'
                    }
                });

                expect(requestify.request.calledWith('http://www.wix.com', {
                    method: 'POST',
                    cookies: {
                        key: 'val'
                    },
                    body: {
                        foo: 'bar'
                    }
                })).to.equal(true);
            });
        });

        describe('#put()', function() {
            it('should call #request() with then given body and method PUT', function() {
                requestify.put('http://www.wix.com', {
                    foo: 'bar'
                }, {
                    cookies: {
                        key: 'val'
                    }
                });

                expect(requestify.request.calledWith('http://www.wix.com', {
                    method: 'PUT',
                    cookies: {
                        key: 'val'
                    },
                    body: {
                        foo: 'bar'
                    }
                })).to.equal(true);
            });
        });

        describe('#del()', function() {
            it('should call #request() with then given body and method DELETE', function() {
                requestify.delete('http://www.wix.com', {
                    cookies: {
                        key: 'val'
                    }
                });

                expect(requestify.request.calledWith('http://www.wix.com', {
                    method: 'DELETE',
                    cookies: {
                        key: 'val'
                    }
                })).to.equal(true);
            });
        });

        describe('#head()', function() {
            it('should call #request() with then given body and method HEAD', function() {
                requestify.head('http://www.wix.com', {
                    body: {
                        key: 'val'
                    }
                });

                expect(requestify.request.calledWith('http://www.wix.com', {
                    method: 'HEAD',
                    body: {
                        key: 'val'
                    }
                })).to.equal(true);
            });
        });

        describe('#cacheTransporter()', function() {
            it('should do nothing since called it without any transporter', function() {
                requestify.cacheTransporter();

                expect(cacheStub.setCacheTransporter.called).to.equal(false);
            });

            it('should call cache.setCacheTransporter with the transporter', function() {
                requestify.cacheTransporter({});

                expect(cacheStub.setCacheTransporter.called).to.equal(true);
            });
        });
    });
});<|endoftext|>


<commit_before>import 'should'
import $ from 'teaspoon'
import Selection from '../src/Selection.jsx'
import React, { Component, PropTypes } from 'react'

describe("Selection", () => {
  const Blah = class A extends Component {
    static displayName = 'A'
    static propTypes = {
      name: PropTypes.string,
      children: PropTypes.any
    }
    render() {
      return (

hi {this.props.name}

          {this.props.children}

      )
    }
  }
  describe("higher-order container creation", () => {
    it("should make a component", () => {
      const Thing = Selection(Blah)
      Thing.displayName.should.be.eql('Selection(A)')

      const stuff = $(<Thing>
hi
</Thing>).render()

      stuff.find('.foo').text().should.eql('hi')

      const nextstuff = $(<Thing name="Greg" />).render()

      nextstuff.find('p').text().should.eql('hi Greg')
    })
  })

  describe("updateState", () => {
    const Thing = Selection(Blah)
    let stuff
    let component
    beforeEach(() => {
      stuff = $(<Thing></Thing>).render()
      component = stuff[0]
    })
    afterEach(() => {
      stuff.unmount()
    })

    it("should keep state the same if passed null", () => {
      component.setState({
        selecting: false,
        selectedNodes: [1,2,3],
        selectedValues: [4,5,6],
        containerBounds: component.bounds
      })

      component.state.should.eql({
        selecting: false,
        selectedNodes: [1,2,3],
        selectedNodeList: [],
        selectedValues: [4,5,6],
        selectedValueList: [],
        containerBounds: component.bounds
      })

      component.updateState(null, null, null)

      component.state.should.eql({
        selecting: false,
        selectedNodes: [1,2,3],
        selectedNodeList: [],
        selectedValues: [4,5,6],
        selectedValueList: [],
        containerBounds: component.bounds
      })
    })
    it("should set values if passed", () => {
      component.setState({
        selecting: false,
        selectedNodes: [1,2,3],
        selectedValues: [4,5,6],
        containerBounds: component.bounds
      })

      component.state.should.eql({
        selecting: false,
        selectedNodes: [1,2,3],
        selectedNodeList: [],
        selectedValues: [4,5,6],
        selectedValueList: [],
        containerBounds: component.bounds
      })

      component.updateState(true, ['hi'], ['there'])

      component.state.should.eql({
        selecting: true,
        selectedNodes: ['hi'],
        selectedNodeList: [],
        selectedValues: ['there'],
        selectedValueList: [],
        containerBounds: component.bounds
      })
    })
    it("should call onSelectSlot if constantSelection is enabled")
    it("should not call onSelectSlot if constantSelection is disabled")
  })
})
<commit_msg>another passing test<commit_after>import 'should'
import $ from 'teaspoon'
import Selection from '../src/Selection.jsx'
import Selectable from '../src/Selectable.jsx'
import React, { Component, PropTypes } from 'react'

describe("Selection", () => {
  const Blah = class A extends Component {
    static displayName = 'A'
    static propTypes = {
      name: PropTypes.string,
      children: PropTypes.any
    }
    render() {
      return (

hi {this.props.name}

          {this.props.children}

      )
    }
  }
  const Child = class B extends Component {
    static displayName='B'
    static propTypes = {
      value: PropTypes.string,
      id: PropTypes.number
    }
    render() {
      return
{this.props.value}

    }
  }
  const options = {
    value: (props) => props.value,
    key: (props) => props.id,
    cacheBounds: true
  }
  const SelectableChild = Selectable(Child, options)
  describe("higher-order container creation", () => {
    it("should make a component", () => {
      const Thing = Selection(Blah)
      Thing.displayName.should.be.eql('Selection(A)')

      const stuff = $(<Thing>
hi
</Thing>).render()

      stuff.find('.foo').text().should.eql('hi')

      const nextstuff = $(<Thing name="Greg" />).render()

      nextstuff.find('p').text().should.eql('hi Greg')
    })
  })

  describe("updateState", () => {
    const Thing = Selection(Blah)
    let stuff
    let component
    beforeEach(() => {
      stuff = $(<Thing></Thing>).render()
      component = stuff[0]
    })
    afterEach(() => {
      stuff.unmount()
    })

    it("should keep state the same if passed null", () => {
      component.setState({
        selecting: false,
        selectedNodes: [1,2,3],
        selectedValues: [4,5,6],
        containerBounds: component.bounds
      })

      component.state.should.eql({
        selecting: false,
        selectedNodes: [1,2,3],
        selectedNodeList: [],
        selectedValues: [4,5,6],
        selectedValueList: [],
        containerBounds: component.bounds
      })

      component.updateState(null, null, null)

      component.state.should.eql({
        selecting: false,
        selectedNodes: [1,2,3],
        selectedNodeList: [],
        selectedValues: [4,5,6],
        selectedValueList: [],
        containerBounds: component.bounds
      })
    })
    it("should set values if passed", () => {
      component.setState({
        selecting: false,
        selectedNodes: [1,2,3],
        selectedValues: [4,5,6],
        containerBounds: component.bounds
      })

      component.state.should.eql({
        selecting: false,
        selectedNodes: [1,2,3],
        selectedNodeList: [],
        selectedValues: [4,5,6],
        selectedValueList: [],
        containerBounds: component.bounds
      })

      component.updateState(true, ['hi'], ['there'])

      component.state.should.eql({
        selecting: true,
        selectedNodes: ['hi'],
        selectedNodeList: [],
        selectedValues: ['there'],
        selectedValueList: [],
        containerBounds: component.bounds
      })
    })

    it("should call onSelectSlot if constantSelect is enabled", () => {
      const spy = sinon.spy()
      stuff = $((
        <Thing selectable constantSelect onSelectSlot={spy}>
          <SelectableChild value="hi" key={1} />
          <SelectableChild value="hi2" key={2} />
          <SelectableChild value="hi3" key={3} />
        </Thing>
          )).render()
      const children = stuff.find(SelectableChild)
      component = stuff[0]
      component.bounds = {hi:'hi'}
      const selectable1 = children[0]
      const selectable2 = children[1]
      const selectable3 = children[2]

      component.updateState(null, {
        3: {node: selectable3},
        1: {node: selectable1},
        2: {node: selectable2}
      }, {
        3: 'hi3',
        1: 'hi',
        2: 'hi2'
      })

      expect(spy.called).to.be.true

      spy.args[0].should.have.length(5)
      spy.args[0][0].should.be.eql({
        3: 'hi3',
        1: 'hi',
        2: 'hi2'
      })
      expect(spy.args[0][1]()).to.eql({
        3: {node: selectable3},
        1: {node: selectable1},
        2: {node: selectable2}
      })
      expect(spy.args[0][2]).to.eql(['hi', 'hi2', 'hi3'])
      expect(spy.args[0][3]()).to.eql([
        {node: selectable1},
        {node: selectable2},
        {node: selectable3}
      ])
      expect(spy.args[0][4]).to.eql({hi: 'hi'})
    })
    it("should not call onSelectSlot if constantSelection is disabled")
  })
})
<|endoftext|>


<commit_before>var should = require("should");
var path = require("path");
var fs = require("fs");
var vm = require("vm");
var Test = require("mocha/lib/test");
var checkArrayExpectation = require("./checkArrayExpectation");

var webpack = require("../lib/webpack");

var harmony = (+process.versions.node.split(".")[0]) >= 4;

describe("TestCases", function() {
	var casesPath = path.join(__dirname, "cases");
	var categories = fs.readdirSync(casesPath);
	categories = categories.map(function(cat) {
		return {
			name: cat,
			tests: fs.readdirSync(path.join(casesPath, cat)).filter(function(folder) {
				return folder.indexOf("_") < 0;
			})
		};
	});
	[{
		name: "normal"
	}, {
		name: "hot",
		plugins: [
			new webpack.HotModuleReplacementPlugin()
		]
	}, {
		name: "hot-multi-step",
		plugins: [
			new webpack.HotModuleReplacementPlugin({
				multiStep: true
			})
		]
	}, {
		name: "devtool-eval",
		devtool: "eval"
	}, {
		name: "devtool-eval-named-modules",
		devtool: "eval",
		plugins: [
			new webpack.NamedModulesPlugin()
		]
	}, {
		name: "devtool-eval-source-map",
		devtool: "#eval-source-map"
	}, {
		name: "devtool-inline-source-map",
		devtool: "inline-source-map"
	}, {
		name: "devtool-source-map",
		devtool: "#@source-map"
	}, {
		name: "devtool-cheap-inline-source-map",
		devtool: "cheap-inline-source-map"
	}, {
		name: "devtool-cheap-eval-source-map",
		devtool: "cheap-eval-source-map"
	}, {
		name: "devtool-cheap-eval-module-source-map",
		devtool: "cheap-eval-module-source-map"
	}, {
		name: "devtool-cheap-source-map",
		devtool: "cheap-source-map"
	}, {
		name: "minimized",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.UglifyJsPlugin({
				sourceMap: false
			})
		]
	}, {
		name: "minimized-source-map",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.UglifyJsPlugin()
		]
	}, {
		name: "deduped",
		plugins: [
			new webpack.optimize.DedupePlugin(),
			new webpack.NamedModulesPlugin()
		]
	}, {
		name: "minimized-deduped",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.DedupePlugin(),
			new webpack.optimize.UglifyJsPlugin()
		]
	}, {
		name: "optimized",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.DedupePlugin(),
			new webpack.optimize.OccurrenceOrderPlugin(),
			new webpack.optimize.UglifyJsPlugin()
		]
	}, {
		name: "all-combined",
		devtool: "#@source-map",
		excludeNominimize: true,
		plugins: [
			new webpack.HotModuleReplacementPlugin(),
			new webpack.optimize.DedupePlugin(),
			new webpack.optimize.OccurrenceOrderPlugin(),
			new webpack.optimize.UglifyJsPlugin(),
			new webpack.NamedModulesPlugin()
		]
	}].forEach(function(config) {
		describe(config.name, function() {
			categories.forEach(function(category) {
				describe(category.name, function() {
					this.timeout(20000);
					category.tests.filter(function(test) {
						var minimizeCheckOk = !config.excludeNominimize || test.indexOf("nominimize") < 0;
						var harmonyCheckOk = !/^es6/.test(test) || harmony;
						return minimizeCheckOk && harmonyCheckOk;
					}).forEach(function(testName) {
						var suite = describe(testName, function() {});
						it(testName + " should compile", function(done) {
							this.timeout(10000);
							var testDirectory = path.join(casesPath, category.name, testName);
							var outputDirectory = path.join(__dirname, "js", config.name, category.name, testName);
							var options = {
								context: casesPath,
								entry: "./" + category.name + "/" + testName + "/index",
								target: "async-node",
								devtool: config.devtool,
								output: {
									pathinfo: true,
									path: outputDirectory,
									filename: "bundle.js"
								},
								resolve: {
									modules: ["web_modules", "node_modules"],
									mainFields: ["webpack", "browser", "web", "browserify", ["jam", "main"], "main"],
									aliasFields: ["browser"],
									extensions: ["", ".webpack.js", ".web.js", ".js"]
								},
								resolveLoader: {
									modules: ["web_loaders", "web_modules", "node_loaders", "node_modules"],
									mainFields: ["webpackLoader", "webLoader", "loader", "main"],
									extensions: ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"]
								},
								module: {
									loaders: [{
										test: /\.json$/,
										loader: "json-loader"
									}, {
										test: /\.coffee$/,
										loader: "coffee-loader"
									}, {
										test: /\.jade$/,
										loader: "jade-loader"
									}]
								},
								plugins: (config.plugins || []).concat(
									new webpack.dependencies.LabeledModulesPlugin()
								)
							};
							webpack(options, function(err, stats) {
								if(err) return done(err);
								fs.writeFileSync(path.join(outputDirectory, "stats.txt"), stats.toString(), "utf-8");
								var jsonStats = stats.toJson({
									errorDetails: true
								});
								if(checkArrayExpectation(testDirectory, jsonStats, "error", "Error", done)) return;
								if(checkArrayExpectation(testDirectory, jsonStats, "warning", "Warning", done)) return;
								var exportedTest = 0;

								function _it(title, fn) {
									var test = new Test(title, fn);
									suite.addTest(test);
									exportedTest++;
									return test;
								}

								function _require(module) {
									if(module.substr(0, 2) === "./") {
										var p = path.join(outputDirectory, module);
										var fn = vm.runInThisContext("(function(require, module, exports, __dirname, it) {" + fs.readFileSync(p, "utf-8") + "\n})", p);
										var module = {
											exports: {}
										};
										fn.call(module.exports, _require, module, module.exports, outputDirectory, _it);
										return module.exports;
									} else return require(module);
								}
								_require("./bundle.js");
								if(exportedTest === 0) return done(new Error("No tests exported by test case"));
								done();
							});
						});
					});
				});
			});
		});
	});
});
<commit_msg>increase test timeout<commit_after>var should = require("should");
var path = require("path");
var fs = require("fs");
var vm = require("vm");
var Test = require("mocha/lib/test");
var checkArrayExpectation = require("./checkArrayExpectation");

var webpack = require("../lib/webpack");

var harmony = (+process.versions.node.split(".")[0]) >= 4;

describe("TestCases", function() {
	var casesPath = path.join(__dirname, "cases");
	var categories = fs.readdirSync(casesPath);
	categories = categories.map(function(cat) {
		return {
			name: cat,
			tests: fs.readdirSync(path.join(casesPath, cat)).filter(function(folder) {
				return folder.indexOf("_") < 0;
			})
		};
	});
	[{
		name: "normal"
	}, {
		name: "hot",
		plugins: [
			new webpack.HotModuleReplacementPlugin()
		]
	}, {
		name: "hot-multi-step",
		plugins: [
			new webpack.HotModuleReplacementPlugin({
				multiStep: true
			})
		]
	}, {
		name: "devtool-eval",
		devtool: "eval"
	}, {
		name: "devtool-eval-named-modules",
		devtool: "eval",
		plugins: [
			new webpack.NamedModulesPlugin()
		]
	}, {
		name: "devtool-eval-source-map",
		devtool: "#eval-source-map"
	}, {
		name: "devtool-inline-source-map",
		devtool: "inline-source-map"
	}, {
		name: "devtool-source-map",
		devtool: "#@source-map"
	}, {
		name: "devtool-cheap-inline-source-map",
		devtool: "cheap-inline-source-map"
	}, {
		name: "devtool-cheap-eval-source-map",
		devtool: "cheap-eval-source-map"
	}, {
		name: "devtool-cheap-eval-module-source-map",
		devtool: "cheap-eval-module-source-map"
	}, {
		name: "devtool-cheap-source-map",
		devtool: "cheap-source-map"
	}, {
		name: "minimized",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.UglifyJsPlugin({
				sourceMap: false
			})
		]
	}, {
		name: "minimized-source-map",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.UglifyJsPlugin()
		]
	}, {
		name: "deduped",
		plugins: [
			new webpack.optimize.DedupePlugin(),
			new webpack.NamedModulesPlugin()
		]
	}, {
		name: "minimized-deduped",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.DedupePlugin(),
			new webpack.optimize.UglifyJsPlugin()
		]
	}, {
		name: "optimized",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.DedupePlugin(),
			new webpack.optimize.OccurrenceOrderPlugin(),
			new webpack.optimize.UglifyJsPlugin()
		]
	}, {
		name: "all-combined",
		devtool: "#@source-map",
		excludeNominimize: true,
		plugins: [
			new webpack.HotModuleReplacementPlugin(),
			new webpack.optimize.DedupePlugin(),
			new webpack.optimize.OccurrenceOrderPlugin(),
			new webpack.optimize.UglifyJsPlugin(),
			new webpack.NamedModulesPlugin()
		]
	}].forEach(function(config) {
		describe(config.name, function() {
			categories.forEach(function(category) {
				describe(category.name, function() {
					this.timeout(20000);
					category.tests.filter(function(test) {
						var minimizeCheckOk = !config.excludeNominimize || test.indexOf("nominimize") < 0;
						var harmonyCheckOk = !/^es6/.test(test) || harmony;
						return minimizeCheckOk && harmonyCheckOk;
					}).forEach(function(testName) {
						var suite = describe(testName, function() {});
						it(testName + " should compile", function(done) {
							var testDirectory = path.join(casesPath, category.name, testName);
							var outputDirectory = path.join(__dirname, "js", config.name, category.name, testName);
							var options = {
								context: casesPath,
								entry: "./" + category.name + "/" + testName + "/index",
								target: "async-node",
								devtool: config.devtool,
								output: {
									pathinfo: true,
									path: outputDirectory,
									filename: "bundle.js"
								},
								resolve: {
									modules: ["web_modules", "node_modules"],
									mainFields: ["webpack", "browser", "web", "browserify", ["jam", "main"], "main"],
									aliasFields: ["browser"],
									extensions: ["", ".webpack.js", ".web.js", ".js"]
								},
								resolveLoader: {
									modules: ["web_loaders", "web_modules", "node_loaders", "node_modules"],
									mainFields: ["webpackLoader", "webLoader", "loader", "main"],
									extensions: ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"]
								},
								module: {
									loaders: [{
										test: /\.json$/,
										loader: "json-loader"
									}, {
										test: /\.coffee$/,
										loader: "coffee-loader"
									}, {
										test: /\.jade$/,
										loader: "jade-loader"
									}]
								},
								plugins: (config.plugins || []).concat(
									new webpack.dependencies.LabeledModulesPlugin()
								)
							};
							webpack(options, function(err, stats) {
								if(err) return done(err);
								fs.writeFileSync(path.join(outputDirectory, "stats.txt"), stats.toString(), "utf-8");
								var jsonStats = stats.toJson({
									errorDetails: true
								});
								if(checkArrayExpectation(testDirectory, jsonStats, "error", "Error", done)) return;
								if(checkArrayExpectation(testDirectory, jsonStats, "warning", "Warning", done)) return;
								var exportedTest = 0;

								function _it(title, fn) {
									var test = new Test(title, fn);
									suite.addTest(test);
									exportedTest++;
									return test;
								}

								function _require(module) {
									if(module.substr(0, 2) === "./") {
										var p = path.join(outputDirectory, module);
										var fn = vm.runInThisContext("(function(require, module, exports, __dirname, it) {" + fs.readFileSync(p, "utf-8") + "\n})", p);
										var module = {
											exports: {}
										};
										fn.call(module.exports, _require, module, module.exports, outputDirectory, _it);
										return module.exports;
									} else return require(module);
								}
								_require("./bundle.js");
								if(exportedTest === 0) return done(new Error("No tests exported by test case"));
								done();
							});
						});
					});
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>var should = require("should");
var path = require("path");
var fs = require("fs");
var vm = require("vm");
var Test = require("mocha/lib/test");
var checkArrayExpectation = require("./checkArrayExpectation");

var webpack = require("../lib/webpack");

var harmony = (+process.versions.node.split(".")[0]) >= 4;

describe("TestCases", function() {
	var casesPath = path.join(__dirname, "cases");
	var categories = fs.readdirSync(casesPath);
	categories = categories.map(function(cat) {
		return {
			name: cat,
			tests: fs.readdirSync(path.join(casesPath, cat)).filter(function(folder) {
				return folder.indexOf("_") < 0;
			})
		};
	});
	[{
		name: "normal"
	}, {
		name: "hot",
		plugins: [
			new webpack.HotModuleReplacementPlugin()
		]
	}, {
		name: "hot-multi-step",
		plugins: [
			new webpack.HotModuleReplacementPlugin({
				multiStep: true
			})
		]
	}, {
		name: "devtool-eval",
		devtool: "eval"
	}, {
		name: "devtool-eval-named-modules",
		devtool: "eval",
		plugins: [
			new webpack.NamedModulesPlugin()
		]
	}, {
		name: "devtool-eval-source-map",
		devtool: "#eval-source-map"
	}, {
		name: "devtool-inline-source-map",
		devtool: "inline-source-map"
	}, {
		name: "devtool-source-map",
		devtool: "#@source-map"
	}, {
		name: "devtool-cheap-inline-source-map",
		devtool: "cheap-inline-source-map"
	}, {
		name: "devtool-cheap-eval-source-map",
		devtool: "cheap-eval-source-map"
	}, {
		name: "devtool-cheap-eval-module-source-map",
		devtool: "cheap-eval-module-source-map"
	}, {
		name: "devtool-cheap-source-map",
		devtool: "cheap-source-map"
	}, {
		name: "minimized",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.UglifyJsPlugin({
				sourceMap: false
			})
		]
	}, {
		name: "minimized-source-map",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.UglifyJsPlugin()
		]
	}, {
		name: "deduped",
		plugins: [
			new webpack.optimize.DedupePlugin(),
			new webpack.NamedModulesPlugin()
		]
	}, {
		name: "minimized-deduped",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.DedupePlugin(),
			new webpack.optimize.UglifyJsPlugin()
		]
	}, {
		name: "optimized",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.DedupePlugin(),
			new webpack.optimize.OccurrenceOrderPlugin(),
			new webpack.optimize.UglifyJsPlugin()
		]
	}, {
		name: "all-combined",
		devtool: "#@source-map",
		excludeNominimize: true,
		plugins: [
			new webpack.HotModuleReplacementPlugin(),
			new webpack.optimize.DedupePlugin(),
			new webpack.optimize.OccurrenceOrderPlugin(),
			new webpack.optimize.UglifyJsPlugin(),
			new webpack.NamedModulesPlugin()
		]
	}].forEach(function(config) {
		describe(config.name, function() {
			categories.forEach(function(category) {
				describe(category.name, function() {
					this.timeout(10000);
					category.tests.filter(function(test) {
						var minimizeCheckOk = !config.excludeNominimize || test.indexOf("nominimize") < 0;
						var harmonyCheckOk = !/^es6/.test(test) || harmony;
						return minimizeCheckOk && harmonyCheckOk;
					}).forEach(function(testName) {
						var suite = describe(testName, function() {});
						it(testName + " should compile", function(done) {
							this.timeout(10000);
							var testDirectory = path.join(casesPath, category.name, testName);
							var outputDirectory = path.join(__dirname, "js", config.name, category.name, testName);
							var options = {
								context: casesPath,
								entry: "./" + category.name + "/" + testName + "/index",
								target: "async-node",
								devtool: config.devtool,
								output: {
									pathinfo: true,
									path: outputDirectory,
									filename: "bundle.js"
								},
								resolve: {
									modules: ["web_modules", "node_modules"],
									mainFields: ["webpack", "browser", "web", "browserify", ["jam", "main"], "main"],
									aliasFields: ["browser"],
									extensions: ["", ".webpack.js", ".web.js", ".js"]
								},
								resolveLoader: {
									modules: ["web_loaders", "web_modules", "node_loaders", "node_modules"],
									mainFields: ["webpackLoader", "webLoader", "loader", "main"],
									extensions: ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"]
								},
								module: {
									loaders: [{
										test: /\.json$/,
										loader: "json-loader"
									}, {
										test: /\.coffee$/,
										loader: "coffee-loader"
									}, {
										test: /\.jade$/,
										loader: "jade-loader"
									}]
								},
								plugins: (config.plugins || []).concat(
									new webpack.dependencies.LabeledModulesPlugin()
								)
							};
							webpack(options, function(err, stats) {
								if(err) return done(err);
								fs.writeFileSync(path.join(outputDirectory, "stats.txt"), stats.toString(), "utf-8");
								var jsonStats = stats.toJson({
									errorDetails: true
								});
								if(checkArrayExpectation(testDirectory, jsonStats, "error", "Error", done)) return;
								if(checkArrayExpectation(testDirectory, jsonStats, "warning", "Warning", done)) return;
								var exportedTest = 0;

								function _it(title, fn) {
									var test = new Test(title, fn);
									suite.addTest(test);
									exportedTest++;
									return test;
								}

								function _require(module) {
									if(module.substr(0, 2) === "./") {
										var p = path.join(outputDirectory, module);
										var fn = vm.runInThisContext("(function(require, module, exports, __dirname, it) {" + fs.readFileSync(p, "utf-8") + "\n})", p);
										var module = {
											exports: {}
										};
										fn.call(module.exports, _require, module, module.exports, outputDirectory, _it);
										return module.exports;
									} else return require(module);
								}
								_require("./bundle.js");
								if(exportedTest === 0) return done(new Error("No tests exported by test case"));
								done();
							});
						});
					});
				});
			});
		});
	});
});
<commit_msg>longer timeout for test cases, appveyor is slow<commit_after>var should = require("should");
var path = require("path");
var fs = require("fs");
var vm = require("vm");
var Test = require("mocha/lib/test");
var checkArrayExpectation = require("./checkArrayExpectation");

var webpack = require("../lib/webpack");

var harmony = (+process.versions.node.split(".")[0]) >= 4;

describe("TestCases", function() {
	var casesPath = path.join(__dirname, "cases");
	var categories = fs.readdirSync(casesPath);
	categories = categories.map(function(cat) {
		return {
			name: cat,
			tests: fs.readdirSync(path.join(casesPath, cat)).filter(function(folder) {
				return folder.indexOf("_") < 0;
			})
		};
	});
	[{
		name: "normal"
	}, {
		name: "hot",
		plugins: [
			new webpack.HotModuleReplacementPlugin()
		]
	}, {
		name: "hot-multi-step",
		plugins: [
			new webpack.HotModuleReplacementPlugin({
				multiStep: true
			})
		]
	}, {
		name: "devtool-eval",
		devtool: "eval"
	}, {
		name: "devtool-eval-named-modules",
		devtool: "eval",
		plugins: [
			new webpack.NamedModulesPlugin()
		]
	}, {
		name: "devtool-eval-source-map",
		devtool: "#eval-source-map"
	}, {
		name: "devtool-inline-source-map",
		devtool: "inline-source-map"
	}, {
		name: "devtool-source-map",
		devtool: "#@source-map"
	}, {
		name: "devtool-cheap-inline-source-map",
		devtool: "cheap-inline-source-map"
	}, {
		name: "devtool-cheap-eval-source-map",
		devtool: "cheap-eval-source-map"
	}, {
		name: "devtool-cheap-eval-module-source-map",
		devtool: "cheap-eval-module-source-map"
	}, {
		name: "devtool-cheap-source-map",
		devtool: "cheap-source-map"
	}, {
		name: "minimized",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.UglifyJsPlugin({
				sourceMap: false
			})
		]
	}, {
		name: "minimized-source-map",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.UglifyJsPlugin()
		]
	}, {
		name: "deduped",
		plugins: [
			new webpack.optimize.DedupePlugin(),
			new webpack.NamedModulesPlugin()
		]
	}, {
		name: "minimized-deduped",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.DedupePlugin(),
			new webpack.optimize.UglifyJsPlugin()
		]
	}, {
		name: "optimized",
		excludeNominimize: true,
		plugins: [
			new webpack.optimize.DedupePlugin(),
			new webpack.optimize.OccurrenceOrderPlugin(),
			new webpack.optimize.UglifyJsPlugin()
		]
	}, {
		name: "all-combined",
		devtool: "#@source-map",
		excludeNominimize: true,
		plugins: [
			new webpack.HotModuleReplacementPlugin(),
			new webpack.optimize.DedupePlugin(),
			new webpack.optimize.OccurrenceOrderPlugin(),
			new webpack.optimize.UglifyJsPlugin(),
			new webpack.NamedModulesPlugin()
		]
	}].forEach(function(config) {
		describe(config.name, function() {
			categories.forEach(function(category) {
				describe(category.name, function() {
					this.timeout(20000);
					category.tests.filter(function(test) {
						var minimizeCheckOk = !config.excludeNominimize || test.indexOf("nominimize") < 0;
						var harmonyCheckOk = !/^es6/.test(test) || harmony;
						return minimizeCheckOk && harmonyCheckOk;
					}).forEach(function(testName) {
						var suite = describe(testName, function() {});
						it(testName + " should compile", function(done) {
							this.timeout(10000);
							var testDirectory = path.join(casesPath, category.name, testName);
							var outputDirectory = path.join(__dirname, "js", config.name, category.name, testName);
							var options = {
								context: casesPath,
								entry: "./" + category.name + "/" + testName + "/index",
								target: "async-node",
								devtool: config.devtool,
								output: {
									pathinfo: true,
									path: outputDirectory,
									filename: "bundle.js"
								},
								resolve: {
									modules: ["web_modules", "node_modules"],
									mainFields: ["webpack", "browser", "web", "browserify", ["jam", "main"], "main"],
									aliasFields: ["browser"],
									extensions: ["", ".webpack.js", ".web.js", ".js"]
								},
								resolveLoader: {
									modules: ["web_loaders", "web_modules", "node_loaders", "node_modules"],
									mainFields: ["webpackLoader", "webLoader", "loader", "main"],
									extensions: ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"]
								},
								module: {
									loaders: [{
										test: /\.json$/,
										loader: "json-loader"
									}, {
										test: /\.coffee$/,
										loader: "coffee-loader"
									}, {
										test: /\.jade$/,
										loader: "jade-loader"
									}]
								},
								plugins: (config.plugins || []).concat(
									new webpack.dependencies.LabeledModulesPlugin()
								)
							};
							webpack(options, function(err, stats) {
								if(err) return done(err);
								fs.writeFileSync(path.join(outputDirectory, "stats.txt"), stats.toString(), "utf-8");
								var jsonStats = stats.toJson({
									errorDetails: true
								});
								if(checkArrayExpectation(testDirectory, jsonStats, "error", "Error", done)) return;
								if(checkArrayExpectation(testDirectory, jsonStats, "warning", "Warning", done)) return;
								var exportedTest = 0;

								function _it(title, fn) {
									var test = new Test(title, fn);
									suite.addTest(test);
									exportedTest++;
									return test;
								}

								function _require(module) {
									if(module.substr(0, 2) === "./") {
										var p = path.join(outputDirectory, module);
										var fn = vm.runInThisContext("(function(require, module, exports, __dirname, it) {" + fs.readFileSync(p, "utf-8") + "\n})", p);
										var module = {
											exports: {}
										};
										fn.call(module.exports, _require, module, module.exports, outputDirectory, _it);
										return module.exports;
									} else return require(module);
								}
								_require("./bundle.js");
								if(exportedTest === 0) return done(new Error("No tests exported by test case"));
								done();
							});
						});
					});
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017, 2018 New Vector Ltd

Licensed 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.
*/

import React from 'react';
import PropTypes from 'prop-types';
import sdk from '../../../index';
import WhoIsTyping from '../../../WhoIsTyping';
import Timer from '../../../utils/Timer';
import MatrixClientPeg from '../../../MatrixClientPeg';
import MemberAvatar from '../avatars/MemberAvatar';

module.exports = React.createClass({
    displayName: 'WhoIsTypingTile',

    propTypes: {
        // the room this statusbar is representing.
        room: PropTypes.object.isRequired,
        onVisible: PropTypes.func,
        // Number of names to display in typing indication. E.g. set to 3, will
        // result in "X, Y, Z and 100 others are typing."
        whoIsTypingLimit: PropTypes.number,
    },

    getDefaultProps: function() {
        return {
            whoIsTypingLimit: 3,
        };
    },

    getInitialState: function() {
        return {
            usersTyping: WhoIsTyping.usersTypingApartFromMe(this.props.room),
            userTimers: {},
        };
    },

    componentWillMount: function() {
        MatrixClientPeg.get().on("RoomMember.typing", this.onRoomMemberTyping);
        MatrixClientPeg.get().on("Room.timeline", this.onRoomTimeline);
    },

    componentDidUpdate: function(_, prevState) {
        if (this.props.onVisible &&
            !prevState.usersTyping.length &&
            this.state.usersTyping.length
        ) {
            this.props.onVisible();
        }
    },

    componentWillUnmount: function() {
        // we may have entirely lost our client as we're logging out before clicking login on the guest bar...
        const client = MatrixClientPeg.get();
        if (client) {
            client.removeListener("RoomMember.typing", this.onRoomMemberTyping);
            client.removeListener("Room.timeline", this.onRoomTimeline);
        }
        Object.values(this.state.userTimers).forEach((t) => t.abort());
    },

    onRoomTimeline: function(event, room) {
        if (room.roomId === this.props.room.roomId) {
            const userId = event.getSender();
            // remove user from usersTyping
            const usersTyping = this.state.usersTyping.filter((m) => m.userId !== userId);
            this.setState({usersTyping});
            this._abortUserTimer(userId);
        }
    },

    onRoomMemberTyping: function(ev, member) {
        const usersTyping = WhoIsTyping.usersTypingApartFromMeAndIgnored(this.props.room);
        this.setState({
            userTimers: this._updateUserTimers(usersTyping),
            usersTyping,
        });
    },

    _updateUserTimers(usersTyping) {
        const usersThatStoppedTyping = this.state.usersTyping.filter((a) => {
            return !usersTyping.some((b) => a.userId === b.userId);
        });
        const usersThatStartedTyping = usersTyping.filter((a) => {
            return !this.state.usersTyping.some((b) => a.userId === b.userId);
        });
        // abort all the timers for the users that started typing again
        usersThatStartedTyping.forEach((m) => {
            const timer = this.state.userTimers[m.userId];
            timer && timer.abort();
        });
        // prepare new userTimers object to update state with
        let userTimers = Object.assign({}, this.state.userTimers);
        // remove members that started typing again
        userTimers = usersThatStartedTyping.reduce((userTimers, m) => {
            delete userTimers[m.userId];
            return userTimers;
        }, userTimers);
        // start timer for members that stopped typing
        userTimers = usersThatStoppedTyping.reduce((userTimers, m) => {
            if (!userTimers[m.userId]) {
                const timer = new Timer(5000);
                userTimers[m.userId] = timer;
                timer.start();
                timer.finished().then(
                    () => this._removeUserTimer(m.userId),  //on elapsed
                    () => {/* aborted */},
                );
            }
            return userTimers;
        }, userTimers);

        return userTimers;
    },

    _abortUserTimer: function(userId) {
        const timer = this.state.userTimers[userId];
        if (timer) {
            timer.abort();
            this._removeUserTimer(userId);
        }
    },

    _removeUserTimer: function(userId) {
        const timer = this.state.userTimers[userId];
        if (timer) {
            const userTimers = Object.assign({}, this.state.userTimers);
            delete userTimers[userId];
            this.setState({userTimers});
        }
    },

    _renderTypingIndicatorAvatars: function(users, limit) {
        let othersCount = 0;
        if (users.length > limit) {
            othersCount = users.length - limit + 1;
            users = users.slice(0, limit - 1);
        }

        const avatars = users.map((u) => {
            return (
                <MemberAvatar
                    key={u.userId}
                    member={u}
                    width={24}
                    height={24}
                    resizeMethod="crop"
                />
            );
        });

        if (othersCount > 0) {
            avatars.push(

                    +{ othersCount }
                ,
            );
        }

        return avatars;
    },

    render: function() {
        let usersTyping = this.state.usersTyping;
        const stoppedUsersOnTimer = Object.keys(this.state.userTimers)
            .map((userId) => this.props.room.getMember(userId));
        usersTyping = usersTyping.concat(stoppedUsersOnTimer);

        const typingString = WhoIsTyping.whoIsTypingString(
            usersTyping,
            this.props.whoIsTypingLimit,
        );
        if (!typingString) {
            return (
);
        }

        const EmojiText = sdk.getComponent('elements.EmojiText');

        return (

                    { this._renderTypingIndicatorAvatars(usersTyping, this.props.whoIsTypingLimit) }

                    <EmojiText>{ typingString }</EmojiText>

        );
    },
});
<commit_msg>add comments<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017, 2018 New Vector Ltd

Licensed 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.
*/

import React from 'react';
import PropTypes from 'prop-types';
import sdk from '../../../index';
import WhoIsTyping from '../../../WhoIsTyping';
import Timer from '../../../utils/Timer';
import MatrixClientPeg from '../../../MatrixClientPeg';
import MemberAvatar from '../avatars/MemberAvatar';

module.exports = React.createClass({
    displayName: 'WhoIsTypingTile',

    propTypes: {
        // the room this statusbar is representing.
        room: PropTypes.object.isRequired,
        onVisible: PropTypes.func,
        // Number of names to display in typing indication. E.g. set to 3, will
        // result in "X, Y, Z and 100 others are typing."
        whoIsTypingLimit: PropTypes.number,
    },

    getDefaultProps: function() {
        return {
            whoIsTypingLimit: 3,
        };
    },

    getInitialState: function() {
        return {
            usersTyping: WhoIsTyping.usersTypingApartFromMe(this.props.room),
            userTimers: {},
            // a map with userid => Timer to delay
            // hiding the "x is typing" message for a
            // user so hiding it can coincide
            // with the sent message by the other side
            // resulting in less timeline jumpiness
        };
    },

    componentWillMount: function() {
        MatrixClientPeg.get().on("RoomMember.typing", this.onRoomMemberTyping);
        MatrixClientPeg.get().on("Room.timeline", this.onRoomTimeline);
    },

    componentDidUpdate: function(_, prevState) {
        if (this.props.onVisible &&
            !prevState.usersTyping.length &&
            this.state.usersTyping.length
        ) {
            this.props.onVisible();
        }
    },

    componentWillUnmount: function() {
        // we may have entirely lost our client as we're logging out before clicking login on the guest bar...
        const client = MatrixClientPeg.get();
        if (client) {
            client.removeListener("RoomMember.typing", this.onRoomMemberTyping);
            client.removeListener("Room.timeline", this.onRoomTimeline);
        }
        Object.values(this.state.userTimers).forEach((t) => t.abort());
    },

    onRoomTimeline: function(event, room) {
        if (room.roomId === this.props.room.roomId) {
            const userId = event.getSender();
            // remove user from usersTyping
            const usersTyping = this.state.usersTyping.filter((m) => m.userId !== userId);
            this.setState({usersTyping});
            // abort timer if any
            this._abortUserTimer(userId);
        }
    },

    onRoomMemberTyping: function(ev, member) {
        const usersTyping = WhoIsTyping.usersTypingApartFromMeAndIgnored(this.props.room);
        this.setState({
            userTimers: this._updateUserTimers(usersTyping),
            usersTyping,
        });
    },

    _updateUserTimers(usersTyping) {
        const usersThatStoppedTyping = this.state.usersTyping.filter((a) => {
            return !usersTyping.some((b) => a.userId === b.userId);
        });
        const usersThatStartedTyping = usersTyping.filter((a) => {
            return !this.state.usersTyping.some((b) => a.userId === b.userId);
        });
        // abort all the timers for the users that started typing again
        usersThatStartedTyping.forEach((m) => {
            const timer = this.state.userTimers[m.userId];
            timer && timer.abort();
        });
        // prepare new userTimers object to update state with
        let userTimers = Object.assign({}, this.state.userTimers);
        // remove members that started typing again
        userTimers = usersThatStartedTyping.reduce((userTimers, m) => {
            delete userTimers[m.userId];
            return userTimers;
        }, userTimers);
        // start timer for members that stopped typing
        userTimers = usersThatStoppedTyping.reduce((userTimers, m) => {
            if (!userTimers[m.userId]) {
                const timer = new Timer(5000);
                userTimers[m.userId] = timer;
                timer.start();
                timer.finished().then(
                    () => this._removeUserTimer(m.userId),  //on elapsed
                    () => {/* aborted */},
                );
            }
            return userTimers;
        }, userTimers);

        return userTimers;
    },

    _abortUserTimer: function(userId) {
        const timer = this.state.userTimers[userId];
        if (timer) {
            timer.abort();
            this._removeUserTimer(userId);
        }
    },

    _removeUserTimer: function(userId) {
        const timer = this.state.userTimers[userId];
        if (timer) {
            const userTimers = Object.assign({}, this.state.userTimers);
            delete userTimers[userId];
            this.setState({userTimers});
        }
    },

    _renderTypingIndicatorAvatars: function(users, limit) {
        let othersCount = 0;
        if (users.length > limit) {
            othersCount = users.length - limit + 1;
            users = users.slice(0, limit - 1);
        }

        const avatars = users.map((u) => {
            return (
                <MemberAvatar
                    key={u.userId}
                    member={u}
                    width={24}
                    height={24}
                    resizeMethod="crop"
                />
            );
        });

        if (othersCount > 0) {
            avatars.push(

                    +{ othersCount }
                ,
            );
        }

        return avatars;
    },

    render: function() {
        let usersTyping = this.state.usersTyping;
        const stoppedUsersOnTimer = Object.keys(this.state.userTimers)
            .map((userId) => this.props.room.getMember(userId));
        // append the users that have been reported not typing anymore
        // but have a timeout timer running so they can disappear
        // when a message comes in
        usersTyping = usersTyping.concat(stoppedUsersOnTimer);

        const typingString = WhoIsTyping.whoIsTypingString(
            usersTyping,
            this.props.whoIsTypingLimit,
        );
        if (!typingString) {
            return (
);
        }

        const EmojiText = sdk.getComponent('elements.EmojiText');

        return (

                    { this._renderTypingIndicatorAvatars(usersTyping, this.props.whoIsTypingLimit) }

                    <EmojiText>{ typingString }</EmojiText>

        );
    },
});
<|endoftext|>


<commit_before>"enable aexpr";

import Morph from 'src/components/widgets/lively-morph.js';

export default class LivelyTabsWrapper extends Morph {
  async initialize() {
    this.windowTitle = "LivelyTabsWrapper";
    this.registerButtons()

    lively.html.registerKeys(this); // automatically installs handler for some methods

    lively.addEventListener("template", this, "dblclick",
      evt => this.onDblClick(evt))
    // #Note 1
    // ``lively.addEventListener`` automatically registers the listener
    // so that the the handler can be deactivated using:
    // ``lively.removeEventListener("template", this)``
    // #Note 1
    // registering a closure instead of the function allows the class to make
    // use of a dispatch at runtime. That means the ``onDblClick`` method can be
    // replaced during development

    //this.get("#textField").value = this.getAttribute("data-mydata") || 0;

    this.containedWindows = [];

    this.content = "";

  }

  addWindow(window) {

    var windowObject = {

      "window": window,
      "id": "tab-bar-element-" + this.containedWindows.length + 1,
      "title": window.title()

    }

    lively.notify(windowObject.title + ", " + windowObject.id);
    this.containedWindows.push(window);
  }

  addTab(windowObject) {

    var newTabHtml = ( {windowObject.title} );

    var currentTabBar = this.get("#tab-bar-identifier");
    currentTabBar.innerHTML = currentTabBar.innerHTML + newTabHtml.outerHTML;

    // #TODO Make it working
    lively.addEventListener("TabEventListener", newTabHtml, "click", () => {
      this.switchToContentOfTab(windowObject.id);
    });
  }

  switchToContentOfTab(tabId) {

    for (var i = 0; i < this.containedWindows.length; i++) {
      if (this.containedWindows[i].id === tabId) {
        this.switchToContentOfWindow(this.containedWindows[i]);
      }
    }
    lively.notify("Tab Id was not found.")

  }

  switchToContentOfWindow(windowObj) {
    if (windowObj.window) {
      this.appendChild(windowObj.window.window());
    } else {
      this.appendChild("Could not read content of Window " + windowObj.title);
    }
  }

  onDblClick() {
    this.animate([
      {backgroundColor: "lightgray"},
      {backgroundColor: "red"},
      {backgroundColor: "lightgray"},
    ], {
      duration: 1000
    })
  }

  // this method is autmatically registered through the ``registerKeys`` method
  onKeyDown(evt) {
    lively.notify("Key Down!" + evt.charCode)
  }

  // this method is automatically registered as handler through ``registerButtons``
  onPlusButton() {
    this.get("#textField").value =  parseFloat(this.get("#textField").value) + 1
  }

  onMinusButton() {
    this.get("#textField").value =  parseFloat(this.get("#textField").value) - 1
  }

  /* Lively-specific API */

  // store something that would be lost
  livelyPrepareSave() {
    this.setAttribute("data-mydata", this.get("#textField").value)
  }

  livelyPreMigrate() {
    // is called on the old object before the migration
  }

  livelyMigrate(other) {
    // whenever a component is replaced with a newer version during development
    // this method is called on the new object during migration, but before initialization
    this.someJavaScriptProperty = other.someJavaScriptProperty
  }

/*
  livelyInspect(contentNode, inspector) {
    // overrides how the inspector displays this component
  }
*/

  async livelyExample() {
    // For content in the window:
    // this.appendChild(
This is example content
);

    var winObj1 = {
      "window": null,
      "id": "tab-bar-element-1",
      "title": "My Tab Bar 1"
    }

    var winObj2 = {
      "window": null,
      "id": "tab-bar-element-2",
      "title": "My Tab Bar 2"
    }

    this.addTab(winObj1);
    this.addTab(winObj2);

  }

}<commit_msg>Meeting Sync<commit_after>"enable aexpr";

import Morph from 'src/components/widgets/lively-morph.js';

export default class LivelyTabsWrapper extends Morph {
  async initialize() {
    this.windowTitle = "LivelyTabsWrapper";
    this.registerButtons()

    lively.html.registerKeys(this); // automatically installs handler for some methods

    lively.addEventListener("template", this, "dblclick",
      evt => this.onDblClick(evt));
    // #Note 1
    // ``lively.addEventListener`` automatically registers the listener
    // so that the the handler can be deactivated using:
    // ``lively.removeEventListener("template", this)``
    // #Note 1
    // registering a closure instead of the function allows the class to make
    // use of a dispatch at runtime. That means the ``onDblClick`` method can be
    // replaced during development

    //this.get("#textField").value = this.getAttribute("data-mydata") || 0;

    if (!this.containedWindows) {
       this.containedWindows = [];
    }

    this.content = "";

  }

  addWindow(window) {

    var windowObject = {

      "window": window,
      "id": "tab-bar-element-" + this.containedWindows.length + 1,
      "title": window.title()

    }

    lively.notify(windowObject.title + ", " + windowObject.id);
    this.containedWindows.push(window);
  }

  addTab(windowObject) {

    var newTab = (
 {
          lively.notify("Worked!")
        }} id={windowObject.id}> {windowObject.title}
);

    var currentTabBar = this.get("#tab-bar-identifier");
    currentTabBar.appendChild(newTab);

    //currentTabBar.innerHTML + newTabHtml.outerHTML;

    // #TODO Make it working
    /*
    lively.addEventListener("TabEventListener", newTabHtml, "click", () => {
      this.switchToContentOfTab(windowObject.id);
    });*/

  }

  switchToContentOfTab(tabId) {

    for (var i = 0; i < this.containedWindows.length; i++) {
      if (this.containedWindows[i].id === tabId) {
        this.switchToContentOfWindow(this.containedWindows[i]);
      }
    }
    lively.notify("Tab Id was not found.")

  }

  switchToContentOfWindow(windowObj) {
    if (windowObj.window) {
      this.appendChild(windowObj.window.window());
    } else {
      this.appendChild("Could not read content of Window " + windowObj.title);
    }
  }

  onDblClick() {
    this.animate([
      {backgroundColor: "lightgray"},
      {backgroundColor: "red"},
      {backgroundColor: "lightgray"},
    ], {
      duration: 1000
    })
  }

  // this method is autmatically registered through the ``registerKeys`` method
  onKeyDown(evt) {
    lively.notify("Key Down!" + evt.charCode)
  }

  // this method is automatically registered a    for (var ea of other.containedWindows) {
  onPlusButton() {
    this.get("#textField").value =  parseFloat(this.get("#textField").value) + 1
  }

  onMinusButton() {
    this.get("#textField").value =  parseFloat(this.get("#textField").value) - 1
  }

  /* Lively-specific API */

  // store something that would be lost
  livelyPrepareSave() {
    this.setAttribute("data-mydata", this.get("#textField").value)
  }

  livelyPreMigrate() {
    // is called on the old object before the migration
  }

/*
  livelyInspect(contentNode, inspector) {
    // overrides how the inspector displays this component
  }
*/

  async livelyExample() {
    // For content in the window:
    // this.appendChild(
This is example content
);

    var winObj1 = {
      "window": null,
      "id": "tab-bar-element-1",
      "title": "My Tab Bar 1"
    }

    var winObj2 = {
      "window": null,
      "id": "tab-bar-element-2",
      "title": "My Tab Bar 2"
    }

    this.addTab(winObj1);
    this.addTab(winObj2);

  }

  livelyMigrate(other)  {

    this.containedWindows = other.containedWindows;

  }

}<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import { Table, DatasetModal, Modal } from 'components';
import Notification from 'components/Notification';

import AdminContainer from 'containers/shared/AdminContainer';

class DatasetsPage extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedRow: null,
      deleteWarning: false,
      deleteSuccess: false,
      deleteError: false
    };
  }

  onClickAction(action, row) {
    if (action === 'delete') {
      this.setState({ deleteWarning: true, selectedRow: row });
    } else if (action == 'toggle') {
      fetch(window.location.origin + row.enable.value, {
        method: 'PUT',
        credentials: 'same-origin'
      }).then(() => {
        window.location.reload();
      });
    } else {
      window.location = row.edit.value;
    }
  }

  onClickDelete() {
    const { selectedRow } = this.state;
    fetch(selectedRow.delete.value, {
      method: 'DELETE',
      credentials: 'include'
    }).then(() => {
      window.location.reload();
    }).catch(() => {
      this.setState({
        deleteSuccess: false,
        deleteError: true,
        deleteWarning: false
      });
    });
  }

  render() {
    const { datasets } = this.props;
    const { deleteWarning, deleteSuccess, deleteError, selectedRow } = this.state;

    const rows = datasets.map(dataset => ({
      ...dataset,
      created: { value: (new Date(dataset.created.value)).toLocaleString(), sortable: true },
      edited: { value: (new Date(dataset.edited.value)).toLocaleString(), sortable: true }
    }));

    return (

        {deleteWarning && (
          <Modal
            show={deleteWarning}
            onClose={() => this.setState({ deleteWarning: false })}
          >

Are you sure you want to delete this dataset?

              {selectedRow.widgets.value && (

                    The deletion {'can\'t'} be reversed and the following widgets will be
                    permanently deleted:

                    {selectedRow.widgets.value.map(widget =>
{widget}
)}

              )}

              <button type="button" className="c-button -outline -dark-text" onClick={() => this.setState({ deleteWarning: false })}>
                Cancel
              </button>
              <button type="button" className="c-button" onClick={() => this.onClickDelete()}>
                Remove
              </button>

          </Modal>
        )}

        {deleteSuccess && (
          <Notification
            type="info"
            content="The dataset has been successfully deleted."
            onClose={() => this.setState({ deleteSuccess: false })}
          />
        )}

        {deleteError && (
          <Notification
            type="error"
            content="The dataset couldn't be deleted."
            onClose={() => this.setState({ deleteError: false })}
          />
        )}

        <AdminContainer>

 this.onClickAction(...params)}
              />

        </AdminContainer>

    );
  }
}

DatasetsPage.propTypes = {
  datasets: PropTypes.array
};

DatasetsPage.defaultProps = {
  datasets: []
};

export default DatasetsPage;
<commit_msg>Remove widgets list message when there are no widgets<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import { Table, DatasetModal, Modal } from 'components';
import Notification from 'components/Notification';

import AdminContainer from 'containers/shared/AdminContainer';

class DatasetsPage extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedRow: null,
      deleteWarning: false,
      deleteSuccess: false,
      deleteError: false
    };
  }

  onClickAction(action, row) {
    if (action === 'delete') {
      this.setState({ deleteWarning: true, selectedRow: row });
    } else if (action == 'toggle') {
      fetch(window.location.origin + row.enable.value, {
        method: 'PUT',
        credentials: 'same-origin'
      }).then(() => {
        window.location.reload();
      });
    } else {
      window.location = row.edit.value;
    }
  }

  onClickDelete() {
    const { selectedRow } = this.state;
    fetch(selectedRow.delete.value, {
      method: 'DELETE',
      credentials: 'include'
    }).then(() => {
      window.location.reload();
    }).catch(() => {
      this.setState({
        deleteSuccess: false,
        deleteError: true,
        deleteWarning: false
      });
    });
  }

  render() {
    const { datasets } = this.props;
    const { deleteWarning, deleteSuccess, deleteError, selectedRow } = this.state;

    const rows = datasets.map(dataset => ({
      ...dataset,
      created: { value: (new Date(dataset.created.value)).toLocaleString(), sortable: true },
      edited: { value: (new Date(dataset.edited.value)).toLocaleString(), sortable: true }
    }));

    return (

        {deleteWarning && (
          <Modal
            show={deleteWarning}
            onClose={() => this.setState({ deleteWarning: false })}
          >

Are you sure you want to delete this dataset?

              {selectedRow.widgets.value.length !== 0 && (

                    The deletion {'can\'t'} be reversed and the following widgets will be
                    permanently deleted:

                    {selectedRow.widgets.value.map(widget =>
{widget}
)}

              )}

              <button type="button" className="c-button -outline -dark-text" onClick={() => this.setState({ deleteWarning: false })}>
                Cancel
              </button>
              <button type="button" className="c-button" onClick={() => this.onClickDelete()}>
                Remove
              </button>

          </Modal>
        )}

        {deleteSuccess && (
          <Notification
            type="info"
            content="The dataset has been successfully deleted."
            onClose={() => this.setState({ deleteSuccess: false })}
          />
        )}

        {deleteError && (
          <Notification
            type="error"
            content="The dataset couldn't be deleted."
            onClose={() => this.setState({ deleteError: false })}
          />
        )}

        <AdminContainer>

 this.onClickAction(...params)}
              />

        </AdminContainer>

    );
  }
}

DatasetsPage.propTypes = {
  datasets: PropTypes.array
};

DatasetsPage.defaultProps = {
  datasets: []
};

export default DatasetsPage;
<|endoftext|>


<commit_before>"use strict";

var co = require('co');

module.exports = ($scope, $state, BMA, summary, UIUtils) => {

  Waves.displayEffect();

  var isMobile = require('js/lib/mobileDetector');
  if (isMobile()) {
    $(".button-collapse").sideNav({
      menuWidth: 280
    });
  }

  UIUtils.changeTitle(summary.version);

  $scope.openWallet = () => {

    let walletHeight = parseInt(localStorage.getItem('wallet_height')) || 1000;
    let walletWidth = parseInt(localStorage.getItem('wallet_width')) || 1400;

    gui.Window.open (window.location.origin + '/cesium/index.html', {
      position: 'center',
      height: walletHeight,
      width: walletWidth
    }, function(win) {
      win.on('closed', function() {
        localStorage.setItem('wallet_height', win.window.innerHeight - 8); // Seems to always have 8 pixels more
        localStorage.setItem('wallet_width', win.window.innerWidth - 16); // Seems to always have 16 pixels more
      });
    });
  };

  let aboutWin;

  $scope.showAbout = () => {
    if (aboutWin) {
      aboutWin.focus();
    } else {
      gui.Window.open(window.location.origin + '/#/about', {
        position: 'center',
        height: 380,
        width: 500
      }, function(subwin) {
        subwin.window.duniter = window.duniter;
        subwin.window.gui = window.gui;
        subwin.on('closed', () => {
          aboutWin = null;
        });
        aboutWin = subwin;
      });
    }
  };

  $scope.startServer = () => {
    $scope.server_stopped = false;
    return co(function *() {
      yield BMA.webmin.server.http.start();
      yield BMA.webmin.server.services.startAll();
      yield BMA.webmin.server.http.regularUPnP();
      $scope.server_started = true;
    });
  };

  $scope.stopServer = () => {
    $scope.server_started = false;
    return co(function *() {
      yield BMA.webmin.server.http.stop();
      yield BMA.webmin.server.services.stopAll();
      $scope.server_stopped = true;
    });
  };

  $scope.restartServer = () => {
    return co(function *() {
      yield $scope.stopServer();
      yield $scope.startServer();
    });
  };
};
<commit_msg>Autofocus main window on Wallet or About windows closed<commit_after>"use strict";

var co = require('co');

module.exports = ($scope, $state, BMA, summary, UIUtils) => {

  Waves.displayEffect();

  var isMobile = require('js/lib/mobileDetector');
  if (isMobile()) {
    $(".button-collapse").sideNav({
      menuWidth: 280
    });
  }

  UIUtils.changeTitle(summary.version);

  $scope.openWallet = () => {

    let walletHeight = parseInt(localStorage.getItem('wallet_height')) || 1000;
    let walletWidth = parseInt(localStorage.getItem('wallet_width')) || 1400;

    gui.Window.open (window.location.origin + '/cesium/index.html', {
      position: 'center',
      height: walletHeight,
      width: walletWidth
    }, function(win) {
      win.on('closed', function() {
        localStorage.setItem('wallet_height', win.window.innerHeight - 8); // Seems to always have 8 pixels more
        localStorage.setItem('wallet_width', win.window.innerWidth - 16); // Seems to always have 16 pixels more
        mainWindow.focus();
      });
    });
  };

  let aboutWin;

  $scope.showAbout = () => {
    if (aboutWin) {
      aboutWin.focus();
    } else {
      gui.Window.open(window.location.origin + '/#/about', {
        position: 'center',
        height: 380,
        width: 500
      }, function(subwin) {
        subwin.window.duniter = window.duniter;
        subwin.window.gui = window.gui;
        subwin.on('closed', () => {
          aboutWin = null;
          mainWindow.focus();
        });
        aboutWin = subwin;
      });
    }
  };

  $scope.startServer = () => {
    $scope.server_stopped = false;
    return co(function *() {
      yield BMA.webmin.server.http.start();
      yield BMA.webmin.server.services.startAll();
      yield BMA.webmin.server.http.regularUPnP();
      $scope.server_started = true;
    });
  };

  $scope.stopServer = () => {
    $scope.server_started = false;
    return co(function *() {
      yield BMA.webmin.server.http.stop();
      yield BMA.webmin.server.services.stopAll();
      $scope.server_stopped = true;
    });
  };

  $scope.restartServer = () => {
    return co(function *() {
      yield $scope.stopServer();
      yield $scope.startServer();
    });
  };
};
<|endoftext|>


<commit_before>import pushinvoices from '../push/subscribeinvoice'

/**
 * Attempts to add a new invoice to the invoice database.
 * @param  lnd   [description]
 * @param  memo  [description]
 * @param  value [description]
 * @return     [description]
 */
export function addInvoice(lnd, { memo, value, private: privateInvoice }) {
  return new Promise((resolve, reject) => {
    lnd.addInvoice({ memo, value, private: privateInvoice, expiry: 600 }, (err, data) => {
      if (err) {
        return reject(err)
      }

      resolve(data)
    })
  })
}

/**
 * Returns a list of all the invoices currently stored within the database
 * @param  {[type]} lnd [description]
 * @return {[type]}     [description]
 */
export function listInvoices(lnd) {
  return new Promise((resolve, reject) => {
    lnd.listInvoices({}, (err, data) => {
      if (err) {
        return reject(err)
      }

      resolve(data)
    })
  })
}

/**
 * @param  {[type]} payreq [description]
 * @return {[type]}        [description]
 */
export function getInvoice(lnd, { pay_req }) {
  return new Promise((resolve, reject) => {
    lnd.decodePayReq({ pay_req }, (err, data) => {
      if (err) {
        return reject(err)
      }

      resolve(data)
    })
  })
}

/**
 * Attemps to look up an invoice according to its payment hash
 * @param  {[type]} lnd   [description]
 * @param  {[type]} rhash [description]
 * @return {[type]}       [description]
 */
export function lookupInvoice(lnd, { rhash }) {
  return new Promise((resolve, reject) => {
    lnd.lookupInvoice({ r_hash: rhash }, (err, data) => {
      if (err) {
        return reject(err)
      }

      resolve(data)
    })
  })
}

/**
 * Returns a uni-directional stream (server -> client) for notifying the client of newly added/settled invoices
 * @param  {[type]} lnd   [description]
 * @param  {[type]} event [description]
 * @return {[type]}       [description]
 */
export function subscribeInvoices(lnd, event) {
  return pushinvoices(lnd, event)
}
<commit_msg>fix(wallet): increase invoice fetch count to 1000<commit_after>import pushinvoices from '../push/subscribeinvoice'

/**
 * Attempts to add a new invoice to the invoice database.
 * @param  lnd   [description]
 * @param  memo  [description]
 * @param  value [description]
 * @return     [description]
 */
export function addInvoice(lnd, { memo, value, private: privateInvoice }) {
  return new Promise((resolve, reject) => {
    lnd.addInvoice({ memo, value, private: privateInvoice, expiry: 600 }, (err, data) => {
      if (err) {
        return reject(err)
      }

      resolve(data)
    })
  })
}

/**
 * Returns a list of all the invoices currently stored within the database
 * @param  {[type]} lnd [description]
 * @return {[type]}     [description]
 */
export function listInvoices(lnd) {
  return new Promise((resolve, reject) => {
    lnd.listInvoices({ num_max_invoices: 1000 }, (err, data) => {
      if (err) {
        return reject(err)
      }

      resolve(data)
    })
  })
}

/**
 * @param  {[type]} payreq [description]
 * @return {[type]}        [description]
 */
export function getInvoice(lnd, { pay_req }) {
  return new Promise((resolve, reject) => {
    lnd.decodePayReq({ pay_req }, (err, data) => {
      if (err) {
        return reject(err)
      }

      resolve(data)
    })
  })
}

/**
 * Attemps to look up an invoice according to its payment hash
 * @param  {[type]} lnd   [description]
 * @param  {[type]} rhash [description]
 * @return {[type]}       [description]
 */
export function lookupInvoice(lnd, { rhash }) {
  return new Promise((resolve, reject) => {
    lnd.lookupInvoice({ r_hash: rhash }, (err, data) => {
      if (err) {
        return reject(err)
      }

      resolve(data)
    })
  })
}

/**
 * Returns a uni-directional stream (server -> client) for notifying the client of newly added/settled invoices
 * @param  {[type]} lnd   [description]
 * @param  {[type]} event [description]
 * @return {[type]}       [description]
 */
export function subscribeInvoices(lnd, event) {
  return pushinvoices(lnd, event)
}
<|endoftext|>