<commit_before>import Ember from 'ember';
import { module, test } from 'qunit';
import { default as _sinon } from 'sinon';
import Initializer from 'ember-blog/initializers/ember-blog-initializer';
import InstanceInitializer from 'ember-blog/instance-initializers/ember-blog-instance-initializer';
import { setupApplicationTest } from 'ember-qunit';
import { currentURL, visit, find, click } from '@ember/test-helpers';

let originalExceptionHandler;
let sinon;

module('Acceptance | routeless engine demo', function (hooks) {
  setupApplicationTest(hooks);

  hooks.beforeEach(function () {
    originalExceptionHandler = Ember.Test.adapter.exception;
    sinon = _sinon.createSandbox();
  });

  hooks.afterEach(function () {
    sinon.restore();
    Ember.Test.adapter.exception = originalExceptionHandler;
  });

  test('can invoke components', async function (assert) {
    await visit('/routable-engine-demo/blog/new');

    assert.equal(currentURL(), '/routable-engine-demo/blog/new');

    assert.equal(
        find('.routable-hello-world')
        .textContent
        .trim(),
      'Hello, world!'
    );
    assert.equal(
        find('.hello-name')
        .textContent
        .trim(),
      'Hello, Jerry!',
      'Re-rendered hello-name component correctly'
    );
  });

  test("can deserialize a route's params", async function (assert) {
    assert.expect(3);

    await visit('/routable-engine-demo/blog/post/1');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1');

    assert.equal(
      find('h3.post-title')
        .textContent
        .trim(),
      'Post 1'
    );
    assert.equal(
      find('p.author')
        .textContent
        .trim(),
      'Derek Zoolander'
    );
  });

  test('can link-to application route of Engine', async function (assert) {
    await visit('/routable-engine-demo/blog/post/new');
    await click('.routable-post-blog-home-link-app');

    assert.equal(currentURL(), '/routable-engine-demo/blog');
  });

  test('correctly handles navigation with query param in initial url', async function (
    assert
  ) {
    assert.expect(9);

    await visit('/routable-engine-demo/blog/post/1?lang=English');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=English',
      'url is visited properly'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'English',
      'query param value is passed through correctly - 1'
    );

    await click('.routable-post-comments-link');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1/comments?lang=English',
      'query param is carried to sub-route'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'English',
      'query param value is passed through correctly - 2'
    );

    await click('.back-to-post-link');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=English',
      'query param is carried back to original route properly'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'English',
      'query param value is passed through correctly - 3'
    );

    await click('.routable-post-blog-home-link');
    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog',
      'query param is removed when changing route hierarchy'
    );

    await click('.routable-post-1-link');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=English',
      'query param is rehydrated in url'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'English',
      'query param value is passed through correctly - 4'
    );
  });

  test('can link-to a route with query params from outside an Engine', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo');
    await click('.blog-post-1-link-jp');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=Japanese'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'Japanese'
    );
  });

  test('can programmatically transition to a route with query params from outside an Engine', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo');
    await click('.blog-post-1-link-ch');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=Chinese'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'Chinese'
    );
  });

  test('can link-to a route with query params within an Engine', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog');
    await click('.routable-post-1-link-jp');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=Japanese'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'Japanese'
    );
  });

  test('can programmatically transition to a route with query params within an Engine', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog');
    await click('.routable-post-1-link-ch');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=Chinese'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'Chinese'
    );
  });

  test('can perform a QP-only link-to transition', async function (assert) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog/post/1?lang=English');
    await click('.routable-post-jp-link');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=Japanese',
      'URL is updated properly'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'Japanese',
      'DOM is updated properly'
    );
  });

  test('can perform a QP-only transitionTo', async function (assert) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog/post/1?lang=English');
    await click('.routable-post-ch-link');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=Chinese',
      'URL is updated properly'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'Chinese',
      'DOM is updated properly'
    );
  });

  test('can perform a redirect transition with QP', async function (assert) {
    assert.expect(1);

    await visit('/routable-engine-demo/redirect');
    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=English'
    );
  });

  test('can perform an afterModel transition with QP', async function (assert) {
    assert.expect(1);

    await visit('/routable-engine-demo/after-model/3');
    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/3?lang=English'
    );
  });

  test('query param bucket cache does not collide when starting outside Engine', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/post/1?lang=English');
    await click('.blog-post-no-qp');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1',
      'URL does not have any query params'
    );

    await click('.non-blog-post');
    assert.equal(
      currentURL(),
      '/post/1?lang=English',
      'URL has original query params'
    );
  });

  test('query param bucket cache does not collide when starting inside Engine', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog/post/1?lang=English');
    await click('.non-blog-post');

    assert.equal(currentURL(), '/post/1', 'URL does not have any query params');

    await click('.blog-post-no-qp');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=English',
      'URL has original query params'
    );
  });

  test("a route can lookup another route's model", async function (assert) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog/post/1/comments');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1/comments');

    assert.equal(
      find('h4.comments')
        .textContent
        .trim(),
      'Comments for Post 1'
    );
  });

  test('can render a link', async function (assert) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog/post/1');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1');

    let contentLink = find('a.routable-post-comments-link').href;

    assert.ok(
      contentLink.includes('/routable-engine-demo/blog/post/1/comments')
    );
  });

  test('link-to current-when attribute prepends engine mount point', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/eager-blog/post/1');

    assert.equal(currentURL(), '/routable-engine-demo/eager-blog/post/1');
    assert.ok(
      find('a.current-when-test-link').classList.contains('active')
    );
  });

  test('internal links can be clicked', async function (assert) {
    assert.expect(1);

    await visit('/routable-engine-demo/blog/post/1');
    await click('.routable-post-home-link');

    assert.equal(currentURL(), '/');
  });

  test('external links can be clicked', async function (assert) {
    assert.expect(1);

    await visit('/routable-engine-demo/blog/post/1');
    await click('.routable-post-comments-link');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1/comments');
  });

  test('a route can use transitionTo to transition to internal route', async function (
    assert
  ) {
    assert.expect(1);

    await visit('/routable-engine-demo/blog/new');
    await click('.trigger-transition-to');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1');
  });

  test('internal links can be clicked', async function (assert) {
    assert.expect(1);

    await visit('/routable-engine-demo/special-admin-blog-here/post/1');
    await click('.routable-post-comments-link');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/special-admin-blog-here/post/1/comments'
    );
  });

  test('transitionTo works properly within parent application', async function (assert) {
    assert.expect(1);

    await visit('/routable-engine-demo/normal-route');

    assert.equal(currentURL(), '/routeless-engine-demo');
  });

  test('transitionToExternal transitions to the parent application from within an engine and returns a thenable Transition object', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/ember-blog/post/1');
    await click('.routable-post-transition-to-home-button');

    assert.equal(currentURL(), '/');

    await click('.routeable-engine');
    await click('.ember-blog-new');
    await click('.trigger-transition-to');

    assert.ok(
      find('.routable-post-transition-to-home-button').classList.contains('transitioned-to-external')
    );
  });

  test('transitionToExternalRoute transitions to the parent application from within an engine and returns a thenable Transition object', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/ember-blog/post/1');
    await click('.routable-post-transition-to-route-home-button');

    assert.equal(currentURL(), '/');

    await click('.routeable-engine');
    await click('.ember-blog-new');
    await click('.trigger-transition-to');

    assert.ok(
      find('.routable-post-transition-to-route-home-button').classList.contains('transitioned-to-route-external')
    );
  });

  test('replaceWithExternal transitions to the parent application from within an engine and returns a thenable Transition object', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/ember-blog/post/1');
    await click('.routable-post-replace-with-home-button');

    assert.equal(currentURL(), '/');

    await click('.routeable-engine');
    await click('.ember-blog-new');
    await click('.trigger-transition-to');

    assert.ok(
      find('.routable-post-replace-with-home-button').classList.contains('replaced-with-external')
    );
  });

  test('loading routes and intermediateTransitionTo work within an engine', async function (
    assert
  ) {
    assert.expect(2);

    this.owner.lookup('router:main').reopen({
      intermediateTransitionTo(routeName) {
        assert.equal(routeName, 'blog.post.loading');
        this._super(...arguments);
      },
    });

    await visit('/routable-engine-demo/blog/post/1/comments');
    await click('.routable-post-likes-link');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1/likes');
  });

  test('error routes and intermediateTransitionTo work within an engine', async function (
    assert
  ) {
    assert.expect(3);

    Ember.Test.adapter.exception = () => { };

    this.owner.lookup('router:main').reopen({
      intermediateTransitionTo(routeName) {
        assert.equal(routeName, 'blog.post.error');
        this._super(...arguments);
      },
    });

    await visit('/routable-engine-demo/blog/post/1/comments');
    await click('.routable-post-diggs-link');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1/comments');
    assert.equal(find('.error-message').textContent, 'Error: Nope!');
  });

  test('initializers run within engine', async function (assert) {
    assert.expect(1);

    let stub = sinon.stub(Initializer, 'initialize');

    await visit('/routable-engine-demo/blog/new');

    assert.ok(stub.calledOnce, 'Initializer ran once');
  });

  test('instance initializers run within engine', async function (assert) {
    assert.expect(1);

    let stub = sinon.stub(InstanceInitializer, 'initialize');

    await visit('/routable-engine-demo/blog/new');

    assert.ok(stub.calledOnce, 'Instance initializer ran once');
  });

  test('instance-initializers run after initializers', async function (assert) {
    assert.expect(2);

    let appInitialized = false;
    let instanceInitialized = false;

    let appInit = sinon.stub(Initializer, 'initialize').callsFake(() => {
      appInitialized = true;
      assert.ok(!instanceInitialized, 'instance initialized has not run yet');
    });

    let instanceInit = sinon.stub(InstanceInitializer, 'initialize').callsFake(() => {
      instanceInitialized = true;
      assert.ok(appInitialized, 'initializer already ran');
    });

    await visit('/routable-engine-demo/blog/new');

    appInit.restore();
    instanceInit.restore();
  });

});<commit_msg>Update tests/acceptance/routeable-engine-demo-test.js<commit_after>import Ember from 'ember';
import { module, test } from 'qunit';
import { default as _sinon } from 'sinon';
import Initializer from 'ember-blog/initializers/ember-blog-initializer';
import InstanceInitializer from 'ember-blog/instance-initializers/ember-blog-instance-initializer';
import { setupApplicationTest } from 'ember-qunit';
import { currentURL, visit, find, click } from '@ember/test-helpers';

let originalExceptionHandler;
let sinon;

module('Acceptance | routeless engine demo', function (hooks) {
  setupApplicationTest(hooks);

  hooks.beforeEach(function () {
    originalExceptionHandler = Ember.Test.adapter.exception;
    sinon = _sinon.createSandbox();
  });

  hooks.afterEach(function () {
    sinon.restore();
    Ember.Test.adapter.exception = originalExceptionHandler;
  });

  test('can invoke components', async function (assert) {
    await visit('/routable-engine-demo/blog/new');

    assert.equal(currentURL(), '/routable-engine-demo/blog/new');

    assert.equal(
        find('.routable-hello-world')
        .textContent
        .trim(),
      'Hello, world!'
    );
    assert.equal(
        find('.hello-name')
        .textContent
        .trim(),
      'Hello, Jerry!',
      'Re-rendered hello-name component correctly'
    );
  });

  test("can deserialize a route's params", async function (assert) {
    assert.expect(3);

    await visit('/routable-engine-demo/blog/post/1');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1');

    assert.equal(
      find('h3.post-title')
        .textContent
        .trim(),
      'Post 1'
    );
    assert.equal(
      find('p.author')
        .textContent
        .trim(),
      'Derek Zoolander'
    );
  });

  test('can link-to application route of Engine', async function (assert) {
    await visit('/routable-engine-demo/blog/post/new');
    await click('.routable-post-blog-home-link-app');

    assert.equal(currentURL(), '/routable-engine-demo/blog');
  });

  test('correctly handles navigation with query param in initial url', async function (
    assert
  ) {
    assert.expect(9);

    await visit('/routable-engine-demo/blog/post/1?lang=English');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=English',
      'url is visited properly'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'English',
      'query param value is passed through correctly - 1'
    );

    await click('.routable-post-comments-link');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1/comments?lang=English',
      'query param is carried to sub-route'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'English',
      'query param value is passed through correctly - 2'
    );

    await click('.back-to-post-link');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=English',
      'query param is carried back to original route properly'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'English',
      'query param value is passed through correctly - 3'
    );

    await click('.routable-post-blog-home-link');
    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog',
      'query param is removed when changing route hierarchy'
    );

    await click('.routable-post-1-link');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=English',
      'query param is rehydrated in url'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'English',
      'query param value is passed through correctly - 4'
    );
  });

  test('can link-to a route with query params from outside an Engine', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo');
    await click('.blog-post-1-link-jp');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=Japanese'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'Japanese'
    );
  });

  test('can programmatically transition to a route with query params from outside an Engine', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo');
    await click('.blog-post-1-link-ch');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=Chinese'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'Chinese'
    );
  });

  test('can link-to a route with query params within an Engine', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog');
    await click('.routable-post-1-link-jp');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=Japanese'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'Japanese'
    );
  });

  test('can programmatically transition to a route with query params within an Engine', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog');
    await click('.routable-post-1-link-ch');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=Chinese'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'Chinese'
    );
  });

  test('can perform a QP-only link-to transition', async function (assert) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog/post/1?lang=English');
    await click('.routable-post-jp-link');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=Japanese',
      'URL is updated properly'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'Japanese',
      'DOM is updated properly'
    );
  });

  test('can perform a QP-only transitionTo', async function (assert) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog/post/1?lang=English');
    await click('.routable-post-ch-link');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=Chinese',
      'URL is updated properly'
    );
    assert.equal(
      find('p.language')
        .textContent
        .trim(),
      'Chinese',
      'DOM is updated properly'
    );
  });

  test('can perform a redirect transition with QP', async function (assert) {
    assert.expect(1);

    await visit('/routable-engine-demo/redirect');
    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=English'
    );
  });

  test('can perform an afterModel transition with QP', async function (assert) {
    assert.expect(1);

    await visit('/routable-engine-demo/after-model/3');
    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/3?lang=English'
    );
  });

  test('query param bucket cache does not collide when starting outside Engine', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/post/1?lang=English');
    await click('.blog-post-no-qp');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1',
      'URL does not have any query params'
    );

    await click('.non-blog-post');
    assert.equal(
      currentURL(),
      '/post/1?lang=English',
      'URL has original query params'
    );
  });

  test('query param bucket cache does not collide when starting inside Engine', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog/post/1?lang=English');
    await click('.non-blog-post');

    assert.equal(currentURL(), '/post/1', 'URL does not have any query params');

    await click('.blog-post-no-qp');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/blog/post/1?lang=English',
      'URL has original query params'
    );
  });

  test("a route can lookup another route's model", async function (assert) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog/post/1/comments');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1/comments');

    assert.equal(
      find('h4.comments')
        .textContent
        .trim(),
      'Comments for Post 1'
    );
  });

  test('can render a link', async function (assert) {
    assert.expect(2);

    await visit('/routable-engine-demo/blog/post/1');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1');

    let contentLink = find('a.routable-post-comments-link').href;

    assert.ok(
      contentLink.includes('/routable-engine-demo/blog/post/1/comments')
    );
  });

  test('link-to current-when attribute prepends engine mount point', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/eager-blog/post/1');

    assert.equal(currentURL(), '/routable-engine-demo/eager-blog/post/1');
    assert.ok(
      find('a.current-when-test-link').classList.contains('active')
    );
  });

  test('internal links can be clicked', async function (assert) {
    assert.expect(1);

    await visit('/routable-engine-demo/blog/post/1');
    await click('.routable-post-home-link');

    assert.equal(currentURL(), '/');
  });

  test('external links can be clicked', async function (assert) {
    assert.expect(1);

    await visit('/routable-engine-demo/blog/post/1');
    await click('.routable-post-comments-link');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1/comments');
  });

  test('a route can use transitionTo to transition to internal route', async function (
    assert
  ) {
    assert.expect(1);

    await visit('/routable-engine-demo/blog/new');
    await click('.trigger-transition-to');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1');
  });

  test('internal links can be clicked', async function (assert) {
    assert.expect(1);

    await visit('/routable-engine-demo/special-admin-blog-here/post/1');
    await click('.routable-post-comments-link');

    assert.equal(
      currentURL(),
      '/routable-engine-demo/special-admin-blog-here/post/1/comments'
    );
  });

  test('transitionTo works properly within parent application', async function (assert) {
    assert.expect(1);

    await visit('/routable-engine-demo/normal-route');

    assert.equal(currentURL(), '/routeless-engine-demo');
  });

  test('transitionToExternal transitions to the parent application from within an engine and returns a thenable Transition object', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/ember-blog/post/1');
    await click('.routable-post-transition-to-home-button');

    assert.equal(currentURL(), '/');

    await click('.routeable-engine');
    await click('.ember-blog-new');
    await click('.trigger-transition-to');

    assert.ok(
      find('.routable-post-transition-to-home-button').classList.contains('transitioned-to-external')
    );
  });

  test("transitionToExternalRoute transitions to the parent application from within an engine's controller and returns a thenable Transition object", async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/ember-blog/post/1');
    await click('.routable-post-transition-to-route-home-button');

    assert.equal(currentURL(), '/');

    await click('.routeable-engine');
    await click('.ember-blog-new');
    await click('.trigger-transition-to');

    assert.ok(
      find('.routable-post-transition-to-route-home-button').classList.contains('transitioned-to-route-external')
    );
  });

  test('replaceWithExternal transitions to the parent application from within an engine and returns a thenable Transition object', async function (
    assert
  ) {
    assert.expect(2);

    await visit('/routable-engine-demo/ember-blog/post/1');
    await click('.routable-post-replace-with-home-button');

    assert.equal(currentURL(), '/');

    await click('.routeable-engine');
    await click('.ember-blog-new');
    await click('.trigger-transition-to');

    assert.ok(
      find('.routable-post-replace-with-home-button').classList.contains('replaced-with-external')
    );
  });

  test('loading routes and intermediateTransitionTo work within an engine', async function (
    assert
  ) {
    assert.expect(2);

    this.owner.lookup('router:main').reopen({
      intermediateTransitionTo(routeName) {
        assert.equal(routeName, 'blog.post.loading');
        this._super(...arguments);
      },
    });

    await visit('/routable-engine-demo/blog/post/1/comments');
    await click('.routable-post-likes-link');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1/likes');
  });

  test('error routes and intermediateTransitionTo work within an engine', async function (
    assert
  ) {
    assert.expect(3);

    Ember.Test.adapter.exception = () => { };

    this.owner.lookup('router:main').reopen({
      intermediateTransitionTo(routeName) {
        assert.equal(routeName, 'blog.post.error');
        this._super(...arguments);
      },
    });

    await visit('/routable-engine-demo/blog/post/1/comments');
    await click('.routable-post-diggs-link');

    assert.equal(currentURL(), '/routable-engine-demo/blog/post/1/comments');
    assert.equal(find('.error-message').textContent, 'Error: Nope!');
  });

  test('initializers run within engine', async function (assert) {
    assert.expect(1);

    let stub = sinon.stub(Initializer, 'initialize');

    await visit('/routable-engine-demo/blog/new');

    assert.ok(stub.calledOnce, 'Initializer ran once');
  });

  test('instance initializers run within engine', async function (assert) {
    assert.expect(1);

    let stub = sinon.stub(InstanceInitializer, 'initialize');

    await visit('/routable-engine-demo/blog/new');

    assert.ok(stub.calledOnce, 'Instance initializer ran once');
  });

  test('instance-initializers run after initializers', async function (assert) {
    assert.expect(2);

    let appInitialized = false;
    let instanceInitialized = false;

    let appInit = sinon.stub(Initializer, 'initialize').callsFake(() => {
      appInitialized = true;
      assert.ok(!instanceInitialized, 'instance initialized has not run yet');
    });

    let instanceInit = sinon.stub(InstanceInitializer, 'initialize').callsFake(() => {
      instanceInitialized = true;
      assert.ok(appInitialized, 'initializer already ran');
    });

    await visit('/routable-engine-demo/blog/new');

    appInit.restore();
    instanceInit.restore();
  });

});
<|endoftext|>


<commit_before>var data  = function(){
  var Randexp = require("randexp");
  var _ = require("lodash");

  var rules = require("./rules");

  /**
   * Generate string based on validation
   * @param {String} validation validation rule
   */
  function generate(validations){
    // Convert string to Special Object
    var specialObject = arrayToSpecialObj(arrayOfValidation)
  }

  /**
   * Convert Array of Validation Rule to Special Object which used in building Regular Expression
   * @param {Array} validation Array of Validation rule
   */
  function arrayToSpecialObj(arrayOfValidation){
    var specialObject = {}

    specialObject.pattern = "."

    _.forEach(arrayOfValidation,function(n,key){
      var size = n.split(':')
      if(size.length > 0 && size.length<=2){
        switch(size[0]){
          case 'alpha' :
          case 'alpha_dash' :
          case 'alpha_num' :
          case 'email' :
            specialObject.pattern = rules[size[0]].pattern
            if(size[0] === 'email'){
              delete specialObject.size;
            }
            break;
          case 'min':
            var min = parseInt(size[1])
            if(min >= 0){
              if(!specialObject.notMax){
                specialObject.min= min
              }
            }else if(typeof size[1] === "undefined" || size[1] === "" ){
              throw new Error("Minimal size is undefined, please check your syntax at '"+n+"'")
            }else if(min<0){
              throw new Error("Minimal size is less than 0")
            }
            break;
          case '^min':
            var min = parseInt(size[1])
            if(min >= 1){
              specialObject.max= min-1
              specialObject.notMin = true;
            }else if(min === 0){
              specialObject.pattern = null
              specialObject.notMin = true;
            }else if(typeof size[1] === "undefined" || size[1] === "" ){
              throw new Error("Minimal size is undefined, please check your syntax at '"+n+"'")
            }else if(min<0){
              throw new Error("Minimal size is less than 0")
            }
            break;
          case 'max':
            var max = parseInt(size[1])
            if(max >= 0){
              if(!specialObject.notMin){
                specialObject.max= max
              }
            }else if(typeof size[1] === "undefined" || size[1] === "" ){
              throw new Error("Maximal size is undefined, please check your syntax at '"+n+"'")
            }else if(min<0){
              throw new Error("Maximal size is less than 0")
            }
            break;
          case '^max':
            var max = parseInt(size[1])
            if(max >= 1){
              specialObject.min= max+1
              specialObject.notMax = true
            }else if(typeof size[1] === "undefined" || size[1] === "" ){
              throw new Error("Maximal size is undefined, please check your syntax at '"+n+"'")
            }else if(min<0){
              throw new Error("Maximal size is less than 0")
            }
            break;
          case 'exact':
            var exactSize = parseInt(size[1])
            if(exactSize>=0){
              specialObject.min = exactSize
              specialObject.max = exactSize
            }else if(typeof size[1] === "undefined" || size[1] === ""){
              throw new Error("Exact size is undefined")
            }else if(exactSize<0){
              throw new Error("Exact size is less than 0")
            }else{
              throw new Error("Unknown Errors")
            }
            break;
          case '^exact':
            var exactSize = parseInt(size[1])
            if(exactSize>=0){
              specialObject.min = exactSize+1
              specialObject.max = exactSize-1
              specialObject.notMin = true
              specialObject.notMax = true
            }else if(typeof size[1] === "undefined" || size[1] === ""){
              throw new Error("Exact size is undefined")
            }else if(exactSize<0){
              throw new Error("Exact size is less than 0")
            }else{
              throw new Error("Unknown Errors")
            }
            break;
          case 'between':
            if(typeof size[1] != "undefined" && size[1] != ""){
              // throw new Error(size)
              var betweenSize = size[1].split(",")

              if(
                typeof betweenSize[0] != "undefined" &&
                typeof betweenSize[1] != "undefined" &&
                parseInt(betweenSize[0]) <= parseInt(betweenSize[1])
              ){
                specialObject.min = parseInt(betweenSize[0])
                specialObject.max = parseInt(betweenSize[1])

                if(specialObject.min<0){
                  throw new Error("Minimal size is less than 0")
                }
                if(specialObject.max<0){
                  throw new Error("Minimal size is less than 0")
                }
              }else if(typeof betweenSize[0] === "undefined" || betweenSize[0] === ""){
                // Throw Error
                throw new Error("Minimal size is undefined, please check your syntax at '"+n+"'")
              }else if(typeof betweenSize[1] === "undefined" || betweenSize[1] === ""){
                // Throw Error
                throw new Error("Maximal size is undefined, please check your syntax at '"+n+"'")
              }else if(parseInt(betweenSize[0])>parseInt(betweenSize[1])){
                // Throw Error
                throw new Error("Minimal Size has bigger value than Maximal Size")
              }else{
                throw new Error("Unknown Error")
              }
            }else{
              // Throw Error
              throw new Error("Minimal and Maximal Size are undefined, please check yout syntax at '"+n+"'")
            }
            break;
          case '^between':
            if(typeof size[1] != "undefined" && size[1] != ""){
              // throw new Error(size)
              var betweenSize = size[1].split(",")

              if(
                typeof betweenSize[0] != "undefined" &&
                typeof betweenSize[1] != "undefined" &&
                parseInt(betweenSize[0]) <= parseInt(betweenSize[1])
              ){
                specialObject.min = parseInt(betweenSize[0])+1
                specialObject.max = parseInt(betweenSize[1])-1
                specialObject.notMin = true
                specialObject.notMax = true

                if(specialObject.min<0){
                  throw new Error("Minimal size is less than 0")
                }
                if(specialObject.max<0){
                  throw new Error("Minimal size is less than 0")
                }
              }else if(typeof betweenSize[0] === "undefined" || betweenSize[0] === ""){
                // Throw Error
                throw new Error("Minimal size is undefined, please check your syntax at '"+n+"'")
              }else if(typeof betweenSize[1] === "undefined" || betweenSize[1] === ""){
                // Throw Error
                throw new Error("Maximal size is undefined, please check your syntax at '"+n+"'")
              }else if(parseInt(betweenSize[0])>parseInt(betweenSize[1])){
                // Throw Error
                throw new Error("Minimal Size has bigger value than Maximal Size")
              }else{
                throw new Error("Unknown Error")
              }
            }else{
              // Throw Error
              throw new Error("Minimal and Maximal Size are undefined, please check yout syntax at '"+n+"'")
            }
            break;
        }
      }
    })

    return specialObject;
  }
  /**
   * Build regex from special object
   * @param {Object} specialObject Special Object
   * @param {String} mode mode for RegExp {i,g,...}
   * @return {Object} Regular Expression Object
   */
  function buildRegex(specialObject){
    if(specialObject.pattern){
      var size = getRegexSize(specialObject);
      var regexSize;

      regexSize = size.join();
      if(regexSize){
        regexSize = "{"+regexSize+"}"
      }

      if(!regexSize && specialObject.pattern[(specialObject.pattern.length-1)] != "}"){
        specialObject.pattern += "+"
      }

      return new RegExp("^"+specialObject.pattern+regexSize+"$",mode);
    }else{
      throw new Error("Couldn't generate regex because of undefined pattern")
    }
  }

  /**
  * Get regex rule Size
  * @param {Object} specialObject Special Object
  * @return {Mixed} String when success {x,y} x is min, and y is max, and FALSE when fail
  */
  function getRegexSize(specialObject){
    if(specialObject.min && specialObject.max){
      if(specialObject.min < 0 && specialObject.max < 0){
        // return new Error("Minimal and Maximal size is less than zero")
        return []
      }else{
        if(!isNaN(specialObject.min) && !isNaN(specialObject.max)){
          if(specialObject.notMax && specialObject.notMin){
            var size = [
              [0,specialObject.max],
              [specialObject.min,""]
            ]
          }else if (specialObject.notMin){
            var size = [0,specialObject.max]
          }else if (specialObject.notMax){
            var size = [specialObject.min,""]
          }else{
            var size = [specialObject.min,specialObject.max]
          }
        }else if(isNaN(specialObject.min) && !isNaN(specialObject.max)){
          // return new Error("Minimal size is not a number")
          return []
        }else if(!isNaN(specialObject.min) && isNaN(specialObject.max)){
          // return new Error("Maximal size is not a number")
          return []
        }else{
          // return new Error("Minimal and Maximal size is not a number")
          return []
        }
      }
    }else if(specialObject.min){
      if(specialObject.min < 0){
        // return new Error("Minimal size is less than zero")
        return []
      }else{
        if(!isNaN(specialObject.min)){
          var size = [specialObject.min,""]
        }else{
          // return new Error("Minimal size is not a number")
          return []
        }
      }
    }else if(specialObject.max){
      if(specialObject.max < 0){
        // return new Error("Maximal size is less than zero")
        return []
      }else{
        if(!isNaN(specialObject.max)){
          var size = [0,specialObject.max];
        }else{
          // return new Error("Maximal size is not a number")
          return []
        }
      }
    }else{
      // return new Error("Minimal or Maximal size is undefined")
      return []
    }

    return size;
  }

  return {
    'stringToArray' : stringToArray,
    'arrayToSpecialObj' : arrayToSpecialObj,
    'buildRegex' : buildRegex,
    'getRegexSize' : getRegexSize,
    'generate' : generate,
  }
}

module.exports = data();
<commit_msg>generate regex<commit_after>var data  = function(){
  var Randexp = require("randexp");
  var _ = require("lodash");

  var rules = require("./rules");

  /**
   * Generate string based on validation
   * @param {String} validation validation rule
   */
  function generate(validations){
    // Convert string to Special Object
    var specialObject = arrayToSpecialObj(arrayOfValidation)
  }

  /**
   * Convert Array of Validation Rule to Special Object which used in building Regular Expression
   * @param {Array} validation Array of Validation rule
   */
  function arrayToSpecialObj(arrayOfValidation){
    var specialObject = {}

    specialObject.pattern = "."

    _.forEach(arrayOfValidation,function(n,key){
      var size = n.split(':')
      if(size.length > 0 && size.length<=2){
        switch(size[0]){
          case 'required' :
              specialObject.min = 1
            break;
          case 'alpha' :
          case 'alpha_dash' :
          case 'alpha_num' :
          case 'email' :
            specialObject.pattern = rules[size[0]].pattern
            if(size[0] === 'email'){
              delete specialObject.size;
            }
            break;
          case 'min':
            var min = parseInt(size[1])
            if(min >= 0){
              if(!specialObject.notMax){
                specialObject.min= min
              }
            }else if(typeof size[1] === "undefined" || size[1] === "" ){
              throw new Error("Minimal size is undefined, please check your syntax at '"+n+"'")
            }else if(min<0){
              throw new Error("Minimal size is less than 0")
            }
            break;
          case '^min':
            var min = parseInt(size[1])
            if(min >= 1){
              specialObject.max= min-1
              specialObject.notMin = true;
            }else if(min === 0){
              specialObject.pattern = null
              specialObject.notMin = true;
            }else if(typeof size[1] === "undefined" || size[1] === "" ){
              throw new Error("Minimal size is undefined, please check your syntax at '"+n+"'")
            }else if(min<0){
              throw new Error("Minimal size is less than 0")
            }
            break;
          case 'max':
            var max = parseInt(size[1])
            if(max >= 0){
              if(!specialObject.notMin){
                specialObject.max= max
              }
            }else if(typeof size[1] === "undefined" || size[1] === "" ){
              throw new Error("Maximal size is undefined, please check your syntax at '"+n+"'")
            }else if(min<0){
              throw new Error("Maximal size is less than 0")
            }
            break;
          case '^max':
            var max = parseInt(size[1])
            if(max >= 1){
              specialObject.min= max+1
              specialObject.notMax = true
            }else if(typeof size[1] === "undefined" || size[1] === "" ){
              throw new Error("Maximal size is undefined, please check your syntax at '"+n+"'")
            }else if(min<0){
              throw new Error("Maximal size is less than 0")
            }
            break;
          case 'exact':
            var exactSize = parseInt(size[1])
            if(exactSize>=0){
              specialObject.min = exactSize
              specialObject.max = exactSize
            }else if(typeof size[1] === "undefined" || size[1] === ""){
              throw new Error("Exact size is undefined")
            }else if(exactSize<0){
              throw new Error("Exact size is less than 0")
            }else{
              throw new Error("Unknown Errors")
            }
            break;
          case '^exact':
            var exactSize = parseInt(size[1])
            if(exactSize>=0){
              specialObject.min = exactSize+1
              specialObject.max = exactSize-1
              specialObject.notMin = true
              specialObject.notMax = true
            }else if(typeof size[1] === "undefined" || size[1] === ""){
              throw new Error("Exact size is undefined")
            }else if(exactSize<0){
              throw new Error("Exact size is less than 0")
            }else{
              throw new Error("Unknown Errors")
            }
            break;
          case 'between':
            if(typeof size[1] != "undefined" && size[1] != ""){
              // throw new Error(size)
              var betweenSize = size[1].split(",")

              if(
                typeof betweenSize[0] != "undefined" &&
                typeof betweenSize[1] != "undefined" &&
                parseInt(betweenSize[0]) <= parseInt(betweenSize[1])
              ){
                specialObject.min = parseInt(betweenSize[0])
                specialObject.max = parseInt(betweenSize[1])

                if(specialObject.min<0){
                  throw new Error("Minimal size is less than 0")
                }
                if(specialObject.max<0){
                  throw new Error("Minimal size is less than 0")
                }
              }else if(typeof betweenSize[0] === "undefined" || betweenSize[0] === ""){
                // Throw Error
                throw new Error("Minimal size is undefined, please check your syntax at '"+n+"'")
              }else if(typeof betweenSize[1] === "undefined" || betweenSize[1] === ""){
                // Throw Error
                throw new Error("Maximal size is undefined, please check your syntax at '"+n+"'")
              }else if(parseInt(betweenSize[0])>parseInt(betweenSize[1])){
                // Throw Error
                throw new Error("Minimal Size has bigger value than Maximal Size")
              }else{
                throw new Error("Unknown Error")
              }
            }else{
              // Throw Error
              throw new Error("Minimal and Maximal Size are undefined, please check yout syntax at '"+n+"'")
            }
            break;
          case '^between':
            if(typeof size[1] != "undefined" && size[1] != ""){
              // throw new Error(size)
              var betweenSize = size[1].split(",")

              if(
                typeof betweenSize[0] != "undefined" &&
                typeof betweenSize[1] != "undefined" &&
                parseInt(betweenSize[0]) <= parseInt(betweenSize[1])
              ){
                specialObject.min = parseInt(betweenSize[0])+1
                specialObject.max = parseInt(betweenSize[1])-1
                specialObject.notMin = true
                specialObject.notMax = true

                if(specialObject.min<0){
                  throw new Error("Minimal size is less than 0")
                }
                if(specialObject.max<0){
                  throw new Error("Minimal size is less than 0")
                }
              }else if(typeof betweenSize[0] === "undefined" || betweenSize[0] === ""){
                // Throw Error
                throw new Error("Minimal size is undefined, please check your syntax at '"+n+"'")
              }else if(typeof betweenSize[1] === "undefined" || betweenSize[1] === ""){
                // Throw Error
                throw new Error("Maximal size is undefined, please check your syntax at '"+n+"'")
              }else if(parseInt(betweenSize[0])>parseInt(betweenSize[1])){
                // Throw Error
                throw new Error("Minimal Size has bigger value than Maximal Size")
              }else{
                throw new Error("Unknown Error")
              }
            }else{
              // Throw Error
              throw new Error("Minimal and Maximal Size are undefined, please check yout syntax at '"+n+"'")
            }
            break;
        }
      }
    })

    return specialObject;
  }
  /**
   * Build regex from special object
   * @param {Object} specialObject Special Object
   * @param {String} mode mode for RegExp {i,g,...}
   * @return {Object} Regular Expression Object
   */
  function buildRegex(specialObject, mode){
    if(typeof mode === "undefined"){
      mode = ""
    }
    if(specialObject.pattern){
      var size = getRegexSize(specialObject);
      var regexSize;
      var regexArray = []
      var regexPattern = "";

      _.forEach(size,function(data,index){
        console.log(data)
        regexSize = data.join();
        if(regexSize){
          regexSize = "{"+regexSize+"}"
        }
        if(!regexSize && specialObject.pattern[(specialObject.pattern.length-1)] != "}"){
          specialObject.pattern += "+"
        }
        regexArray.push("^"+specialObject.pattern+regexSize+"")
        console.log(regexArray);
      })

      regexPattern = regexArray.join("|")
      return new RegExp("("+regexPattern+")$",mode);
    }else{
      throw new Error("Couldn't generate regex because of undefined pattern")
    }
  }

  /**
  * Get regex rule Size
  * @param {Object} specialObject Special Object
  * @return {Mixed} String when success {x,y} x is min, and y is max, and FALSE when fail
  */
  function getRegexSize(specialObject){
    if(specialObject.min && specialObject.max){
      if(specialObject.min < 0 && specialObject.max < 0){
        // return new Error("Minimal and Maximal size is less than zero")
        return []
      }else{
        if(!isNaN(specialObject.min) && !isNaN(specialObject.max)){
          if(specialObject.notMax && specialObject.notMin){
            var size = [
              [0,specialObject.max],
              [specialObject.min,""]
            ]
          }else if (specialObject.notMin && !specialObject.notMax ){
            if(specialObject.min)
              var size = [[specialObject.min,specialObject.max]]
            else
              var size = [[0,specialObject.max]]

          }else if (specialObject.notMax && !specialObject.notMin){
            var size = [[specialObject.min,""]]
          }else{
            var size = [[specialObject.min,specialObject.max]]
          }
        }else if(isNaN(specialObject.min) && !isNaN(specialObject.max)){
          // return new Error("Minimal size is not a number")
          return []
        }else if(!isNaN(specialObject.min) && isNaN(specialObject.max)){
          // return new Error("Maximal size is not a number")
          return []
        }else{
          // return new Error("Minimal and Maximal size is not a number")
          return []
        }
      }
    }else if(specialObject.min){
      if(specialObject.min < 0){
        // return new Error("Minimal size is less than zero")
        return []
      }else{
        if(!isNaN(specialObject.min)){
          var size = [[specialObject.min,""]]
        }else{
          // return new Error("Minimal size is not a number")
          return []
        }
      }
    }else if(specialObject.max){
      if(specialObject.max < 0){
        // return new Error("Maximal size is less than zero")
        return []
      }else{
        if(!isNaN(specialObject.max)){
            var size = [[0,specialObject.max]];
        }else{
          // return new Error("Maximal size is not a number")
          return []
        }
      }
    }else{
      // return new Error("Minimal or Maximal size is undefined")
      return []
    }

    return size;
  }

  return {
    'arrayToSpecialObj' : arrayToSpecialObj,
    'buildRegex' : buildRegex,
    'getRegexSize' : getRegexSize,
    'generate' : generate,
  }
}

module.exports = data();
<|endoftext|>


<commit_before>export default class GameProcessor {
    constructor(size, opponents) {
        this.size = size;
        this.opponents = opponents;
        this.battlefields = [];
    }

    /**
     * @param {{id: {number}, coordinate: {string}}} criteria
     */
    findCellByCriteria(criteria) {
        let cell = this.cells.find(cell =>
            (undefined !== criteria.id && cell.id === criteria.id) ||
            (undefined !== criteria.coordinate && cell.coordinate === criteria.coordinate)
        );
        if (undefined !== cell) {
            return cell;
        }

        throw `cell by criteria ${JSON.stringify(criteria)} not found`;
    }
}<commit_msg>comment out unused code [will be used later]<commit_after>export default class GameProcessor {
    constructor(size, opponents) {
        this.size = size;
        this.opponents = opponents;
        this.battlefields = [];
    }

    /**
     * @param {{id: {number}, coordinate: {string}}} criteria
     */
    /** findCellByCriteria(criteria) {
        let cell = this.cells.find(cell =>
            (undefined !== criteria.id && cell.id === criteria.id) ||
            (undefined !== criteria.coordinate && cell.coordinate === criteria.coordinate)
        );
        if (undefined !== cell) {
            return cell;
        }

        throw `cell by criteria ${JSON.stringify(criteria)} not found`;
    } */
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var os = require("os");
var fs = require("fs");
var promise = require("deferred");

var vccutil = require("./vccutil.js");
var logger = require("./log.js");

// This is an init8js module, it runs in-process with the init in order to
// register our cluster targets, so it must follow the service module pattern
module.exports = {
    LoadTargets: function (service, config, targets, f_register_services) {
	    var deferred = promise();
	    var config = vccutil.getConfig();
	    var servicefile = "/etc/vcc/services-"+config.service+".yml";
	    // make sure service targets definition file exists
	    fs.stat(servicefile, function(err, stat) {
	        if(err == null) {
	            // parse the yaml file and register the targets
	            logger.debug("Registering service provider targets for "+config.service);
	            f_register_services(yaml.load(servicefile));
	            deferred.resolve();
	        } else if(err.code == 'ENOENT') {
	            // no service file
	            logger.error('There is no service definition for '+config.service);
	            logger.error('Please create '+servicefile);
	        } else {
	            // something went wrong
	            logger.error('unhandled error hook stat', servicefile);
	        }
	    });
	    return deferred.promise();
	}
}<commit_msg>need yamljs library<commit_after>#!/usr/bin/env node

var os = require("os");
var fs = require("fs");
var promise = require("deferred");
var yaml = require('yamljs');

var vccutil = require("./vccutil.js");
var logger = require("./log.js");

// This is an init8js module, it runs in-process with the init in order to
// register our cluster targets, so it must follow the service module pattern
module.exports = {
    LoadTargets: function (service, config, targets, f_register_services) {
	    var deferred = promise();
	    var config = vccutil.getConfig();
	    var servicefile = "/etc/vcc/services-"+config.service+".yml";
	    // make sure service targets definition file exists
	    fs.stat(servicefile, function(err, stat) {
	        if(err == null) {
	            // parse the yaml file and register the targets
	            logger.debug("Registering service provider targets for "+config.service);
	            f_register_services(yaml.load(servicefile));
	            deferred.resolve();
	        } else if(err.code == 'ENOENT') {
	            // no service file
	            logger.error('There is no service definition for '+config.service);
	            logger.error('Please create '+servicefile);
	        } else {
	            // something went wrong
	            logger.error('unhandled error hook stat', servicefile);
	        }
	    });
	    return deferred.promise();
	}
}<|endoftext|>


<commit_before>function City() {
  this.LOT_WIDTH = 1;
  this.LOT_DEPTH = 1;
  this.STREET_WIDTH = 2;
  this.STREET_DEPTH = 2;
  this.BLOCK_WIDTH = 4;
  this.BLOCK_DEPTH = 4;
  this.BLOCK_ROWS = 60;
  this.BLOCK_COLUMNS = 20;
  this.MIN_BUILDING_HEIGHT = 0.5;
  this.MAX_BUILDING_HEIGHT = 20;
  this.MAX_BUILDING_MATERIALS = 50;
  this.TOTAL_SCENE_WIDTH = (this.BLOCK_WIDTH * this.BLOCK_ROWS) + (this.STREET_WIDTH * (this.BLOCK_ROWS - 1));
  this.HALF_SCENE_WIDTH = this.TOTAL_SCENE_WIDTH / 2;
  this.TOTAL_SCENE_DEPTH = (this.BLOCK_DEPTH * this.BLOCK_COLUMNS) + (this.STREET_DEPTH * (this.BLOCK_COLUMNS - 1));
  this.HALF_SCENE_DEPTH = this.TOTAL_SCENE_DEPTH / 2;
}

City.prototype.buildScene = function() {
  var scene = new THREE.Scene();

  var originMaterial = new THREE.MeshLambertMaterial({ color: 0xf32920 });
  var origin = new THREE.Mesh(new THREE.SphereGeometry(0.5, 10, 10), originMaterial);
  scene.add(origin);

  var groundMaterial = new THREE.MeshBasicMaterial({ color: 0x777777 });
  var ground = new THREE.Mesh(new THREE.PlaneGeometry(this.TOTAL_SCENE_WIDTH * 5, this.TOTAL_SCENE_DEPTH * 5), groundMaterial);
  ground.rotation.x = -(Math.PI / 2);
  scene.add(ground);

  var buildingMaterials = [];
  var buildingGeometries = [];
  for (var i = 0; i < this.MAX_BUILDING_MATERIALS; i++) {
    var r = Math.random();
    var g = Math.random();
    var b = Math.random();
    var buildingColor = new THREE.Color(0xffffff);
    buildingColor.setRGB(r, g, b);

    buildingMaterials.push(new THREE.MeshLambertMaterial({ color: buildingColor.getHex() }));
    buildingGeometries.push(new THREE.Geometry());
  }

  var BLOCK_LAYOUTS = [
                        [ { width: 1.0, depth: 1.0, offsetFromBlockCenterX: 0.0, offsetFromBlockCenterZ: 0.0 } ],
                        [ { width: 0.5, depth: 1.0, offsetFromBlockCenterX: -0.5, offsetFromBlockCenterZ: 0.0 },
                          { width: 0.5, depth: 1.0, offsetFromBlockCenterX: 0.5, offsetFromBlockCenterZ: 0.0 } ],
                        [ { width: 1.0, depth: 0.5, offsetFromBlockCenterX: 0.0, offsetFromBlockCenterZ: -0.5 },
                          { width: 1.0, depth: 0.5, offsetFromBlockCenterX: 0.0, offsetFromBlockCenterZ: 0.5 } ],
                        [ { width: 0.5, depth: 1.0, offsetFromBlockCenterX: -0.5, offsetFromBlockCenterZ: 0.0 },
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: 0.5, offsetFromBlockCenterZ: -0.5},
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: 0.5, offsetFromBlockCenterZ: 0.5} ],
                        [ { width: 0.5, depth: 0.5, offsetFromBlockCenterX: -0.5, offsetFromBlockCenterZ: -0.5 },
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: -0.5, offsetFromBlockCenterZ: 0.5},
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: 0.5, offsetFromBlockCenterZ: -0.5},
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: 0.5, offsetFromBlockCenterZ: 0.5} ],
                        [ { width: (1 / 3), depth: 0.5, offsetFromBlockCenterX: -(2 / 3), offsetFromBlockCenterZ: 0.5 },
                          { width: (1 / 3), depth: 0.5, offsetFromBlockCenterX: 0.0, offsetFromBlockCenterZ: 0.5},
                          { width: (1 / 3), depth: 0.5, offsetFromBlockCenterX: (2 / 3), offsetFromBlockCenterZ: 0.5},
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: -0.5, offsetFromBlockCenterZ: -0.5},
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: 0.5, offsetFromBlockCenterZ: -0.5} ],
                      ];

  // Loop through the lower left corner of each block
  for (var i = -(this.HALF_SCENE_WIDTH); i < this.HALF_SCENE_WIDTH; i += this.BLOCK_WIDTH + this.STREET_WIDTH) {
    for (var j = -(this.HALF_SCENE_DEPTH); j < this.HALF_SCENE_DEPTH; j += this.BLOCK_DEPTH + this.STREET_DEPTH) {

      var building;
      var blockLayout = BLOCK_LAYOUTS[Math.floor(Math.random() * BLOCK_LAYOUTS.length)];
      for (var layoutIndex = 0; layoutIndex < blockLayout.length; layoutIndex++) {
        var lotLayout = blockLayout[layoutIndex];
        var maxHeightI = this.MAX_BUILDING_HEIGHT * ((this.HALF_SCENE_WIDTH - Math.abs(i)) / this.HALF_SCENE_WIDTH);
        var maxHeightJ = this.MAX_BUILDING_HEIGHT * ((this.HALF_SCENE_DEPTH - Math.abs(j)) / this.HALF_SCENE_DEPTH);
        var maxHeight = Math.min(maxHeightI, maxHeightJ);
        var buildingHeight = Math.floor((Math.random() * maxHeight - this.MIN_BUILDING_HEIGHT)) + this.MIN_BUILDING_HEIGHT;

        building = new THREE.Mesh(new THREE.CubeGeometry(lotLayout.width * this.BLOCK_WIDTH, 1, lotLayout.depth * this.BLOCK_WIDTH));

        building.position.x = i + this.BLOCK_WIDTH / 2 + ((this.BLOCK_WIDTH / 2) * lotLayout.offsetFromBlockCenterX);
        building.scale.y =  (Math.random() * maxHeight) + this.MIN_BUILDING_HEIGHT;
        building.position.y = building.scale.y / 2;
        building.position.z = j + this.BLOCK_DEPTH / 2 + ((this.BLOCK_DEPTH / 2) * lotLayout.offsetFromBlockCenterZ);

        var index = Math.floor(Math.random() * this.MAX_BUILDING_MATERIALS);
        THREE.GeometryUtils.merge(buildingGeometries[index], building);
      }
    }
  }

  for (var i = 0; i < this.MAX_BUILDING_MATERIALS; i++) {
    scene.add(new THREE.Mesh(buildingGeometries[i], buildingMaterials[i]));
  }

  return scene;
}
<commit_msg>Extracting code out to dedicated methods.<commit_after>function City() {
  this.LOT_WIDTH = 1;
  this.LOT_DEPTH = 1;
  this.STREET_WIDTH = 2;
  this.STREET_DEPTH = 2;
  this.BLOCK_WIDTH = 4;
  this.BLOCK_DEPTH = 4;
  this.BLOCK_ROWS = 60;
  this.BLOCK_COLUMNS = 20;
  this.MIN_BUILDING_HEIGHT = 0.5;
  this.MAX_BUILDING_HEIGHT = 20;
  this.MAX_BUILDING_MATERIALS = 50;
  this.TOTAL_SCENE_WIDTH = (this.BLOCK_WIDTH * this.BLOCK_ROWS) + (this.STREET_WIDTH * (this.BLOCK_ROWS - 1));
  this.HALF_SCENE_WIDTH = this.TOTAL_SCENE_WIDTH / 2;
  this.TOTAL_SCENE_DEPTH = (this.BLOCK_DEPTH * this.BLOCK_COLUMNS) + (this.STREET_DEPTH * (this.BLOCK_COLUMNS - 1));
  this.HALF_SCENE_DEPTH = this.TOTAL_SCENE_DEPTH / 2;

  this.BLOCK_LAYOUTS = [
                        [ { width: 1.0, depth: 1.0, offsetFromBlockCenterX: 0.0, offsetFromBlockCenterZ: 0.0 } ],
                        [ { width: 0.5, depth: 1.0, offsetFromBlockCenterX: -0.5, offsetFromBlockCenterZ: 0.0 },
                          { width: 0.5, depth: 1.0, offsetFromBlockCenterX: 0.5, offsetFromBlockCenterZ: 0.0 } ],
                        [ { width: 1.0, depth: 0.5, offsetFromBlockCenterX: 0.0, offsetFromBlockCenterZ: -0.5 },
                          { width: 1.0, depth: 0.5, offsetFromBlockCenterX: 0.0, offsetFromBlockCenterZ: 0.5 } ],
                        [ { width: 0.5, depth: 1.0, offsetFromBlockCenterX: -0.5, offsetFromBlockCenterZ: 0.0 },
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: 0.5, offsetFromBlockCenterZ: -0.5},
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: 0.5, offsetFromBlockCenterZ: 0.5} ],
                        [ { width: 0.5, depth: 0.5, offsetFromBlockCenterX: -0.5, offsetFromBlockCenterZ: -0.5 },
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: -0.5, offsetFromBlockCenterZ: 0.5},
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: 0.5, offsetFromBlockCenterZ: -0.5},
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: 0.5, offsetFromBlockCenterZ: 0.5} ],
                        [ { width: (1 / 3), depth: 0.5, offsetFromBlockCenterX: -(2 / 3), offsetFromBlockCenterZ: 0.5 },
                          { width: (1 / 3), depth: 0.5, offsetFromBlockCenterX: 0.0, offsetFromBlockCenterZ: 0.5},
                          { width: (1 / 3), depth: 0.5, offsetFromBlockCenterX: (2 / 3), offsetFromBlockCenterZ: 0.5},
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: -0.5, offsetFromBlockCenterZ: -0.5},
                          { width: 0.5, depth: 0.5, offsetFromBlockCenterX: 0.5, offsetFromBlockCenterZ: -0.5} ],
                      ];
}

City.prototype.buildScene = function() {
  var scene = new THREE.Scene();

  var originMaterial = new THREE.MeshLambertMaterial({ color: 0xf32920 });
  var origin = new THREE.Mesh(new THREE.SphereGeometry(0.5, 10, 10), originMaterial);
  scene.add(origin);

  var groundMaterial = new THREE.MeshBasicMaterial({ color: 0x777777 });
  var ground = new THREE.Mesh(new THREE.PlaneGeometry(this.TOTAL_SCENE_WIDTH * 5, this.TOTAL_SCENE_DEPTH * 5), groundMaterial);
  ground.rotation.x = -(Math.PI / 2);
  scene.add(ground);

  var buildingMaterials = this.buildMaterials();
  var buildingGeometries = this.buildGeometries();

  // Loop through the lower left corner of each block
  for (var i = -(this.HALF_SCENE_WIDTH); i < this.HALF_SCENE_WIDTH; i += this.BLOCK_WIDTH + this.STREET_WIDTH) {
    for (var j = -(this.HALF_SCENE_DEPTH); j < this.HALF_SCENE_DEPTH; j += this.BLOCK_DEPTH + this.STREET_DEPTH) {

      var building;
      var blockLayout = this.BLOCK_LAYOUTS[Math.floor(Math.random() * this.BLOCK_LAYOUTS.length)];
      for (var layoutIndex = 0; layoutIndex < blockLayout.length; layoutIndex++) {
        var lotLayout = blockLayout[layoutIndex];
        var maxHeightI = this.MAX_BUILDING_HEIGHT * ((this.HALF_SCENE_WIDTH - Math.abs(i)) / this.HALF_SCENE_WIDTH);
        var maxHeightJ = this.MAX_BUILDING_HEIGHT * ((this.HALF_SCENE_DEPTH - Math.abs(j)) / this.HALF_SCENE_DEPTH);
        var maxHeight = Math.min(maxHeightI, maxHeightJ);
        var buildingHeight = Math.floor((Math.random() * maxHeight - this.MIN_BUILDING_HEIGHT)) + this.MIN_BUILDING_HEIGHT;

        var building = this.generateBuilding(i, maxHeight, j, lotLayout);

        var index = Math.floor(Math.random() * this.MAX_BUILDING_MATERIALS);
        THREE.GeometryUtils.merge(buildingGeometries[index], building);
      }
    }
  }

  for (var i = 0; i < this.MAX_BUILDING_MATERIALS; i++) {
    scene.add(new THREE.Mesh(buildingGeometries[i], buildingMaterials[i]));
  }

  return scene;
}

City.prototype.buildMaterials = function() {
  var buildingMaterials = [];

  for (var i = 0; i < this.MAX_BUILDING_MATERIALS; i++) {
    var r = Math.random();
    var g = Math.random();
    var b = Math.random();
    var buildingColor = new THREE.Color(0xffffff).setRGB(r, g, b);

    buildingMaterials.push(new THREE.MeshLambertMaterial({ color: buildingColor.getHex() }));
  }

  return buildingMaterials;
}

City.prototype.buildGeometries = function() {
  var buildingGeometries = [];

  for (var i = 0; i < this.MAX_BUILDING_MATERIALS; i++) {
    buildingGeometries.push(new THREE.Geometry());
  }

  return buildingGeometries;
}

City.prototype.generateBuilding = function(x, maxY, z, lotLayout) {
  var building = new THREE.Mesh(new THREE.CubeGeometry(lotLayout.width * this.BLOCK_WIDTH, 1, lotLayout.depth * this.BLOCK_WIDTH));

  building.position.x = x + this.BLOCK_WIDTH / 2 + ((this.BLOCK_WIDTH / 2) * lotLayout.offsetFromBlockCenterX);
  building.scale.y =  (Math.random() * maxY) + this.MIN_BUILDING_HEIGHT;
  building.position.y = building.scale.y / 2;
  building.position.z = z + this.BLOCK_DEPTH / 2 + ((this.BLOCK_DEPTH / 2) * lotLayout.offsetFromBlockCenterZ);

  return building;
}

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from '../../../prop_types';
import $ from 'jquery';
import i18n from '../../../i18n';
import { autobind, mixin } from '../../../utils/decorators';

import { InputSelectOption } from '../../../components';

import {
  CssClassMixin,
  InputComponentMixin,
  SelectComponentMixin,
  InputSelectActionsListenerMixin,
  MaterializeSelectMixin
} from '../../../mixins';

@mixin(
  CssClassMixin,
  InputComponentMixin,
  SelectComponentMixin,
  InputSelectActionsListenerMixin,
  MaterializeSelectMixin
)
export default class InputSelect extends Component {
  static propTypes = {
    includeBlank: PropTypes.bool,
    blankText: PropTypes.localizedString,
  };

  static defaultProps = {
    includeBlank: true,
    themeClassKey: 'input.select',
    blankText: 'select',
  };

  componentDidMount() {
    const valuesSelect = ReactDOM.findDOMNode(this.refs.select);
    const $form = $(valuesSelect.form);
    $form.on('reset', this.clearSelection);
  }

  componentWillUnmount() {
    const valuesSelect = ReactDOM.findDOMNode(this.refs.select);
    const $form = $(valuesSelect.form);
    $form.off('reset', this.clearSelection);
  }

  clearSelection() {
    this.setState({
      value: [],
    }, this.triggerDependableChanged);
  }

  selectedValue() {
    let value = this.state.value;
    Console.log(value)
    if (!this.props.multiple) {
      value = value[0];
    }

    return value;
  }

  @autobind
  handleChange(event) {
    const selectElement = ReactDOM.findDOMNode(this.refs.select);
    const newValue = this.ensureIsArray(selectElement.value);
    this.props.onChange(event, newValue, this);

    if(!event.isDefaultPrevented()) {
      this.setState({
        value: newValue
      }, this.triggerDependableChanged);
    }
  }

  renderOptions() {
    const selectOptions = [];
    const options = this.state.options;

    if (this.props.includeBlank) {
      selectOptions.push(
        <InputSelectOption
          name={i18n.t(this.props.blankText)}
          value=""
          key="empty_option"
        />
      );
    }

    for (let i = 0; i < options.length; i++) {
      const optionProps = options[i];
      selectOptions.push(<InputSelectOption {...optionProps} key={optionProps.name} />);
    }

    return selectOptions;
  }

  render() {
    return (
      <select
        id={this.props.id}
        name={this.props.name}
        value={this.selectedValue()}
        onChange={this.handleChange}
        disabled={this.isDisabled() || this.props.readOnly}
        className={this.className()}
        ref="select"
      >
        {this.renderOptions()}
      </select>
    );
  }
}
<commit_msg>	Teste inputselect no método selectedvalue.<commit_after>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from '../../../prop_types';
import $ from 'jquery';
import i18n from '../../../i18n';
import { autobind, mixin } from '../../../utils/decorators';

import { InputSelectOption } from '../../../components';

import {
  CssClassMixin,
  InputComponentMixin,
  SelectComponentMixin,
  InputSelectActionsListenerMixin,
  MaterializeSelectMixin
} from '../../../mixins';

@mixin(
  CssClassMixin,
  InputComponentMixin,
  SelectComponentMixin,
  InputSelectActionsListenerMixin,
  MaterializeSelectMixin
)
export default class InputSelect extends Component {
  static propTypes = {
    includeBlank: PropTypes.bool,
    blankText: PropTypes.localizedString,
  };

  static defaultProps = {
    includeBlank: true,
    themeClassKey: 'input.select',
    blankText: 'select',
  };

  componentDidMount() {
    const valuesSelect = ReactDOM.findDOMNode(this.refs.select);
    const $form = $(valuesSelect.form);
    $form.on('reset', this.clearSelection);
  }

  componentWillUnmount() {
    const valuesSelect = ReactDOM.findDOMNode(this.refs.select);
    const $form = $(valuesSelect.form);
    $form.off('reset', this.clearSelection);
  }

  clearSelection() {
    this.setState({
      value: [],
    }, this.triggerDependableChanged);
  }

  selectedValue() {
    let value = this.state.value;
    Console.log(value)
    if (!this.props.multiple) {
      Console.log(value)
      value = value[0];
    }

    return value;
  }

  @autobind
  handleChange(event) {
    const selectElement = ReactDOM.findDOMNode(this.refs.select);
    const newValue = this.ensureIsArray(selectElement.value);
    this.props.onChange(event, newValue, this);

    if(!event.isDefaultPrevented()) {
      this.setState({
        value: newValue
      }, this.triggerDependableChanged);
    }
  }

  renderOptions() {
    const selectOptions = [];
    const options = this.state.options;

    if (this.props.includeBlank) {
      selectOptions.push(
        <InputSelectOption
          name={i18n.t(this.props.blankText)}
          value=""
          key="empty_option"
        />
      );
    }

    for (let i = 0; i < options.length; i++) {
      const optionProps = options[i];
      selectOptions.push(<InputSelectOption {...optionProps} key={optionProps.name} />);
    }

    return selectOptions;
  }

  render() {
    return (
      <select
        id={this.props.id}
        name={this.props.name}
        value={this.selectedValue()}
        onChange={this.handleChange}
        disabled={this.isDisabled() || this.props.readOnly}
        className={this.className()}
        ref="select"
      >
        {this.renderOptions()}
      </select>
    );
  }
}
<|endoftext|>


<commit_before>'use strict';

function AnatoliaTemplate(options) {
    this._template = options.template;
    this._data = options.data;
    this._methods = options.methods;
}

AnatoliaTemplate.prototype.constructor = AnatoliaTemplate;

AnatoliaTemplate.prototype.parseAndReplace = function () {
    var context = this;

    var component = document.createElement('template');
    component.innerHTML = context._template;

    var elements = component.content.querySelectorAll("[a-for]");

    if (elements.length) {
        elements.forEach(function (element) {
            var forAttribute = element.getAttribute('a-for').split(' ');
            var dataKey = forAttribute[2];
            var dataItem = forAttribute[0];

            var state = context._findByKeyArray(context._data, dataKey.split('.'));

            if (state instanceof Array) {
                var elementCount = state.length;

                var tempElement = "";

                for (var i = 1; i <= elementCount; i++) {
                    tempElement += element.outerHTML;
                }

                var newElement = document.createElement('template');
                newElement.innerHTML = tempElement;

                element.parentElement.append(newElement.content);
            }
        });
    }

    context._template = component.innerHTML;

    var matchList = [];
    var expressionRegex = /{{\s*([^}]+)\s*}}/g;
    var matcher;

    while (matcher = expressionRegex.exec(context._template)) {
        var obj = {};
        obj.searched = matcher[0];
        obj.replaced = matcher[1];

        matchList.push(obj);
    }

    matchList.forEach(function (matching) {
        context._template = context._template.replace(matching.searched, context._flatten(context._data)[matching.replaced]);
    });

    return context;
};

AnatoliaTemplate.prototype.bindMethods = function (bindMethods) {
    var context = this;

    var component = document.createElement('template');
    component.innerHTML = context._template;

    for (var i in bindMethods) {
        var methods = bindMethods[i];

        for (var j in methods) {
            var fn = methods[j];

            var targetElements = component.content.querySelectorAll(i);

            targetElements.forEach(function (element) {
                element.addEventListener(j, fn);
            });
        }
    }

    return component;
};

AnatoliaTemplate.prototype.listen = function () {
    return this._template;
};

AnatoliaTemplate.prototype._flatten = function (obj) {
    var toReturn = {};

    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;

        if ((typeof obj[i]) == 'object') {
            var flatObject = this._flatten(obj[i]);
            for (var x in flatObject) {
                if (!flatObject.hasOwnProperty(x)) continue;

                toReturn[i + '.' + x] = flatObject[x];
            }
        } else {
            toReturn[i] = obj[i];
        }
    }
    return toReturn;
};

AnatoliaTemplate.prototype._findByKeyArray = function (state, keys) {
    var newState = null;

    for (var i in keys) {
        var key = keys[i];

        if (newState === null) {
            newState = state[key];
        } else {
            newState = newState[key];
        }
    }

    return newState;
};<commit_msg>revert<commit_after>'use strict';

function AnatoliaTemplate(options) {
    this._template = options.template;
    this._data = options.data;
    this._methods = options.methods;
}

AnatoliaTemplate.prototype.constructor = AnatoliaTemplate;

AnatoliaTemplate.prototype.parseAndReplace = function () {
    var context = this;

    var matchList = [];
    var expressionRegex = /{{\s*([^}]+)\s*}}/g;
    var matcher;

    while (matcher = expressionRegex.exec(context._template)) {
        var obj = {};
        obj.searched = matcher[0];
        obj.replaced = matcher[1];

        matchList.push(obj);
    }

    matchList.forEach(function (matching) {
        context._template = context._template.replace(matching.searched, context._flatten(context._data)[matching.replaced]);
    });

    return context;
};

AnatoliaTemplate.prototype.bindMethods = function (bindMethods) {
    var context = this;

    var component = document.createElement('template');
    component.innerHTML = context._template;

    for (var i in bindMethods) {
        var methods = bindMethods[i];

        for (var j in methods) {
            var fn = methods[j];

            var targetElements = component.content.querySelectorAll(i);

            targetElements.forEach(function (element) {
                element.addEventListener(j, fn);
            });
        }
    }

    return component;
};

AnatoliaTemplate.prototype.listen = function () {
    return this._template;
};

AnatoliaTemplate.prototype._flatten = function (obj) {
    var toReturn = {};

    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;

        if ((typeof obj[i]) == 'object') {
            var flatObject = this._flatten(obj[i]);
            for (var x in flatObject) {
                if (!flatObject.hasOwnProperty(x)) continue;

                toReturn[i + '.' + x] = flatObject[x];
            }
        } else {
            toReturn[i] = obj[i];
        }
    }
    return toReturn;
};

AnatoliaTemplate.prototype._findByKeyArray = function (state, keys) {
    var newState = null;

    for (var i in keys) {
        var key = keys[i];

        if (newState === null) {
            newState = state[key];
        } else {
            newState = newState[key];
        }
    }

    return newState;
};<|endoftext|>


<commit_before>/**
* bSlideer
* Desctiption: simple slider for jQuery
* Features: auto sliding, left/right controlls, bullet controls
* Author: Jiri Benes
* Version: 1.0.5
* TODO:
* - bullets support
* - autoswitch postponing
* - disabling loop
* BUG
* - fix integer step
*
* Usage:
* 	DOM structure:
* 		.bslider [1]
*			.window [0/1]
*				.frame [1]
*					.item [1..n]
*				.controlls [0/1]
*					.left [0/1]
*					.right [0/1]
*					.bullets [1]
*						.bullet [0..n]
*	CSS:
*		.slider {
*		    position: relative;
*		    overflow: hidden;
*
*		    .item {
*		        position: relative;
*		        float: left;
*		    }
*
*		    .frame {
*		        position: relative;
*		        overflow: hidden;
*		    }
*		}
*	JS:
*		$('.slider').bSlider();
*		or
*		$('.slider').bSlider({
*			speed: 500, // sets item speed
*			auto: false, // allow auto switching. False for disabling, int for delay in ms
*			autoHeight: true, // adjust slider height after item switch
*			itemMaxWidth: false, // set window width as item width (width 100% is not posible since frame width is sum of items width )
*			controlsMaxWidth: false, // controlls element gets 100% width
*			step: false, // length of one move. false for item width, int for pixel
*			//fixedWidth: true, // all items have same width (better performance)
*			onFinishStop: false,
*			left: false, // example '#left-buttom' jQuery selector for left control, false if is used default DOM structure as above
*			right: false, // example '#right-buttom' jQuery selector for right control, false if is used default DOM structure as above
*			stepCount: 1, // int, how many items are slided. Default value 1
*			method: 'slide', // slide or fade
*			onReady: function() {},
*			onSlideBegin: function() {},
*			onSlideComplete: function() {},
*			onFinish: function() {}
*		});
*/

(function ( $ ) {
$.fn.bSlider = function( options ) {

	var settings = $.extend({
		speed: 500,
		auto: false,
		autoHeight: true,
		itemMaxWidth: false,
		controlsMaxWidth: false,
		step: false,
		onFinishStop: false,
		left: false,
		right: false,
		stepCount: 1,
		method: 'slide',
		onReady: function() {},
		onSlideBegin: function() {},
		onSlideComplete: function() {},
		onFinish: function() {}
		//fixedWidth: true
	}, options );

	var _name = 'bSlider';

	var slide = function(slider, way, callback) {
		// get slider data
		if(typeof way === 'undefined') {
			var way = slider[1];
			var slider = slider[0];
		}
		var data = slider.data()[_name];
		var settings = data.settings;
		// choose active element
		if(way == 'left') {
			if(data.active < settings.stepCount) {
				var active = data.count - settings.stepCount;
			}
			else var active = data.active - settings.stepCount;
		} else if (way == 'right') {
			if(data.active >= data.count - data.size) {
				var active =  0;
			}
			else var active = data.active + settings.stepCount;
		} else {
			var active = way;
		}
		active = Math.ceil(active);

		// get choosen item
		var item = $('.item:nth-child('+(active+1)+')', slider);
		if($('.bullets', slider).length > 0) {
			$('.bullet:nth-child('+(active+1)+')', slider).addClass('active').siblings().removeClass('active');
		}

		settings.onSlideBegin.call( this, slider );

		// moove frame
		animateCss = {
			left: -1 * active * data.step
		}

		if(settings.method == 'fade') {
			//item.fadeIn(settings.speed).siblings().fadeOut(settings.speed);
			item.stop().fadeTo(
				settings.speed,
				1,
				function() {

					settings.onSlideComplete.call( this, slider );

					if(data.settings.onFinishStop && data.active +1 == data.count) {
						settings.onFinish.call( this, slider );
					}

					if(data.auto !== false && (!data.settings.onFinishStop || data.active +1 != data.count)) {
						clearInterval(data.auto);
						//data.auto = setInterval(slide, settings.auto, [slider, 'right']);
						var param = [slider, 'right'];
						data.auto = setTimeout( (function(param) {
						    return function() {
						        slide(param);
						    };
						})(param) , settings.auto);
					}
				}
		 	).siblings().stop().fadeTo(
				settings.speed,
				0
		 	);
		} else {
			data.frame.animate(
				animateCss,
				{
					duration: settings.speed,
					queue: false,
					complete: function() {

						settings.onSlideComplete.call( this, slider );

						if(data.settings.onFinishStop && data.active +1 == data.count) {
							settings.onFinish.call( this, slider );
						}

						if(data.auto !== false && (!data.settings.onFinishStop || data.active +1 != data.count)) {
							clearInterval(data.auto);
							//data.auto = setInterval(slide, settings.auto, [slider, 'right']);
							var param = [slider, 'right'];
							data.auto = setTimeout( (function(param) {
							    return function() {
							        slide(param);
							    };
							})(param) , settings.auto);
						}
					}
			 	}
		 	);
		}

		// change class of selected item
		item.addClass("active").siblings().removeClass("active");
		// set frame height if wanted
		if(settings.autoHeight) {
			//alert(item.html());
			data.frame.animate({height: item.outerHeight(true)}, { duration: settings.speed, queue: false });
		}

		// save data again
		data.active = active;
		slider.data(_name, data);
	}

	return this.each(function() {
		// data object
		var data = {}
		// slider object
		$this = $(this);

		var actualSlider = $(this);
		// get active element
		if($('.item.active', $this).length == 0) {
			active = 0;
		} else {
			active = $('.item.active', $this).index();
		}

		if (!settings.left) {
			settings.left = $('.controls .left', $(this));
		}
		else {
			settings.left = $(settings.left);
		}

		if (!settings.right) {
			settings.right = $('.controls .right', $(this));
		}
		else {
			settings.right = $(settings.right);
		}
		// autoresizing controlls wrapper, if allowed
		if(settings.controlsMaxWidth) {
			var controls = $('.controls', $this);

			controls.width(parseInt($this.width()));

			controls.addClass(_name+'-controls-resize');

			$(window).unbind('resize.'+_name+'-controls').bind('resize.'+_name+'-controls', function(e) {
				$('.'+_name+'-controls-resize').each(function() {
					var slider = $(this).parents('.bslider');
					$(this).width(parseInt(slider.width()));
				});
			});
		}

		controls.show();

		// set width of browser if allowed
		if(settings.itemMaxWidth) {
			$('.item', $this).width(parseInt($this.width()) - parseInt($('.item', $this).first().css('padding-left')) - parseInt($('.item', $this).first().css('padding-right')));

			$this.addClass(_name+'-resize');

			$(window).unbind('resize.'+_name).bind('resize.'+_name, function(e) {
				$('.'+_name+'-resize').each(function() {
					var slider = $(this);
					var data = slider.data()[_name];

					var width = slider.width();
					//slider.find('.item').width(parseInt(width) - parseInt($('.item', slider).first().css('padding-left')) - parseInt($('.item', slider).first().css('padding-right')));
					var new_width = parseInt(width) - parseInt($('.item', slider).first().css('padding-left')) - parseInt($('.item', slider).first().css('padding-right'));
					$('.item', slider).width(new_width);

					if(settings.method == 'fade') {
						data.frame.width(new_width);
					} else {
						data.frame.css({
							left: -1 * data.active * width,
							width: data.count * width
						});
					}

					if(!data.settings.step) var step = $('.item', slider).first().outerWidth(true);

					data.step = step;
					data.width = width;
					slider.data(_name, data);
				});

			});
		}
		var frame_width = 0;
		// loop items, set items count
		var count = $('.item', $this).each(function() {
			frame_width += $(this).outerWidth(true);
			// copy data-background from item as their bg img
			var attr = $(this).attr('data-background');
			if (typeof attr !== 'undefined' && attr !== false) {
				$(this).css('background-image', 'url('+$(this).attr('data-background')+')');
			}
			// if we have fade effect, set item absolute
			if(settings.method == 'fade') {
				$(this).css({
					'position': 'absolute',
					'left': '0',
					'top': '0'
				});
			}
		}).length;
		// get item width
		var item = $('.item:nth-child('+(active+1)+')', $this);
		var frame = $('.frame', $this);
		if(settings.step) var step = settings.step;
		else var step = item.outerWidth(true);
		var height = item.outerHeight(true);
		if($('.window', $this).length > 0) var size = $('.window', $this).outerWidth(true) / item.outerWidth(true);
		else var size = $this.outerWidth(true) / item.outerWidth(true);

		// if we have fade effect, set frame width as item width
		if(settings.method == 'fade') {
			frame_width = item.outerWidth(true);
		}
		// reset frame position
		frame.css({
			left: -1 * active * step,
			height: height,
			width: frame_width
		});
		// set active class to curent item
		item.addClass("active").siblings().removeClass("active");
		if(settings.method == 'fade') {
			item.show().siblings().hide();
		}

		// bing left event
		settings.left.bind('click.'+_name, function() {
			slide(actualSlider, 'left');
		});
		// bind right event
		settings.right.bind('click.'+_name, function() {
			slide(actualSlider, 'right');
		});
		// bind bullet event
		$('.controls .bullet', $this).bind('click.'+_name, function() {
			slide($(this).parents('.bslider'), $(this).index());
		});

		$('.rewind', $this).bind('click.'+_name, function() {
			slide($(this).parents('.bslider'), 0);
		});

		$('.bullet:nth-child('+(active+1)+')', $this).addClass('active');

		settings.onReady.call( this, $this );
		// bind auto slide
		if(settings.auto) {
			//data.auto = setInterval(slide, settings.auto, [$this, 'right']);
			var param = [$this, 'right'];
			data.auto = setTimeout( (function(param) {
			    return function() {
			        slide(param);
			    };
			})(param) , settings.auto);
		} else {
			data.auto = false;
		}

		data.active = active;
		data.count = count;
		data.step = step;
		data.size = size;
		data.frame = frame;
		data.settings = settings;

		$this.data(_name, data);

	});

};
}( jQuery ));<commit_msg>controls show fix<commit_after>/**
* bSlideer
* Desctiption: simple slider for jQuery
* Features: auto sliding, left/right controlls, bullet controls
* Author: Jiri Benes
* Version: 1.0.5
* TODO:
* - bullets support
* - autoswitch postponing
* - disabling loop
* BUG
* - fix integer step
*
* Usage:
* 	DOM structure:
* 		.bslider [1]
*			.window [0/1]
*				.frame [1]
*					.item [1..n]
*				.controlls [0/1]
*					.left [0/1]
*					.right [0/1]
*					.bullets [1]
*						.bullet [0..n]
*	CSS:
*		.slider {
*		    position: relative;
*		    overflow: hidden;
*
*		    .item {
*		        position: relative;
*		        float: left;
*		    }
*
*		    .frame {
*		        position: relative;
*		        overflow: hidden;
*		    }
*		}
*	JS:
*		$('.slider').bSlider();
*		or
*		$('.slider').bSlider({
*			speed: 500, // sets item speed
*			auto: false, // allow auto switching. False for disabling, int for delay in ms
*			autoHeight: true, // adjust slider height after item switch
*			itemMaxWidth: false, // set window width as item width (width 100% is not posible since frame width is sum of items width )
*			controlsMaxWidth: false, // controlls element gets 100% width
*			step: false, // length of one move. false for item width, int for pixel
*			//fixedWidth: true, // all items have same width (better performance)
*			onFinishStop: false,
*			left: false, // example '#left-buttom' jQuery selector for left control, false if is used default DOM structure as above
*			right: false, // example '#right-buttom' jQuery selector for right control, false if is used default DOM structure as above
*			stepCount: 1, // int, how many items are slided. Default value 1
*			method: 'slide', // slide or fade
*			onReady: function() {},
*			onSlideBegin: function() {},
*			onSlideComplete: function() {},
*			onFinish: function() {}
*		});
*/

(function ( $ ) {
$.fn.bSlider = function( options ) {

	var settings = $.extend({
		speed: 500,
		auto: false,
		autoHeight: true,
		itemMaxWidth: false,
		controlsMaxWidth: false,
		step: false,
		onFinishStop: false,
		left: false,
		right: false,
		stepCount: 1,
		method: 'slide',
		onReady: function() {},
		onSlideBegin: function() {},
		onSlideComplete: function() {},
		onFinish: function() {}
		//fixedWidth: true
	}, options );

	var _name = 'bSlider';

	var slide = function(slider, way, callback) {
		// get slider data
		if(typeof way === 'undefined') {
			var way = slider[1];
			var slider = slider[0];
		}
		var data = slider.data()[_name];
		var settings = data.settings;
		// choose active element
		if(way == 'left') {
			if(data.active < settings.stepCount) {
				var active = data.count - settings.stepCount;
			}
			else var active = data.active - settings.stepCount;
		} else if (way == 'right') {
			if(data.active >= data.count - data.size) {
				var active =  0;
			}
			else var active = data.active + settings.stepCount;
		} else {
			var active = way;
		}
		active = Math.ceil(active);

		// get choosen item
		var item = $('.item:nth-child('+(active+1)+')', slider);
		if($('.bullets', slider).length > 0) {
			$('.bullet:nth-child('+(active+1)+')', slider).addClass('active').siblings().removeClass('active');
		}

		settings.onSlideBegin.call( this, slider );

		// moove frame
		animateCss = {
			left: -1 * active * data.step
		}

		if(settings.method == 'fade') {
			//item.fadeIn(settings.speed).siblings().fadeOut(settings.speed);
			item.stop().fadeTo(
				settings.speed,
				1,
				function() {

					settings.onSlideComplete.call( this, slider );

					if(data.settings.onFinishStop && data.active +1 == data.count) {
						settings.onFinish.call( this, slider );
					}

					if(data.auto !== false && (!data.settings.onFinishStop || data.active +1 != data.count)) {
						clearInterval(data.auto);
						//data.auto = setInterval(slide, settings.auto, [slider, 'right']);
						var param = [slider, 'right'];
						data.auto = setTimeout( (function(param) {
						    return function() {
						        slide(param);
						    };
						})(param) , settings.auto);
					}
				}
		 	).siblings().stop().fadeTo(
				settings.speed,
				0
		 	);
		} else {
			data.frame.animate(
				animateCss,
				{
					duration: settings.speed,
					queue: false,
					complete: function() {

						settings.onSlideComplete.call( this, slider );

						if(data.settings.onFinishStop && data.active +1 == data.count) {
							settings.onFinish.call( this, slider );
						}

						if(data.auto !== false && (!data.settings.onFinishStop || data.active +1 != data.count)) {
							clearInterval(data.auto);
							//data.auto = setInterval(slide, settings.auto, [slider, 'right']);
							var param = [slider, 'right'];
							data.auto = setTimeout( (function(param) {
							    return function() {
							        slide(param);
							    };
							})(param) , settings.auto);
						}
					}
			 	}
		 	);
		}

		// change class of selected item
		item.addClass("active").siblings().removeClass("active");
		// set frame height if wanted
		if(settings.autoHeight) {
			//alert(item.html());
			data.frame.animate({height: item.outerHeight(true)}, { duration: settings.speed, queue: false });
		}

		// save data again
		data.active = active;
		slider.data(_name, data);
	}

	return this.each(function() {
		// data object
		var data = {}
		// slider object
		$this = $(this);

		var actualSlider = $(this);
		// get active element
		if($('.item.active', $this).length == 0) {
			active = 0;
		} else {
			active = $('.item.active', $this).index();
		}

		if (!settings.left) {
			settings.left = $('.controls .left', $(this));
		}
		else {
			settings.left = $(settings.left);
		}

		if (!settings.right) {
			settings.right = $('.controls .right', $(this));
		}
		else {
			settings.right = $(settings.right);
		}
		// autoresizing controlls wrapper, if allowed
		if(settings.controlsMaxWidth) {
			var controls = $('.controls', $this);

			controls.width(parseInt($this.width()));

			controls.addClass(_name+'-controls-resize');

			$(window).unbind('resize.'+_name+'-controls').bind('resize.'+_name+'-controls', function(e) {
				$('.'+_name+'-controls-resize').each(function() {
					var slider = $(this).parents('.bslider');
					$(this).width(parseInt(slider.width()));
				});
			});

			controls.show();
		}

		// set width of browser if allowed
		if(settings.itemMaxWidth) {
			$('.item', $this).width(parseInt($this.width()) - parseInt($('.item', $this).first().css('padding-left')) - parseInt($('.item', $this).first().css('padding-right')));

			$this.addClass(_name+'-resize');

			$(window).unbind('resize.'+_name).bind('resize.'+_name, function(e) {
				$('.'+_name+'-resize').each(function() {
					var slider = $(this);
					var data = slider.data()[_name];

					var width = slider.width();
					//slider.find('.item').width(parseInt(width) - parseInt($('.item', slider).first().css('padding-left')) - parseInt($('.item', slider).first().css('padding-right')));
					var new_width = parseInt(width) - parseInt($('.item', slider).first().css('padding-left')) - parseInt($('.item', slider).first().css('padding-right'));
					$('.item', slider).width(new_width);

					if(settings.method == 'fade') {
						data.frame.width(new_width);
					} else {
						data.frame.css({
							left: -1 * data.active * width,
							width: data.count * width
						});
					}

					if(!data.settings.step) var step = $('.item', slider).first().outerWidth(true);

					data.step = step;
					data.width = width;
					slider.data(_name, data);
				});

			});
		}
		var frame_width = 0;
		// loop items, set items count
		var count = $('.item', $this).each(function() {
			frame_width += $(this).outerWidth(true);
			// copy data-background from item as their bg img
			var attr = $(this).attr('data-background');
			if (typeof attr !== 'undefined' && attr !== false) {
				$(this).css('background-image', 'url('+$(this).attr('data-background')+')');
			}
			// if we have fade effect, set item absolute
			if(settings.method == 'fade') {
				$(this).css({
					'position': 'absolute',
					'left': '0',
					'top': '0'
				});
			}
		}).length;
		// get item width
		var item = $('.item:nth-child('+(active+1)+')', $this);
		var frame = $('.frame', $this);
		if(settings.step) var step = settings.step;
		else var step = item.outerWidth(true);
		var height = item.outerHeight(true);
		if($('.window', $this).length > 0) var size = $('.window', $this).outerWidth(true) / item.outerWidth(true);
		else var size = $this.outerWidth(true) / item.outerWidth(true);

		// if we have fade effect, set frame width as item width
		if(settings.method == 'fade') {
			frame_width = item.outerWidth(true);
		}
		// reset frame position
		frame.css({
			left: -1 * active * step,
			height: height,
			width: frame_width
		});
		// set active class to curent item
		item.addClass("active").siblings().removeClass("active");
		if(settings.method == 'fade') {
			item.show().siblings().hide();
		}

		// bing left event
		settings.left.bind('click.'+_name, function() {
			slide(actualSlider, 'left');
		});
		// bind right event
		settings.right.bind('click.'+_name, function() {
			slide(actualSlider, 'right');
		});
		// bind bullet event
		$('.controls .bullet', $this).bind('click.'+_name, function() {
			slide($(this).parents('.bslider'), $(this).index());
		});

		$('.rewind', $this).bind('click.'+_name, function() {
			slide($(this).parents('.bslider'), 0);
		});

		$('.bullet:nth-child('+(active+1)+')', $this).addClass('active');

		settings.onReady.call( this, $this );
		// bind auto slide
		if(settings.auto) {
			//data.auto = setInterval(slide, settings.auto, [$this, 'right']);
			var param = [$this, 'right'];
			data.auto = setTimeout( (function(param) {
			    return function() {
			        slide(param);
			    };
			})(param) , settings.auto);
		} else {
			data.auto = false;
		}

		data.active = active;
		data.count = count;
		data.step = step;
		data.size = size;
		data.frame = frame;
		data.settings = settings;

		$this.data(_name, data);

	});

};
}( jQuery ));<|endoftext|>


<commit_before>module.exports = function(msg) {

var request = require('request')
var user_name = ''
// Set the headers
var headers = {
    'User-Agent':       'Super Agent/0.0.1',
    'Content-Type':     'application/x-www-form-urlencoded'
}

// Configure the request
var options = {
    url: 'https://slack.com/api/users.info',
    method: 'POST',
    headers: headers,
    form: {'token': msg.meta.bot_token, 'user': msg.body.event.user}
}

// Start the request
user_name = request(options, function (error, response, body, callback) {
    //if (!error && response.statusCode == 200) {
        // Print out the response body
        var result = JSON.parse(body);
        user_name = result.user.name;
        callback(user_name);
    //}
});

};
<commit_msg>trying callbacks<commit_after>module.exports = function(msg, callback) {

var request = require('request')
var user_name = ''
// Set the headers
var headers = {
    'User-Agent':       'Super Agent/0.0.1',
    'Content-Type':     'application/x-www-form-urlencoded'
}

// Configure the request
var options = {
    url: 'https://slack.com/api/users.info',
    method: 'POST',
    headers: headers,
    form: {'token': msg.meta.bot_token, 'user': msg.body.event.user}
}

// Start the request
 request(options, function (error, response, body) {
    //if (!error && response.statusCode == 200) {
        // Print out the response body
        var result = JSON.parse(body);
        user_name = result.user.name;
        return callback(user_name)
    //}
});

};
<|endoftext|>