<commit_before>var get = Ember.get, set = Ember.set;

DS.DjangoTastypieAdapter = DS.RESTAdapter.extend({
  /**
    Set this parameter if you are planning to do cross-site
    requests to the destination domain. Remember trailing slash
  */
  serverDomain: null,

  /**
    This is the default Tastypie namespace found in the documentation.
    You may change it if necessary when creating the adapter
  */
  namespace: "api/v1",

  /**
    Bulk commits are not supported at this time by the adapter.
    Changing this setting will not work
  */
  bulkCommit: false,

  /**
    Tastypie returns the next URL when all the elements of a type
    cannot be fetched inside a single request. Unless you override this
    feature in Tastypie, you don't need to change this value. Pagination
    will work out of the box for findAll requests
  */
  since: 'next',

  /**
    Serializer object to manage JSON transformations
  */
  serializer: DS.DjangoTastypieSerializer,

  init: function() {
    var serializer,
        namespace;

    this._super();

    namespace = get(this, 'namespace');
    Em.assert("tastypie namespace parameter is mandatory.", !!namespace);

    // Make the adapter available for the serializer
    serializer = get(this, 'serializer');
    set(serializer, 'adapter', this);
    set(serializer, 'namespace', namespace);
  },

  /**
    Create a record in the Django server. POST actions must
    be enabled in the Resource
  */
  createRecord: function(store, type, record) {
    var data,
        root = this.rootForType(type);

    data = record.serialize();

    this.ajax(this.buildURL(root), "POST", {
      data: data,
      success: function(json) {
        this.didSaveRecord(store, type, record, json);
      }
    });
  },

  /**
    Edit a record in the Django server. PUT actions must
    be enabled in the Resource
  */
  updateRecord: function(store, type, record) {
    var id,
        data;

    id = Em.get(record, 'id');
    root = this.rootForType(type);

    data = record.serialize();

    this.ajax(this.buildURL(root, id), "PUT", {
      data: data,
      success: function(json) {
        this.didSaveRecord(store, type, record, json);
      }
    });
  },

  /**
    Delete a record in the Django server. DELETE actions
    must be enabled in the Resource
  */
  deleteRecord: function(store, type, record) {
    var id,
        root;

    id = get(record, 'id');
    root = this.rootForType(type);

    this.ajax(this.buildURL(root, id), "DELETE", {
      success: function(json) {
        this.didSaveRecord(store, type, record, json);
      }
    });
  },

  findMany: function(store, type, ids) {
    var url,
        root = this.rootForType(type);

    ids = this.serializeIds(ids);

    // FindMany array through subset of resources
    if (ids instanceof Array) {
      ids = "set/" + ids.join(";") + '/';
    }

    url = this.buildURL(root);
    url += ids;

    this.ajax(url, "GET", {
      success: function(json) {
        this.didFindMany(store, type, json);
      }
    });
  },

  didFindMany: function(store, type, json) {
    store.loadMany(type, json.objects);
  },

  didFindQuery: function(store, type, json, recordArray) {
    recordArray.load(json.objects);
  },

  buildURL: function(record, suffix) {
    var url = this._super(record, suffix);

    // Add the trailing slash to avoid setting requirement in Django.settings
    if (url.charAt(url.length -1) !== '/') {
      url += '/';
    }

    // Add the server domain if any
    if (!!this.serverDomain) {
      url = this.removeTrailingSlash(this.serverDomain) + url;
    }

    return url;
  },

  /**
     The actual nextUrl is being stored. The offset must be extracted from
     the string to do a new call.
     When there are remaining objects to be returned, Tastypie returns a
     `next` URL that in the meta header. Whenever there are no
     more objects to be returned, the `next` paramater value will be null.
     Instead of calculating the next `offset` each time, we store the nextUrl
     from which the offset will be extrated for the next request
  */
  sinceQuery: function(since) {
    var offsetParam,
        query;

    query = {};

    if (!!since) {
      offsetParam = since.match(/offset=(\d+)/);
      offsetParam = (!!offsetParam && !!offsetParam[1]) ? offsetParam[1] : null;
      query.offset = offsetParam;
    }

    return offsetParam ? query : null;
  },

  removeTrailingSlash: function(url) {
    if (url.charAt(url.length -1) === '/') {
      return url.slice(0, -1);
    }
    return url;
  },

  /**
    django-tastypie does not pluralize names for lists
  */
  pluralize: function(name) {
    return name;
  }
});
<commit_msg>createRecord success call didCreateRecord<commit_after>var get = Ember.get, set = Ember.set;

DS.DjangoTastypieAdapter = DS.RESTAdapter.extend({
  /**
    Set this parameter if you are planning to do cross-site
    requests to the destination domain. Remember trailing slash
  */
  serverDomain: null,

  /**
    This is the default Tastypie namespace found in the documentation.
    You may change it if necessary when creating the adapter
  */
  namespace: "api/v1",

  /**
    Bulk commits are not supported at this time by the adapter.
    Changing this setting will not work
  */
  bulkCommit: false,

  /**
    Tastypie returns the next URL when all the elements of a type
    cannot be fetched inside a single request. Unless you override this
    feature in Tastypie, you don't need to change this value. Pagination
    will work out of the box for findAll requests
  */
  since: 'next',

  /**
    Serializer object to manage JSON transformations
  */
  serializer: DS.DjangoTastypieSerializer,

  init: function() {
    var serializer,
        namespace;

    this._super();

    namespace = get(this, 'namespace');
    Em.assert("tastypie namespace parameter is mandatory.", !!namespace);

    // Make the adapter available for the serializer
    serializer = get(this, 'serializer');
    set(serializer, 'adapter', this);
    set(serializer, 'namespace', namespace);
  },

  /**
    Create a record in the Django server. POST actions must
    be enabled in the Resource
  */
  createRecord: function(store, type, record) {
    var data,
        root = this.rootForType(type);

    data = record.serialize();

    this.ajax(this.buildURL(root), "POST", {
      data: data,
      success: function(json) {
        this.didCreateRecord(store, type, record, json);
      }
    });
  },

  /**
    Edit a record in the Django server. PUT actions must
    be enabled in the Resource
  */
  updateRecord: function(store, type, record) {
    var id,
        data;

    id = Em.get(record, 'id');
    root = this.rootForType(type);

    data = record.serialize();

    this.ajax(this.buildURL(root, id), "PUT", {
      data: data,
      success: function(json) {
        this.didSaveRecord(store, type, record, json);
      }
    });
  },

  /**
    Delete a record in the Django server. DELETE actions
    must be enabled in the Resource
  */
  deleteRecord: function(store, type, record) {
    var id,
        root;

    id = get(record, 'id');
    root = this.rootForType(type);

    this.ajax(this.buildURL(root, id), "DELETE", {
      success: function(json) {
        this.didSaveRecord(store, type, record, json);
      }
    });
  },

  findMany: function(store, type, ids) {
    var url,
        root = this.rootForType(type);

    ids = this.serializeIds(ids);

    // FindMany array through subset of resources
    if (ids instanceof Array) {
      ids = "set/" + ids.join(";") + '/';
    }

    url = this.buildURL(root);
    url += ids;

    this.ajax(url, "GET", {
      success: function(json) {
        this.didFindMany(store, type, json);
      }
    });
  },

  didFindMany: function(store, type, json) {
    store.loadMany(type, json.objects);
  },

  didFindQuery: function(store, type, json, recordArray) {
    recordArray.load(json.objects);
  },

  buildURL: function(record, suffix) {
    var url = this._super(record, suffix);

    // Add the trailing slash to avoid setting requirement in Django.settings
    if (url.charAt(url.length -1) !== '/') {
      url += '/';
    }

    // Add the server domain if any
    if (!!this.serverDomain) {
      url = this.removeTrailingSlash(this.serverDomain) + url;
    }

    return url;
  },

  /**
     The actual nextUrl is being stored. The offset must be extracted from
     the string to do a new call.
     When there are remaining objects to be returned, Tastypie returns a
     `next` URL that in the meta header. Whenever there are no
     more objects to be returned, the `next` paramater value will be null.
     Instead of calculating the next `offset` each time, we store the nextUrl
     from which the offset will be extrated for the next request
  */
  sinceQuery: function(since) {
    var offsetParam,
        query;

    query = {};

    if (!!since) {
      offsetParam = since.match(/offset=(\d+)/);
      offsetParam = (!!offsetParam && !!offsetParam[1]) ? offsetParam[1] : null;
      query.offset = offsetParam;
    }

    return offsetParam ? query : null;
  },

  removeTrailingSlash: function(url) {
    if (url.charAt(url.length -1) === '/') {
      return url.slice(0, -1);
    }
    return url;
  },

  /**
    django-tastypie does not pluralize names for lists
  */
  pluralize: function(name) {
    return name;
  }
});
<|endoftext|>


<commit_before>import Ember from "ember-metal/core";
import run from "ember-metal/run_loop";
import EmberObject from "ember-runtime/system/object";
import jQuery from "ember-views/system/jquery";
import EmberView from "ember-views/views/view";
import { compile } from "ember-template-compiler";

var originalLookup = Ember.lookup;
var lookup, view;

QUnit.module("views/view/view_lifecycle_test - pre-render", {
  setup() {
    Ember.lookup = lookup = {};
  },

  teardown() {
    if (view) {
      run(function() {
        view.destroy();
      });
    }
    Ember.lookup = originalLookup;
  }
});

QUnit.test("should create and append a DOM element after bindings have synced", function() {
  var ViewTest;

  lookup.ViewTest = ViewTest = {};

  run(function() {
    ViewTest.fakeController = EmberObject.create({
      fakeThing: 'controllerPropertyValue'
    });

    view = EmberView.createWithMixins({
      fooBinding: 'ViewTest.fakeController.fakeThing',
      template: compile("{{view.foo}}")
    });

    ok(!view.get('element'), "precond - does not have an element before appending");

    // the actual render happens in the `render` queue, which is after the `sync`
    // queue where the binding is synced.
    view.append();
  });

  equal(view.$().text(), 'controllerPropertyValue', "renders and appends after bindings have synced");
});

QUnit.test("should throw an exception if trying to append a child before rendering has begun", function() {
  run(function() {
    view = EmberView.create();
  });

  throws(function() {
    view.appendChild(EmberView, {});
  }, null, "throws an error when calling appendChild()");
});

QUnit.test("should not affect rendering if rerender is called before initial render happens", function() {
  run(function() {
    view = EmberView.create({
      template: compile("Rerender me!")
    });

    view.rerender();
    view.append();
  });

  equal(view.$().text(), "Rerender me!", "renders correctly if rerender is called first");
});

QUnit.test("should not affect rendering if destroyElement is called before initial render happens", function() {
  run(function() {
    view = EmberView.create({
      template: compile("Don't destroy me!")
    });

    view.destroyElement();
    view.append();
  });

  equal(view.$().text(), "Don't destroy me!", "renders correctly if destroyElement is called first");
});

QUnit.module("views/view/view_lifecycle_test - in render", {
  setup() {

  },

  teardown() {
    if (view) {
      run(function() {
        view.destroy();
      });
    }
  }
});

QUnit.skip("rerender should throw inside a template", function() {
  throws(function() {
    run(function() {
      var renderCount = 0;
      view = EmberView.create({
        template(context, options) {
          var view = options.data.view;

          var child1 = view.appendChild(EmberView, {
            template(context, options) {
              renderCount++;
              options.data.buffer.push(String(renderCount));
            }
          });

          view.appendChild(EmberView, {
            template(context, options) {
              options.data.buffer.push("Inside child2");
              child1.rerender();
            }
          });
        }
      });

      view.appendTo("#qunit-fixture");
    });
  }, /Something you did caused a view to re-render after it rendered but before it was inserted into the DOM./);
});

QUnit.module("views/view/view_lifecycle_test - hasElement", {
  teardown() {
    if (view) {
      run(function() {
        view.destroy();
      });
    }
  }
});

QUnit.test("createElement puts the view into the hasElement state", function() {
  var hasCalledInsertElement = false;
  view = EmberView.create({
    didInsertElement() {
      hasCalledInsertElement = true;
    }
  });

  run(function() {
    view.createElement();
  });

  ok(!hasCalledInsertElement, 'didInsertElement is not called');
  equal(view.element.tagName, 'DIV', 'content is rendered');
});

QUnit.test("trigger rerender on a view in the hasElement state doesn't change its state to inDOM", function() {
  var hasCalledInsertElement = false;
  view = EmberView.create({
    didInsertElement() {
      hasCalledInsertElement = true;
    }
  });

  run(function() {
    view.createElement();
    view.rerender();
  });

  ok(!hasCalledInsertElement, 'didInsertElement is not called');
  equal(view.element.tagName, 'DIV', 'content is rendered');
});

QUnit.module("views/view/view_lifecycle_test - in DOM", {
  teardown() {
    if (view) {
      run(function() {
        view.destroy();
      });
    }
  }
});

QUnit.test("should throw an exception when calling appendChild when DOM element exists", function() {
  run(function() {
    view = EmberView.create({
      template: compile("Wait for the kick")
    });

    view.append();
  });

  throws(function() {
    view.appendChild(EmberView, {
      template: compile("Ah ah ah! You didn't say the magic word!")
    });
  }, null, "throws an exception when calling appendChild after element is created");
});

QUnit.skip("should replace DOM representation if rerender() is called after element is created", function() {
  run(function() {
    view = EmberView.create({
      template(context, options) {
        var buffer = options.data.buffer;
        var value = context.get('shape');

        buffer.push("Do not taunt happy fun "+value);
      },

      context: EmberObject.create({
        shape: 'sphere'
      })
    });

    view.append();
  });

  equal(view.$().text(), "Do not taunt happy fun sphere", "precond - creates DOM element");

  view.set('context.shape', 'ball');
  run(function() {
    view.rerender();
  });

  equal(view.$().text(), "Do not taunt happy fun ball", "rerenders DOM element when rerender() is called");
});

QUnit.test("should destroy DOM representation when destroyElement is called", function() {
  run(function() {
    view = EmberView.create({
      template: compile("Don't fear the reaper")
    });

    view.append();
  });

  ok(view.get('element'), "precond - generates a DOM element");

  run(function() {
    view.destroyElement();
  });

  ok(!view.get('element'), "destroys view when destroyElement() is called");
});

QUnit.test("should destroy DOM representation when destroy is called", function() {
  run(function() {
    view = EmberView.create({
      template: compile("
Don't fear the reaper
")
    });

    view.append();
  });

  ok(view.get('element'), "precond - generates a DOM element");

  run(function() {
    view.destroy();
  });

  ok(jQuery('#warning').length === 0, "destroys element when destroy() is called");
});

QUnit.test("should throw an exception if trying to append an element that is already in DOM", function() {
  run(function() {
    view = EmberView.create({
      template: compile('Broseidon, King of the Brocean')
    });

    view.append();
  });

  ok(view.get('element'), "precond - creates DOM element");

  throws(function() {
    run(function() {
      view.append();
    });
  }, null, "raises an exception on second append");
});

QUnit.module("views/view/view_lifecycle_test - destroyed");

QUnit.test("should throw an exception when calling appendChild after view is destroyed", function() {
  run(function() {
    view = EmberView.create({
      template: compile("Wait for the kick")
    });

    view.append();
  });

  run(function() {
    view.destroy();
  });

  throws(function() {
    view.appendChild(EmberView, {
      template: compile("Ah ah ah! You didn't say the magic word!")
    });
  }, null, "throws an exception when calling appendChild");
});

QUnit.test("should throw an exception when rerender is called after view is destroyed", function() {
  run(function() {
    view = EmberView.create({
      template: compile('foo')
    });

    view.append();
  });

  run(function() {
    view.destroy();
  });

  throws(function() {
    view.rerender();
  }, null, "throws an exception when calling rerender");
});

QUnit.test("should throw an exception when destroyElement is called after view is destroyed", function() {
  run(function() {
    view = EmberView.create({
      template: compile('foo')
    });

    view.append();
  });

  run(function() {
    view.destroy();
  });

  throws(function() {
    view.destroyElement();
  }, null, "throws an exception when calling destroyElement");
});

QUnit.test("trigger rerender on a view in the inDOM state keeps its state as inDOM", function() {
  run(function() {
    view = EmberView.create({
      template: compile('foo')
    });

    view.append();
  });

  run(function() {
    view.rerender();
  });

  equal(view.currentState, view._states.inDOM, "the view is still in the inDOM state");

  run(function() {
    view.destroy();
  });
});

<commit_msg>Use unbound to assert dom rerender<commit_after>import Ember from "ember-metal/core";
import run from "ember-metal/run_loop";
import EmberObject from "ember-runtime/system/object";
import jQuery from "ember-views/system/jquery";
import EmberView from "ember-views/views/view";
import { compile } from "ember-template-compiler";

var originalLookup = Ember.lookup;
var lookup, view;

QUnit.module("views/view/view_lifecycle_test - pre-render", {
  setup() {
    Ember.lookup = lookup = {};
  },

  teardown() {
    if (view) {
      run(function() {
        view.destroy();
      });
    }
    Ember.lookup = originalLookup;
  }
});

QUnit.test("should create and append a DOM element after bindings have synced", function() {
  var ViewTest;

  lookup.ViewTest = ViewTest = {};

  run(function() {
    ViewTest.fakeController = EmberObject.create({
      fakeThing: 'controllerPropertyValue'
    });

    view = EmberView.createWithMixins({
      fooBinding: 'ViewTest.fakeController.fakeThing',
      template: compile("{{view.foo}}")
    });

    ok(!view.get('element'), "precond - does not have an element before appending");

    // the actual render happens in the `render` queue, which is after the `sync`
    // queue where the binding is synced.
    view.append();
  });

  equal(view.$().text(), 'controllerPropertyValue', "renders and appends after bindings have synced");
});

QUnit.test("should throw an exception if trying to append a child before rendering has begun", function() {
  run(function() {
    view = EmberView.create();
  });

  throws(function() {
    view.appendChild(EmberView, {});
  }, null, "throws an error when calling appendChild()");
});

QUnit.test("should not affect rendering if rerender is called before initial render happens", function() {
  run(function() {
    view = EmberView.create({
      template: compile("Rerender me!")
    });

    view.rerender();
    view.append();
  });

  equal(view.$().text(), "Rerender me!", "renders correctly if rerender is called first");
});

QUnit.test("should not affect rendering if destroyElement is called before initial render happens", function() {
  run(function() {
    view = EmberView.create({
      template: compile("Don't destroy me!")
    });

    view.destroyElement();
    view.append();
  });

  equal(view.$().text(), "Don't destroy me!", "renders correctly if destroyElement is called first");
});

QUnit.module("views/view/view_lifecycle_test - in render", {
  setup() {

  },

  teardown() {
    if (view) {
      run(function() {
        view.destroy();
      });
    }
  }
});

QUnit.skip("rerender should throw inside a template", function() {
  throws(function() {
    run(function() {
      var renderCount = 0;
      view = EmberView.create({
        template(context, options) {
          var view = options.data.view;

          var child1 = view.appendChild(EmberView, {
            template(context, options) {
              renderCount++;
              options.data.buffer.push(String(renderCount));
            }
          });

          view.appendChild(EmberView, {
            template(context, options) {
              options.data.buffer.push("Inside child2");
              child1.rerender();
            }
          });
        }
      });

      view.appendTo("#qunit-fixture");
    });
  }, /Something you did caused a view to re-render after it rendered but before it was inserted into the DOM./);
});

QUnit.module("views/view/view_lifecycle_test - hasElement", {
  teardown() {
    if (view) {
      run(function() {
        view.destroy();
      });
    }
  }
});

QUnit.test("createElement puts the view into the hasElement state", function() {
  var hasCalledInsertElement = false;
  view = EmberView.create({
    didInsertElement() {
      hasCalledInsertElement = true;
    }
  });

  run(function() {
    view.createElement();
  });

  ok(!hasCalledInsertElement, 'didInsertElement is not called');
  equal(view.element.tagName, 'DIV', 'content is rendered');
});

QUnit.test("trigger rerender on a view in the hasElement state doesn't change its state to inDOM", function() {
  var hasCalledInsertElement = false;
  view = EmberView.create({
    didInsertElement() {
      hasCalledInsertElement = true;
    }
  });

  run(function() {
    view.createElement();
    view.rerender();
  });

  ok(!hasCalledInsertElement, 'didInsertElement is not called');
  equal(view.element.tagName, 'DIV', 'content is rendered');
});

QUnit.module("views/view/view_lifecycle_test - in DOM", {
  teardown() {
    if (view) {
      run(function() {
        view.destroy();
      });
    }
  }
});

QUnit.test("should throw an exception when calling appendChild when DOM element exists", function() {
  run(function() {
    view = EmberView.create({
      template: compile("Wait for the kick")
    });

    view.append();
  });

  throws(function() {
    view.appendChild(EmberView, {
      template: compile("Ah ah ah! You didn't say the magic word!")
    });
  }, null, "throws an exception when calling appendChild after element is created");
});

QUnit.test("should replace DOM representation if rerender() is called after element is created", function() {
  run(function() {
    view = EmberView.createWithMixins({
      template: compile("Do not taunt happy fun {{unbound view.shape}}"),
      rerender() {
        this._super.apply(this, arguments);
      },
      shape: 'sphere'
    });

    view.volatileProp = view.get('context.shape');
    view.append();
  });

  equal(view.$().text(), "Do not taunt happy fun sphere",
        "precond - creates DOM element");

  view.shape = 'ball';

  equal(view.$().text(), "Do not taunt happy fun sphere",
        "precond - keeps DOM element");

  run(function() {
    view.rerender();
  });

  equal(view.$().text(), "Do not taunt happy fun ball",
        "rerenders DOM element when rerender() is called");
});

QUnit.test("should destroy DOM representation when destroyElement is called", function() {
  run(function() {
    view = EmberView.create({
      template: compile("Don't fear the reaper")
    });

    view.append();
  });

  ok(view.get('element'), "precond - generates a DOM element");

  run(function() {
    view.destroyElement();
  });

  ok(!view.get('element'), "destroys view when destroyElement() is called");
});

QUnit.test("should destroy DOM representation when destroy is called", function() {
  run(function() {
    view = EmberView.create({
      template: compile("
Don't fear the reaper
")
    });

    view.append();
  });

  ok(view.get('element'), "precond - generates a DOM element");

  run(function() {
    view.destroy();
  });

  ok(jQuery('#warning').length === 0, "destroys element when destroy() is called");
});

QUnit.test("should throw an exception if trying to append an element that is already in DOM", function() {
  run(function() {
    view = EmberView.create({
      template: compile('Broseidon, King of the Brocean')
    });

    view.append();
  });

  ok(view.get('element'), "precond - creates DOM element");

  throws(function() {
    run(function() {
      view.append();
    });
  }, null, "raises an exception on second append");
});

QUnit.module("views/view/view_lifecycle_test - destroyed");

QUnit.test("should throw an exception when calling appendChild after view is destroyed", function() {
  run(function() {
    view = EmberView.create({
      template: compile("Wait for the kick")
    });

    view.append();
  });

  run(function() {
    view.destroy();
  });

  throws(function() {
    view.appendChild(EmberView, {
      template: compile("Ah ah ah! You didn't say the magic word!")
    });
  }, null, "throws an exception when calling appendChild");
});

QUnit.test("should throw an exception when rerender is called after view is destroyed", function() {
  run(function() {
    view = EmberView.create({
      template: compile('foo')
    });

    view.append();
  });

  run(function() {
    view.destroy();
  });

  throws(function() {
    view.rerender();
  }, null, "throws an exception when calling rerender");
});

QUnit.test("should throw an exception when destroyElement is called after view is destroyed", function() {
  run(function() {
    view = EmberView.create({
      template: compile('foo')
    });

    view.append();
  });

  run(function() {
    view.destroy();
  });

  throws(function() {
    view.destroyElement();
  }, null, "throws an exception when calling destroyElement");
});

QUnit.test("trigger rerender on a view in the inDOM state keeps its state as inDOM", function() {
  run(function() {
    view = EmberView.create({
      template: compile('foo')
    });

    view.append();
  });

  run(function() {
    view.rerender();
  });

  equal(view.currentState, view._states.inDOM, "the view is still in the inDOM state");

  run(function() {
    view.destroy();
  });
});

<|endoftext|>


<commit_before>const path = require('path');
const chai = require('chai');
const expect = chai.expect;

const { MockerParser, Mocker, MockModule } = require('../../../lib');

describe('./mocker/MockerParser.js', () => {
  let mockerParser;

  before(() => {
    mockerParser = new MockerParser({
      basePath: path.resolve(__dirname, '../../data/fixtures/mock_server/mockers')
    });

    // console.log(mockerParser);
  });

  describe('check basic info', () => {
    it('should be instanceof MockerParser ', () => {
      expect(mockerParser).to.be.an.instanceof(MockerParser);
    });

    it('should contain some fields', () => {
      expect(mockerParser).to.have.all.keys('basePath', 'matmanMockers');
    });
  });

  describe('check demo_01', () => {
    it('mockerParser.getMockerByName(\'demo_01\') should return correct mocker', () => {
      let mocker = mockerParser.getMockerByName('demo_01');

      expect(mocker).to.be.an.instanceof(Mocker);
      expect(mocker.name).to.equal('demo_01');
      expect(mocker.mockModuleList).to.have.lengthOf(2);
    });

    it('mockerParser.getMockModuleByName(\'demo_01\', \'error\') should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_01', 'error');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('error');

      return mockModule.getResult()
        .then((data) => {
          expect(data).to.eql({
            errCode: 100000
          });
        });
    });
  });

  describe('check demo_02', () => {
    it('mockerParser.getMockerByName(\'demo_02\') should return correct mocker', () => {
      let mocker = mockerParser.getMockerByName('demo_02');

      expect(mocker).to.be.undefined;
    });

    it('mockerParser.getMockerByName(\'demo_02_renamed\') should return correct mocker', () => {
      let mocker = mockerParser.getMockerByName('demo_02_renamed');

      expect(mocker).to.be.an.instanceof(Mocker);
      expect(mocker.name).to.equal('demo_02_renamed');
      expect(mocker.mockModuleList).to.have.lengthOf(5);
    });

    it('mockerParser.getMockModuleByName(\'demo_02_renamed\', \'error\') should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_02_renamed', 'error');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('error');

      return mockModule.getResult()
        .then((data) => {
          expect(data).to.eql({
            errCode: 100000
          });
        });
    });

    it('mockerParser.getMockModuleByName(\'demo_02_renamed\', \'success_1\') should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_02_renamed', 'success_1');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('success_1');

      return mockModule.getResult()
        .then((data) => {
          expect(data).to.eql({
            'result': {
              'other': 'other',
              'result': 1
            },
            'retcode': 0
          });
        });
    });

    it('mockerParser.getMockModuleByName(\'demo_02_renamed\', \'success_2\') should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_02_renamed', 'success_2');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('success_2');

      return mockModule.getResult()
        .then((data) => {
          expect(data).to.eql({
            'result': 2
          });
        });
    });

    it('mockerParser.getMockModuleByName(\'demo_02_renamed\', \'success_3_renamed\') should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_02_renamed', 'success_3_renamed');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('success_3_renamed');

      return mockModule.getResult()
        .then((data) => {
          expect(data).to.eql({
            'result': 3
          });
        });
    });

    it('mockerParser.getMockModuleByName(\'demo_02_renamed\', \'success_4\') should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_02_renamed', 'success_4');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('success_4');

      return mockModule.getResult()
        .then((data) => {
          expect(data).to.equal(4);
        });
    });
    it('mockerParser.getMockModuleByName(\'demo_02_renamed\', \'success_4\') with param should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_02_renamed', 'success_4');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('success_4');

      return mockModule.getResult({ a: 110 })
        .then((data) => {
          expect(data).to.equal('from_param_110');
        });
    });
  });

  describe('check getMockerByRoute', () => {
    it('should return demo_01', () => {
      let mocker = mockerParser.getMockerByRoute('/cgi-bin/a/b/demo_01');

      expect(mocker).to.be.an.instanceof(Mocker);
      expect(mocker.name).to.equal('demo_01');
    });

    it('should return null', () => {
      let mocker = mockerParser.getMockerByRoute('/cgi-bin/a/b/demo_not_exist');

      expect(mocker).to.be.null;
    });

    it('should return demo_02', () => {
      let mocker = mockerParser.getMockerByRoute('/cgi-bin/a/b/demo_02');

      expect(mocker).to.be.an.instanceof(Mocker);
      expect(mocker.name).to.equal('demo_02_renamed');
    });
  });

  describe('check getResInfoByRoute', () => {
    it('demo_01 ok', () => {
      let resInfo = mockerParser.getResInfoByRoute('/cgi-bin/a/b/demo_01');

      expect(resInfo).to.have.all.keys('mockerItem', 'mockModuleItem', 'moduleFullPath', 'params');
      expect(resInfo.mockerItem.name).to.equal('demo_01');
      expect(resInfo.mockModuleItem.name).to.equal('error');
    });

    it('should return null', () => {
      let mocker = mockerParser.getResInfoByRoute('/cgi-bin/a/b/demo_not_exist');

      expect(mocker).to.be.null;
    });

    it('demo_02 ok', () => {
      let resInfo = mockerParser.getResInfoByRoute('/cgi-bin/a/b/demo_02');

      expect(resInfo).to.have.all.keys('mockerItem', 'mockModuleItem', 'moduleFullPath', 'params');
      expect(resInfo.mockerItem.name).to.equal('demo_02_renamed');
      expect(resInfo.mockModuleItem.name).to.equal('success_1');
    });
  });
});

<commit_msg>fix: 修改测试用例<commit_after>const path = require('path');
const chai = require('chai');
const expect = chai.expect;

const { MockerParser, Mocker, MockModule } = require('../../../lib');

describe('./mocker/MockerParser.js', () => {
  let mockerParser;

  before(() => {
    mockerParser = new MockerParser({
      basePath: path.resolve(__dirname, '../../data/fixtures/mock_server/mockers')
    });

    // console.log(mockerParser);
  });

  describe('check basic info', () => {
    it('should be instanceof MockerParser ', () => {
      expect(mockerParser).to.be.an.instanceof(MockerParser);
    });

    it('should contain some fields', () => {
      expect(mockerParser).to.have.all.keys('basePath', 'matmanMockers');
    });
  });

  describe('check demo_01', () => {
    it('mockerParser.getMockerByName(\'demo_01\') should return correct mocker', () => {
      let mocker = mockerParser.getMockerByName('demo_01');

      expect(mocker).to.be.an.instanceof(Mocker);
      expect(mocker.name).to.equal('demo_01');
      expect(mocker.mockModuleList).to.have.lengthOf(2);
    });

    it('mockerParser.getMockModuleByName(\'demo_01\', \'error\') should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_01', 'error');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('error');

      return mockModule.getResult()
        .then((data) => {
          expect(data).to.eql({
            errCode: 100000
          });
        });
    });
  });

  describe('check demo_02', () => {
    it('mockerParser.getMockerByName(\'demo_02\') should return undefined', () => {
      let mocker = mockerParser.getMockerByName('demo_02');

      expect(mocker).to.be.undefined;
    });

    it('mockerParser.getMockerByName(\'demo_02_renamed\') should return correct mocker', () => {
      let mocker = mockerParser.getMockerByName('demo_02_renamed');

      expect(mocker).to.be.an.instanceof(Mocker);
      expect(mocker.name).to.equal('demo_02_renamed');
      expect(mocker.mockModuleList).to.have.lengthOf(5);
    });

    it('mockerParser.getMockModuleByName(\'demo_02_renamed\', \'error\') should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_02_renamed', 'error');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('error');

      return mockModule.getResult()
        .then((data) => {
          expect(data).to.eql({
            errCode: 100000
          });
        });
    });

    it('mockerParser.getMockModuleByName(\'demo_02_renamed\', \'success_1\') should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_02_renamed', 'success_1');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('success_1');

      return mockModule.getResult()
        .then((data) => {
          expect(data).to.eql({
            'result': {
              'other': 'other',
              'result': 1
            },
            'retcode': 0
          });
        });
    });

    it('mockerParser.getMockModuleByName(\'demo_02_renamed\', \'success_2\') should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_02_renamed', 'success_2');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('success_2');

      return mockModule.getResult()
        .then((data) => {
          expect(data).to.eql({
            'result': 2
          });
        });
    });

    it('mockerParser.getMockModuleByName(\'demo_02_renamed\', \'success_3_renamed\') should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_02_renamed', 'success_3_renamed');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('success_3_renamed');

      return mockModule.getResult()
        .then((data) => {
          expect(data).to.eql({
            'result': 3
          });
        });
    });

    it('mockerParser.getMockModuleByName(\'demo_02_renamed\', \'success_4\') should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_02_renamed', 'success_4');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('success_4');

      return mockModule.getResult()
        .then((data) => {
          expect(data).to.equal(4);
        });
    });
    it('mockerParser.getMockModuleByName(\'demo_02_renamed\', \'success_4\') with param should return correct mockModule', () => {
      let mockModule = mockerParser.getMockModuleByName('demo_02_renamed', 'success_4');

      expect(mockModule).to.be.an.instanceof(MockModule);
      expect(mockModule.name).to.equal('success_4');

      return mockModule.getResult({ a: 110 })
        .then((data) => {
          expect(data).to.equal('from_param_110');
        });
    });
  });

  describe('check getMockerByRoute', () => {
    it('should return demo_01', () => {
      let mocker = mockerParser.getMockerByRoute('/cgi-bin/a/b/demo_01');

      expect(mocker).to.be.an.instanceof(Mocker);
      expect(mocker.name).to.equal('demo_01');
    });

    it('should return null', () => {
      let mocker = mockerParser.getMockerByRoute('/cgi-bin/a/b/demo_not_exist');

      expect(mocker).to.be.null;
    });

    it('should return demo_02', () => {
      let mocker = mockerParser.getMockerByRoute('/cgi-bin/a/b/demo_02');

      expect(mocker).to.be.an.instanceof(Mocker);
      expect(mocker.name).to.equal('demo_02_renamed');
    });
  });

  describe('check getResInfoByRoute', () => {
    it('demo_01 ok', () => {
      let resInfo = mockerParser.getResInfoByRoute('/cgi-bin/a/b/demo_01');

      expect(resInfo).to.have.all.keys('mockerItem', 'mockModuleItem', 'moduleFullPath', 'params');
      expect(resInfo.mockerItem.name).to.equal('demo_01');
      expect(resInfo.mockModuleItem.name).to.equal('error');
    });

    it('should return null', () => {
      let mocker = mockerParser.getResInfoByRoute('/cgi-bin/a/b/demo_not_exist');

      expect(mocker).to.be.null;
    });

    it('demo_02 ok', () => {
      let resInfo = mockerParser.getResInfoByRoute('/cgi-bin/a/b/demo_02');

      expect(resInfo).to.have.all.keys('mockerItem', 'mockModuleItem', 'moduleFullPath', 'params');
      expect(resInfo.mockerItem.name).to.equal('demo_02_renamed');
      expect(resInfo.mockModuleItem.name).to.equal('success_1');
    });
  });
});

<|endoftext|>


<commit_before>import EE from 'events';
import inherits from 'inherits';

// We create a basic promise so the caller can cancel the replication possibly
// before we have actually started listening to changes etc
inherits(Replication, EE);
function Replication() {
  EE.call(this);
  this.cancelled = false;
  this.state = 'pending';
  var self = this;
  var promise = new Promise(function (fulfill, reject) {
    self.once('complete', fulfill);
    self.once('error', reject);
  });
  self.then = function (resolve, reject) {
    return promise.then(resolve, reject);
  };
  self.catch = function (reject) {
    return promise.catch(reject);
  };
  // As we allow error handling via "error" event as well,
  // put a stub in here so that rejecting never throws UnhandledError.
  self.catch(function () {});
}

Replication.prototype.cancel = function () {
  this.cancelled = true;
  this.state = 'cancelled';
  this.emit('cancel');
};

Replication.prototype.ready = function (src, target) {
  var self = this;
  if (self._readyCalled) {
    return;
  }
  self._readyCalled = true;

  function onDestroy() {
    self.cancel();
  }
  src.once('destroyed', onDestroy);
  target.once('destroyed', onDestroy);
  function cleanup() {
    src.removeListener('destroyed', onDestroy);
    target.removeListener('destroyed', onDestroy);
  }
  self.once('complete', cleanup);
};

export default Replication;<commit_msg>Fix memory leak when replications fails<commit_after>import EE from 'events';
import inherits from 'inherits';

// We create a basic promise so the caller can cancel the replication possibly
// before we have actually started listening to changes etc
inherits(Replication, EE);
function Replication() {
  EE.call(this);
  this.cancelled = false;
  this.state = 'pending';
  var self = this;
  var promise = new Promise(function (fulfill, reject) {
    self.once('complete', fulfill);
    self.once('error', reject);
  });
  self.then = function (resolve, reject) {
    return promise.then(resolve, reject);
  };
  self.catch = function (reject) {
    return promise.catch(reject);
  };
  // As we allow error handling via "error" event as well,
  // put a stub in here so that rejecting never throws UnhandledError.
  self.catch(function () {});
}

Replication.prototype.cancel = function () {
  this.cancelled = true;
  this.state = 'cancelled';
  this.emit('cancel');
};

Replication.prototype.ready = function (src, target) {
  var self = this;
  if (self._readyCalled) {
    return;
  }
  self._readyCalled = true;

  function onDestroy() {
    self.cancel();
  }
  src.once('destroyed', onDestroy);
  target.once('destroyed', onDestroy);
  function cleanup() {
    src.removeListener('destroyed', onDestroy);
    target.removeListener('destroyed', onDestroy);
  }
  self.once('complete', cleanup);
  self.once('error', cleanup);
};

export default Replication;
<|endoftext|>


<commit_before>module.exports = class LambdaTimeoutApproaching extends Error {
  constructor (remainingMs) {
    const message = `Lambda will timeout in ${remainingMs}ms`

    super(message)

    this.name = 'LambdaTimeoutApproaching'
    this.message = message
    this.stack = []
  }
}
<commit_msg>Remove unnecessary this.message assignment<commit_after>module.exports = class LambdaTimeoutApproaching extends Error {
  constructor (remainingMs) {
    const message = `Lambda will timeout in ${remainingMs}ms`

    super(message)

    this.name = 'LambdaTimeoutApproaching'
    this.stack = []
  }
}
<|endoftext|>


<commit_before>import React, { Component } from "react";
import Transition from "react-transition-group/Transition";
import PropTypes from "prop-types";
import cx from "classnames";
import IconButton from "../IconButton/IconButton";
import RichText from "../RichText";

export default class Notification extends Component {
  constructor(props) {
    super(props);
    this.state = {
      in: false
    };
  }
  componentDidMount() {}

  onClickCapture(event) {
    if (event.target.event.target.tagName === "A") {
      this.props.onLinkClick(this.props.id);
    }
  }

  dismissFeaturedNotification(){
    this.props.dismissFeaturedNotification();
    this.setState({in: false});
  }

  render() {
    return (

        { this.props.featuredNotification
          ?
          <Transition in={this.setState.inProp} >

                  <RichText>{this.props.content}</RichText>
                  <IconButton onClick={this.dismissFeaturedNotification} icon="close-notification" type="flat" />

                {/* <Timestamp /> */}

          </Transition>
          :

                <RichText>{this.props.content}</RichText>

              {/* <Timestamp /> */}

        }

      }

    );
  }
}
<commit_msg>Notification(react): add jsx for featured icon<commit_after>import React, { Component } from "react";
import Transition from "react-transition-group/Transition";
import PropTypes from "prop-types";
import cx from "classnames";
import IconButton from "../IconButton/IconButton";
import RichText from "../RichText";

const COMPONENT_CLASS = "hig__icon";
const FEATURED_COMPONENT_CLASS = "hig__notification--featured";
const UNREAD_MARKER_CLASS = "hig__notification__unread-marker";
const CONTENT_CLASS = "hig__notification__content";

export default class Notification extends Component {
  constructor(props) {
    super(props);
    this.state = {
      in: false
    };
  }
  componentDidMount() {}

  onClickCapture(event) {
    if (event.target.event.target.tagName === "A") {
      this.props.onLinkClick(this.props.id);
    }
  }

  dismissFeaturedNotification() {
    this.props.dismissFeaturedNotification();
    this.setState({ in: false });
  }

  render() {
    return (

        {this.props.featuredNotification ? (
          <Transition in={this.setState.inProp} timeout={300}>
            <div
              className={`${COMPONENT_CLASS} ${FEATURED_COMPONENT_CLASS}`}
              onClickCapture={this.onClickCapture}
            >
              <div className={`${UNREAD_MARKER_CLASS}`} />
              <div className={`${CONTENT_CLASS}`}>
                <RichText>{this.props.content}</RichText>
                <IconButton
                  onClick={this.dismissFeaturedNotification}
                  icon="close-notification"
                  type="flat"
                />

              {/* <Timestamp /> */}

          </Transition>
        ) : (
          <div
            className={`${COMPONENT_CLASS}`}
            onClickCapture={this.onClickCapture}
          >
            <div className={`${UNREAD_MARKER_CLASS}`} />
            <div className={`${CONTENT_CLASS}`}>
              <RichText>{this.props.content}</RichText>

            {/* <Timestamp /> */}

        )}

    );
  }
}
<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var ThermostatMeasurementSchema = new Schema({
  thermostatId: {
    type: Schema.Types.ObjectId,
    required: true
  },
  recordTime: {
    type: [Date],
    required: true
  },
  temperatureValue: {
    type: Number,
    required: true
  },
  humidityValue: {
    type: Number,
    required: true
  },
  relays: {
    type: Number,
    required: true
  },
  temperatureSetPointValue: {
    type: Number,
    required: true
  },
  tMinHeatValue: {
    type: Number,
    required: true
  },
  tMaxHeatValue: {
    type: Number,
    required: true
  },
  tMinColdValue: {
    type: Number,
    required: true
  },
  tMaxColdValue: {
    type: Number,
    required: true
  },
  workingModeValue: {
    type: Number,
    required: true
  },
  presenceModeTimeValue: {
    type: Number,
    required: true
  },
  useModeValue: {
    type: Number,
    required: true
  },
  tempUnitValue: {
    type: Number,
    required: true
  },
  temperature2Value: {
    type: Number,
    required: true
  },
  luminosityValue: {
    type: Number,
    required: true
  },
  hardwareStateValue: {
    type: Number,
    required: true
  },
  proximityValue: {
    type: Number,
    required: true
  },
  savingTimesValue: {
    type: Number,
    required: true
  },
  WiFi_RSSIValue: {
    type: Number,
    required: true
  },
  LCD_StateValue: {
    type: Number,
    required: true
  },
  stateValue: {
    type: Number,
    required: true
  },
  Usual_Night_LuminosityValue: {
    type: Number,
    required: true
  },
  WifiVersionValue: {
    type: Number,
    required: true
  }
});

//compound index based on thermostatId and the recordTime
ThermostatMeasurementSchema.index({thermostatId: 1, recordTime: -1});

ThermostatMeasurementSchema.pre('validate', function(next) {
  var stringDate = this.recordTime;
  this.recordTime = new Date(stringDate);
  next();
});

module.exports = mongoose.model('ThermostatMeasurement', ThermostatMeasurementSchema);
<commit_msg>remove validate hook for thermostat_measurement where I used to set the recordTime as a Date obj<commit_after>'use strict';

var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var ThermostatMeasurementSchema = new Schema({
  thermostatId: {
    type: Schema.Types.ObjectId,
    required: true
  },
  recordTime: {
    type: [Date],
    required: true
  },
  temperatureValue: {
    type: Number,
    required: true
  },
  humidityValue: {
    type: Number,
    required: true
  },
  relays: {
    type: Number,
    required: true
  },
  temperatureSetPointValue: {
    type: Number,
    required: true
  },
  tMinHeatValue: {
    type: Number,
    required: true
  },
  tMaxHeatValue: {
    type: Number,
    required: true
  },
  tMinColdValue: {
    type: Number,
    required: true
  },
  tMaxColdValue: {
    type: Number,
    required: true
  },
  workingModeValue: {
    type: Number,
    required: true
  },
  presenceModeTimeValue: {
    type: Number,
    required: true
  },
  useModeValue: {
    type: Number,
    required: true
  },
  tempUnitValue: {
    type: Number,
    required: true
  },
  temperature2Value: {
    type: Number,
    required: true
  },
  luminosityValue: {
    type: Number,
    required: true
  },
  hardwareStateValue: {
    type: Number,
    required: true
  },
  proximityValue: {
    type: Number,
    required: true
  },
  savingTimesValue: {
    type: Number,
    required: true
  },
  WiFi_RSSIValue: {
    type: Number,
    required: true
  },
  LCD_StateValue: {
    type: Number,
    required: true
  },
  stateValue: {
    type: Number,
    required: true
  },
  Usual_Night_LuminosityValue: {
    type: Number,
    required: true
  },
  WifiVersionValue: {
    type: Number,
    required: true
  }
});

//compound index based on thermostatId and the recordTime
ThermostatMeasurementSchema.index({thermostatId: 1, recordTime: -1});

module.exports = mongoose.model('ThermostatMeasurement', ThermostatMeasurementSchema);
<|endoftext|>


<commit_before>define( [
            'dojo/_base/declare',
            'dojo/_base/array',
            'dojo/aspect',
            'dojo/on',
            'dijit/focus',
            'dijit/form/Button',
            'dijit/form/RadioButton',
            'dojo/dom-construct',
            'dijit/Dialog',
            'dojox/form/Uploader',
            'dojox/form/uploader/plugins/IFrame',
            './FileDialog/TrackList/BAMDriver',
            './FileDialog/TrackList/BigWigDriver',
            './FileDialog/TrackList/GFF3Driver',
            './FileDialog/TrackList/GTFDriver',
            './FileDialog/TrackList/VCFTabixDriver',
            './FileDialog/ResourceList',
            './FileDialog/TrackList',
            'JBrowse/Util'
        ],
        function(
            declare,
            array,
            aspect,
            on,
            dijitFocus,
            Button,
            RadioButton,
            dom,
            Dialog,
            Uploaded,
            IFramePlugin,
            BAMDriver,
            BigWigDriver,
            GFF3Driver,
            GTFDriver,
            VCFTabixDriver,
            ResourceList,
            TrackList,
            Util
        ) {

return declare( null, {

    constructor: function( args ) {
        this.browser = args.browser;
        this.config = dojo.clone( args.config || {} );
        this.browserSupports = {
            dnd: 'draggable' in document.createElement('span')
        };

        this._fileTypeDrivers = [ new BAMDriver(), new BigWigDriver(), new GFF3Driver(), new GTFDriver(), new VCFTabixDriver() ];
    },

    addFileTypeDriver: function( d ) {
        this._fileTypeDrivers.unshift( d );
    },
    getFileTypeDrivers: function() {
        return this._fileTypeDrivers.slice();
    },

    _makeActionBar: function( openCallback, cancelCallback ) {
        var actionBar = dom.create(
            'div', {
                className: 'dijitDialogPaneActionBar'
            });

        var disChoices = this.trackDispositionChoice = [
            new RadioButton({ id: 'openImmediately',
                              value: 'openImmediately',
                              checked: true
                            }),
            new RadioButton({ id: 'addToTrackList',
                              value: 'addToTrackList'
                            })
        ];

        var aux = dom.create('div',{className:'aux'},actionBar);
        disChoices[0].placeAt(aux);
        dom.create('label', { "for": 'openImmediately', innerHTML: 'Open immediately' }, aux ),
        disChoices[1].placeAt(aux);
        dom.create('label', { "for": 'addToTrackList', innerHTML: 'Add to tracks' }, aux );

        new Button({ iconClass: 'dijitIconDelete', label: 'Cancel',
                     onClick: dojo.hitch( this, function() {
                                              cancelCallback && cancelCallback();
                                              this.dialog.hide();
                                          })
                   })
            .placeAt( actionBar );
        new Button({ iconClass: 'dijitIconFolderOpen',
                     label: 'Open',
                     onClick: dojo.hitch( this, function() {
                         openCallback && openCallback({
                             trackConfs: this.trackList.getTrackConfigurations(),
                             trackDisposition: this.trackDispositionChoice[0].checked ? this.trackDispositionChoice[0].value :
                                               this.trackDispositionChoice[1].checked ? this.trackDispositionChoice[1].value :
                                                                                undefined
                         });
                         this.dialog.hide();
                     })
                   })
            .placeAt( actionBar );

        return { domNode: actionBar };
    },

    show: function( args ) {
        var dialog = this.dialog = new Dialog(
            { title: "Open files", className: 'fileDialog' }
            );

        var localFilesControl   = this._makeLocalFilesControl();
        var remoteURLsControl   = this._makeRemoteURLsControl();
        var resourceListControl = this._makeResourceListControl();
        var trackListControl    = this._makeTrackListControl();
        var actionBar           = this._makeActionBar( args.openCallback, args.cancelCallback );

        // connect the local files control to the resource list
        if( !Util.isElectron() ) {
            dojo.connect( localFilesControl.uploader, 'onChange', function() {
                resourceListControl.addLocalFiles( localFilesControl.uploader._files );
            });
        }
        else {
            on( localFilesControl.uploader, 'click', function() {
                var remote = electronRequire('remote');
                var app = remote.require('app');
                var dialog = remote.require('dialog');
                var ret = dialog.showOpenDialog({ properties: [ 'openFile','multiSelections' ]});
                if( ret ) {
                    resourceListControl.addURLs( ret );
                }
            });
        }

        // connect the remote URLs control to the resource list
        dojo.connect( remoteURLsControl, 'onChange', function( urls ) {
            resourceListControl.clearURLs();
            resourceListControl.addURLs( urls );
        });

        // connect the resource list to the track list
        dojo.connect( resourceListControl, 'onChange', function( resources ) {
            trackListControl.update( resources );
        });

        var div = function( attr, children ) {
            var d = dom.create('div', attr );
            array.forEach( children, dojo.hitch( d, 'appendChild' ));
            return d;
        };
        var content = [
                dom.create( 'div', { className: 'intro', innerHTML: args.introMsg||'Add any combination of data files and URLs, and JBrowse will automatically suggest tracks to display their contents.' } ),
                div( { className: 'resourceControls' },
                     [ localFilesControl.domNode, remoteURLsControl.domNode ]
                   ),
                resourceListControl.domNode,
                trackListControl.domNode,
                actionBar.domNode
        ];
        dialog.set( 'content', content );
        dialog.show();

        aspect.after( dialog, 'hide', dojo.hitch( this, function() {
                              dijitFocus.curNode && dijitFocus.curNode.blur();
                              setTimeout( function() { dialog.destroyRecursive(); }, 500 );
                      }));
    },

    _makeLocalFilesControl: function() {
        var container = dom.create('div', { className: 'localFilesControl' });

        dom.create('h3', { innerHTML: 'Local files' }, container );

        var dragArea = dom.create('div', { className: 'dragArea' }, container );
        var fileBox;
        if( Util.isElectron() ) {
            fileBox = dom.create('input', { type: 'button', value: 'Select files...', id: 'openFile' }, dragArea );
        }
        else {
            fileBox = new dojox.form.Uploader({
                multiple: true
            });
            fileBox.placeAt( dragArea );
            if( this.browserSupports.dnd ) {
                // let the uploader process any files dragged into the dialog
                fileBox.addDropTarget( this.dialog.domNode );

                // add a message saying you can drag files in
                dom.create(
                    'div', {
                        className: 'dragMessage',
                        innerHTML: 'Select or drag files here.'
                    }, dragArea
                );
            }
        }

        // little elements used to show pipeline-like connections between the controls
        dom.create( 'div', { className: 'connector', innerHTML: ' '}, container );

        return { domNode: container, uploader: fileBox };
    },

    _makeRemoteURLsControl: function() {
        var container = dom.create('div', { className: 'remoteURLsControl' });

        // make the input elements
        dom.create('h3', { innerHTML: 'Remote URLs - <smaller>one per line</smaller>' }, container );

        // the onChange here will be connected to by the other parts
        // of the dialog to propagate changes to the text in the box
        var self = { domNode: container,
                     onChange: function(urls) {
                         //console.log('urls changed');
                     }
                   };
        self.input = dom.create( 'textarea', {
                                     className: 'urlInput',
                                     placeHolder: "http://paste.urls.here/example.bam",
                                     cols: 25,
                                     rows: 5,
                                     spellcheck: false
                                 }, container );

        // set up the handlers to propagate changes
        var realChange = function() {
            var text = dojo.trim( self.input.value );
            var urls = text.length ? text.split( /\s+/ ) : [];
            self.onChange( urls );
        };
        // watch the input text for changes.  just do it every 900ms
        // because there are many ways that text can get changed (like
        // pasting), not all of which fire the same events.  not using
        // the onchange event, because that doesn't fire until the
        // textarea loses focus.
        var previousText = '';
        var checkFrequency = 900;
        var checkForChange = function() {
            // compare with all whitespace changed to commas so that
            // we are insensitive to changes in whitespace
            if( self.input.value.replace(/\s+/g,',') != previousText ) {
                realChange();
                previousText = self.input.value.replace(/\s+/g,',');
            }
            window.setTimeout( checkForChange, checkFrequency );
        };
        window.setTimeout( checkForChange, checkFrequency );

        // little elements used to show pipeline-like connections between the controls
        dom.create( 'div', { className: 'connector', innerHTML: ' '}, container );

        return self;
    },

    _makeResourceListControl: function () {
        var rl = new ResourceList({ dialog: this });
        return rl;
    },
    _makeTrackListControl: function() {
        var tl = new TrackList({ browser: this.browser, fileDialog: this });
        this.trackList = tl;
        return tl;
    }
});
});
<commit_msg>Correct windows path<commit_after>define( [
            'dojo/_base/declare',
            'dojo/_base/array',
            'dojo/aspect',
            'dojo/on',
            'dijit/focus',
            'dijit/form/Button',
            'dijit/form/RadioButton',
            'dojo/dom-construct',
            'dijit/Dialog',
            'dojox/form/Uploader',
            'dojox/form/uploader/plugins/IFrame',
            './FileDialog/TrackList/BAMDriver',
            './FileDialog/TrackList/BigWigDriver',
            './FileDialog/TrackList/GFF3Driver',
            './FileDialog/TrackList/GTFDriver',
            './FileDialog/TrackList/VCFTabixDriver',
            './FileDialog/ResourceList',
            './FileDialog/TrackList',
            'JBrowse/Util'
        ],
        function(
            declare,
            array,
            aspect,
            on,
            dijitFocus,
            Button,
            RadioButton,
            dom,
            Dialog,
            Uploaded,
            IFramePlugin,
            BAMDriver,
            BigWigDriver,
            GFF3Driver,
            GTFDriver,
            VCFTabixDriver,
            ResourceList,
            TrackList,
            Util
        ) {

return declare( null, {

    constructor: function( args ) {
        this.browser = args.browser;
        this.config = dojo.clone( args.config || {} );
        this.browserSupports = {
            dnd: 'draggable' in document.createElement('span')
        };

        this._fileTypeDrivers = [ new BAMDriver(), new BigWigDriver(), new GFF3Driver(), new GTFDriver(), new VCFTabixDriver() ];
    },

    addFileTypeDriver: function( d ) {
        this._fileTypeDrivers.unshift( d );
    },
    getFileTypeDrivers: function() {
        return this._fileTypeDrivers.slice();
    },

    _makeActionBar: function( openCallback, cancelCallback ) {
        var actionBar = dom.create(
            'div', {
                className: 'dijitDialogPaneActionBar'
            });

        var disChoices = this.trackDispositionChoice = [
            new RadioButton({ id: 'openImmediately',
                              value: 'openImmediately',
                              checked: true
                            }),
            new RadioButton({ id: 'addToTrackList',
                              value: 'addToTrackList'
                            })
        ];

        var aux = dom.create('div',{className:'aux'},actionBar);
        disChoices[0].placeAt(aux);
        dom.create('label', { "for": 'openImmediately', innerHTML: 'Open immediately' }, aux ),
        disChoices[1].placeAt(aux);
        dom.create('label', { "for": 'addToTrackList', innerHTML: 'Add to tracks' }, aux );

        new Button({ iconClass: 'dijitIconDelete', label: 'Cancel',
                     onClick: dojo.hitch( this, function() {
                                              cancelCallback && cancelCallback();
                                              this.dialog.hide();
                                          })
                   })
            .placeAt( actionBar );
        new Button({ iconClass: 'dijitIconFolderOpen',
                     label: 'Open',
                     onClick: dojo.hitch( this, function() {
                         openCallback && openCallback({
                             trackConfs: this.trackList.getTrackConfigurations(),
                             trackDisposition: this.trackDispositionChoice[0].checked ? this.trackDispositionChoice[0].value :
                                               this.trackDispositionChoice[1].checked ? this.trackDispositionChoice[1].value :
                                                                                undefined
                         });
                         this.dialog.hide();
                     })
                   })
            .placeAt( actionBar );

        return { domNode: actionBar };
    },

    show: function( args ) {
        var dialog = this.dialog = new Dialog(
            { title: "Open files", className: 'fileDialog' }
            );

        var localFilesControl   = this._makeLocalFilesControl();
        var remoteURLsControl   = this._makeRemoteURLsControl();
        var resourceListControl = this._makeResourceListControl();
        var trackListControl    = this._makeTrackListControl();
        var actionBar           = this._makeActionBar( args.openCallback, args.cancelCallback );

        // connect the local files control to the resource list
        if( !Util.isElectron() ) {
            dojo.connect( localFilesControl.uploader, 'onChange', function() {
                resourceListControl.addLocalFiles( localFilesControl.uploader._files );
            });
        }
        else {
            on( localFilesControl.uploader, 'click', function() {
                var remote = electronRequire('remote');
                var app = remote.require('app');
                var dialog = remote.require('dialog');
                var ret = dialog.showOpenDialog({ properties: [ 'openFile','multiSelections' ]});
                if( ret ) {
                    resourceListControl.addURLs( Util.replacePath( ret ) );
                }
            });
        }

        // connect the remote URLs control to the resource list
        dojo.connect( remoteURLsControl, 'onChange', function( urls ) {
            resourceListControl.clearURLs();
            resourceListControl.addURLs( urls );
        });

        // connect the resource list to the track list
        dojo.connect( resourceListControl, 'onChange', function( resources ) {
            trackListControl.update( resources );
        });

        var div = function( attr, children ) {
            var d = dom.create('div', attr );
            array.forEach( children, dojo.hitch( d, 'appendChild' ));
            return d;
        };
        var content = [
                dom.create( 'div', { className: 'intro', innerHTML: args.introMsg||'Add any combination of data files and URLs, and JBrowse will automatically suggest tracks to display their contents.' } ),
                div( { className: 'resourceControls' },
                     [ localFilesControl.domNode, remoteURLsControl.domNode ]
                   ),
                resourceListControl.domNode,
                trackListControl.domNode,
                actionBar.domNode
        ];
        dialog.set( 'content', content );
        dialog.show();

        aspect.after( dialog, 'hide', dojo.hitch( this, function() {
                              dijitFocus.curNode && dijitFocus.curNode.blur();
                              setTimeout( function() { dialog.destroyRecursive(); }, 500 );
                      }));
    },

    _makeLocalFilesControl: function() {
        var container = dom.create('div', { className: 'localFilesControl' });

        dom.create('h3', { innerHTML: 'Local files' }, container );

        var dragArea = dom.create('div', { className: 'dragArea' }, container );
        var fileBox;
        if( Util.isElectron() ) {
            fileBox = dom.create('input', { type: 'button', value: 'Select files...', id: 'openFile' }, dragArea );
        }
        else {
            fileBox = new dojox.form.Uploader({
                multiple: true
            });
            fileBox.placeAt( dragArea );
            if( this.browserSupports.dnd ) {
                // let the uploader process any files dragged into the dialog
                fileBox.addDropTarget( this.dialog.domNode );

                // add a message saying you can drag files in
                dom.create(
                    'div', {
                        className: 'dragMessage',
                        innerHTML: 'Select or drag files here.'
                    }, dragArea
                );
            }
        }

        // little elements used to show pipeline-like connections between the controls
        dom.create( 'div', { className: 'connector', innerHTML: ' '}, container );

        return { domNode: container, uploader: fileBox };
    },

    _makeRemoteURLsControl: function() {
        var container = dom.create('div', { className: 'remoteURLsControl' });

        // make the input elements
        dom.create('h3', { innerHTML: 'Remote URLs - <smaller>one per line</smaller>' }, container );

        // the onChange here will be connected to by the other parts
        // of the dialog to propagate changes to the text in the box
        var self = { domNode: container,
                     onChange: function(urls) {
                         //console.log('urls changed');
                     }
                   };
        self.input = dom.create( 'textarea', {
                                     className: 'urlInput',
                                     placeHolder: "http://paste.urls.here/example.bam",
                                     cols: 25,
                                     rows: 5,
                                     spellcheck: false
                                 }, container );

        // set up the handlers to propagate changes
        var realChange = function() {
            var text = dojo.trim( self.input.value );
            var urls = text.length ? text.split( /\s+/ ) : [];
            self.onChange( urls );
        };
        // watch the input text for changes.  just do it every 900ms
        // because there are many ways that text can get changed (like
        // pasting), not all of which fire the same events.  not using
        // the onchange event, because that doesn't fire until the
        // textarea loses focus.
        var previousText = '';
        var checkFrequency = 900;
        var checkForChange = function() {
            // compare with all whitespace changed to commas so that
            // we are insensitive to changes in whitespace
            if( self.input.value.replace(/\s+/g,',') != previousText ) {
                realChange();
                previousText = self.input.value.replace(/\s+/g,',');
            }
            window.setTimeout( checkForChange, checkFrequency );
        };
        window.setTimeout( checkForChange, checkFrequency );

        // little elements used to show pipeline-like connections between the controls
        dom.create( 'div', { className: 'connector', innerHTML: ' '}, container );

        return self;
    },

    _makeResourceListControl: function () {
        var rl = new ResourceList({ dialog: this });
        return rl;
    },
    _makeTrackListControl: function() {
        var tl = new TrackList({ browser: this.browser, fileDialog: this });
        this.trackList = tl;
        return tl;
    }
});
});
<|endoftext|>


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

import BackgroundOverlay from './Images/background-overlay.png';
import Backgrounds from './Backgrounds';

const styles = {
  container: {
    position: 'fixed',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    opacity: 0,
    zIndex: -10,
    transition: 'opacity 1s',
  },
  active: {
    opacity: 1,
  },
  image: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    zIndex: 0,
    backgroundRepeat: 'no-repeat',
    backgroundPosition: 'center',
    backgroundSize: 'cover',
    backgroundAttachment: 'fixed',
  },
  overlay: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    zIndex: 1,
    backgroundImage: `url(${BackgroundOverlay})`,
  },
};

class AppBackgroundImage extends React.PureComponent {
  static propTypes = {
    bossId: PropTypes.number,
  };
  //url ? `url(${url})` : null
  /*
*/

  constructor() {
    super();
    this.state = {
      image: null,
      show: false,
    };
  }

  componentWillReceiveProps(newProps) {
    if (newProps.bossId !== this.props.bossId) {
      const bossId = newProps.bossId;
      if (Backgrounds[bossId] && Backgrounds[bossId].length > 0) {
        const imageIndex = Math.floor(Math.random() * Backgrounds[bossId].length);

        this.setState({
          image: Backgrounds[bossId][imageIndex],
        });
      }
    }
    this.setState({
      show: !!newProps.bossId && Backgrounds[newProps.bossId] && Backgrounds[newProps.bossId].length > 0,
    });
  }

  render() {
    let containerStyle = styles.container;
    if (this.state.show) {
      containerStyle = {
        ...containerStyle,
        ...styles.active,
      };
    }

    return (

        <div
          style={{
            ...styles.image,
            backgroundImage: this.state.image ? `url(${this.state.image})` : null,
          }}
        />

    );
  }
}

export default AppBackgroundImage;
<commit_msg>Show dark background while loading background image<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import BackgroundOverlay from './Images/background-overlay.png';
import Backgrounds from './Backgrounds';

const styles = {
  container: {
    position: 'fixed',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    opacity: 0,
    zIndex: -10,
    transition: 'opacity 1s',
    background: '#000',
  },
  active: {
    opacity: 1,
  },
  image: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    zIndex: 0,
    backgroundRepeat: 'no-repeat',
    backgroundPosition: 'center',
    backgroundSize: 'cover',
    backgroundAttachment: 'fixed',
  },
  overlay: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    zIndex: 1,
    backgroundImage: `url(${BackgroundOverlay})`,
  },
};

class AppBackgroundImage extends React.PureComponent {
  static propTypes = {
    bossId: PropTypes.number,
  };
  //url ? `url(${url})` : null
  /*
*/

  constructor() {
    super();
    this.state = {
      image: null,
      show: false,
    };
  }

  componentWillReceiveProps(newProps) {
    if (newProps.bossId !== this.props.bossId) {
      const bossId = newProps.bossId;
      if (Backgrounds[bossId] && Backgrounds[bossId].length > 0) {
        const imageIndex = Math.floor(Math.random() * Backgrounds[bossId].length);

        this.setState({
          image: Backgrounds[bossId][imageIndex],
        });
      }
    }
    this.setState({
      show: !!newProps.bossId && Backgrounds[newProps.bossId] && Backgrounds[newProps.bossId].length > 0,
    });
  }

  render() {
    let containerStyle = styles.container;
    if (this.state.show) {
      containerStyle = {
        ...containerStyle,
        ...styles.active,
      };
    }

    return (

        <div
          style={{
            ...styles.image,
            backgroundImage: this.state.image ? `url(${this.state.image})` : null,
          }}
        />

    );
  }
}

export default AppBackgroundImage;
<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var CounterClockwise = require('../../../../src/math/angle/CounterClockwise');
var RadToDeg = require('../../../../src/math/RadToDeg');
var Wrap = require('../../../../src/math/Wrap');

/**
 * Renders this Game Object with the WebGL Renderer to the given Camera.
 * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera.
 * This method should not be called directly. It is a utility function of the Render module.
 *
 * @method SpineGameObject#renderWebGL
 * @since 3.19.0
 * @private
 *
 * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer.
 * @param {SpineGameObject} src - The Game Object being rendered in this call.
 * @param {number} interpolationPercentage - Reserved for future use and custom pipelines.
 * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object.
 * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested
 */
var SpineGameObjectWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix)
{
    var plugin = src.plugin;
    var skeleton = src.skeleton;
    var sceneRenderer = plugin.sceneRenderer;

    var GameObjectRenderMask = 15;

    var willRender = !(GameObjectRenderMask !== src.renderFlags || (src.cameraFilter !== 0 && (src.cameraFilter & camera.id)));

    if (!skeleton || !willRender)
    {
        //  Reset the current type
        renderer.currentType = '';

        //  If there is already a batch running, we need to close it
        if (!renderer.nextTypeMatch)
        {
            //  The next object in the display list is not a Spine object, so we end the batch
            sceneRenderer.end();

            renderer.rebindPipeline(renderer.pipelines.MultiPipeline);
        }

        return;
    }

    if (renderer.newType)
    {
        renderer.clearPipeline();
    }

    var camMatrix = renderer._tempMatrix1;
    var spriteMatrix = renderer._tempMatrix2;
    var calcMatrix = renderer._tempMatrix3;

    spriteMatrix.applyITRS(src.x, src.y, src.rotation, Math.abs(src.scaleX), Math.abs(src.scaleY));

    camMatrix.copyFrom(camera.matrix);

    if (parentMatrix)
    {
        //  Multiply the camera by the parent matrix
        camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY);

        //  Undo the camera scroll
        spriteMatrix.e = src.x;
        spriteMatrix.f = src.y;

        //  Multiply by the Sprite matrix, store result in calcMatrix
        camMatrix.multiply(spriteMatrix, calcMatrix);
    }
    else
    {
        spriteMatrix.e -= camera.scrollX * src.scrollFactorX;
        spriteMatrix.f -= camera.scrollY * src.scrollFactorY;

        //  Multiply by the Sprite matrix, store result in calcMatrix
        camMatrix.multiply(spriteMatrix, calcMatrix);
    }

    var viewportHeight = renderer.height;

    skeleton.x = calcMatrix.tx;
    skeleton.y = viewportHeight - calcMatrix.ty;

    skeleton.scaleX = calcMatrix.scaleX;
    skeleton.scaleY = calcMatrix.scaleY;

    if (src.scaleX < 0)
    {
        skeleton.scaleX *= -1;

        src.root.rotation = RadToDeg(calcMatrix.rotationNormalized);
    }
    else
    {
        //  +90 degrees to account for the difference in Spine vs. Phaser rotation
        src.root.rotation = Wrap(RadToDeg(CounterClockwise(calcMatrix.rotationNormalized)) + 90, 0, 360);
    }

    if (src.scaleY < 0)
    {
        skeleton.scaleY *= -1;

        if (src.scaleX < 0)
        {
            src.root.rotation -= (RadToDeg(calcMatrix.rotationNormalized) * 2);
        }
        else
        {
            src.root.rotation += (RadToDeg(calcMatrix.rotationNormalized) * 2);
        }
    }

    if (camera.renderToTexture || renderer.currentFramebuffer !== null)
    {
        skeleton.y = calcMatrix.ty;
        skeleton.scaleY *= -1;
    }

    //  Add autoUpdate option
    skeleton.updateWorldTransform();

    if (renderer.newType)
    {
        sceneRenderer.begin();
    }

    //  Draw the current skeleton
    sceneRenderer.drawSkeleton(skeleton, src.preMultipliedAlpha);

    if (plugin.drawDebug || src.drawDebug)
    {
        //  Because if we don't, the bones render positions are completely wrong (*sigh*)
        var oldX = skeleton.x;
        var oldY = skeleton.y;

        skeleton.x = 0;
        skeleton.y = 0;

        sceneRenderer.drawSkeletonDebug(skeleton, src.preMultipliedAlpha);

        skeleton.x = oldX;
        skeleton.y = oldY;
    }

    if (!renderer.nextTypeMatch)
    {
        //  The next object in the display list is not a Spine object, so we end the batch
        sceneRenderer.end();

        renderer.rebindPipeline(renderer.pipelines.MultiPipeline);
    }
};

module.exports = SpineGameObjectWebGLRenderer;
<commit_msg>A Spine Game Object with `setVisible(false)` will no longer still cause internal gl commands and is now properly skipped, retaining any current batch in the process. Fix #5174<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var CounterClockwise = require('../../../../src/math/angle/CounterClockwise');
var RadToDeg = require('../../../../src/math/RadToDeg');
var Wrap = require('../../../../src/math/Wrap');

/**
 * Renders this Game Object with the WebGL Renderer to the given Camera.
 * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera.
 * This method should not be called directly. It is a utility function of the Render module.
 *
 * @method SpineGameObject#renderWebGL
 * @since 3.19.0
 * @private
 *
 * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer.
 * @param {SpineGameObject} src - The Game Object being rendered in this call.
 * @param {number} interpolationPercentage - Reserved for future use and custom pipelines.
 * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object.
 * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested
 */
var SpineGameObjectWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix)
{
    var plugin = src.plugin;
    var skeleton = src.skeleton;
    var childAlpha = skeleton.color.a;
    var sceneRenderer = plugin.sceneRenderer;

    var GameObjectRenderMask = 15;

    var willRender = !(GameObjectRenderMask !== src.renderFlags || (src.cameraFilter !== 0 && (src.cameraFilter & camera.id)) || childAlpha === 0);

    if (!skeleton || !willRender)
    {
        //  If there is already a batch running, we need to close it
        if (!renderer.nextTypeMatch)
        {
            //  The next object in the display list is not a Spine object, so we end the batch
            sceneRenderer.end();

            if (!renderer.finalType)
            {
                //  Reset the current type
                renderer.currentType = '';

                renderer.rebindPipeline(renderer.pipelines.MultiPipeline);
            }
        }

        return;
    }

    if (renderer.newType)
    {
        renderer.clearPipeline();
    }

    var camMatrix = renderer._tempMatrix1;
    var spriteMatrix = renderer._tempMatrix2;
    var calcMatrix = renderer._tempMatrix3;

    spriteMatrix.applyITRS(src.x, src.y, src.rotation, Math.abs(src.scaleX), Math.abs(src.scaleY));

    camMatrix.copyFrom(camera.matrix);

    if (parentMatrix)
    {
        //  Multiply the camera by the parent matrix
        camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY);

        //  Undo the camera scroll
        spriteMatrix.e = src.x;
        spriteMatrix.f = src.y;

        //  Multiply by the Sprite matrix, store result in calcMatrix
        camMatrix.multiply(spriteMatrix, calcMatrix);
    }
    else
    {
        spriteMatrix.e -= camera.scrollX * src.scrollFactorX;
        spriteMatrix.f -= camera.scrollY * src.scrollFactorY;

        //  Multiply by the Sprite matrix, store result in calcMatrix
        camMatrix.multiply(spriteMatrix, calcMatrix);
    }

    var viewportHeight = renderer.height;

    skeleton.x = calcMatrix.tx;
    skeleton.y = viewportHeight - calcMatrix.ty;

    skeleton.scaleX = calcMatrix.scaleX;
    skeleton.scaleY = calcMatrix.scaleY;

    if (src.scaleX < 0)
    {
        skeleton.scaleX *= -1;

        src.root.rotation = RadToDeg(calcMatrix.rotationNormalized);
    }
    else
    {
        //  +90 degrees to account for the difference in Spine vs. Phaser rotation
        src.root.rotation = Wrap(RadToDeg(CounterClockwise(calcMatrix.rotationNormalized)) + 90, 0, 360);
    }

    if (src.scaleY < 0)
    {
        skeleton.scaleY *= -1;

        if (src.scaleX < 0)
        {
            src.root.rotation -= (RadToDeg(calcMatrix.rotationNormalized) * 2);
        }
        else
        {
            src.root.rotation += (RadToDeg(calcMatrix.rotationNormalized) * 2);
        }
    }

    if (camera.renderToTexture || renderer.currentFramebuffer !== null)
    {
        skeleton.y = calcMatrix.ty;
        skeleton.scaleY *= -1;
    }

    //  Add autoUpdate option
    skeleton.updateWorldTransform();

    if (renderer.newType)
    {
        sceneRenderer.begin();
    }

    //  Draw the current skeleton
    sceneRenderer.drawSkeleton(skeleton, src.preMultipliedAlpha);

    if (plugin.drawDebug || src.drawDebug)
    {
        //  Because if we don't, the bones render positions are completely wrong (*sigh*)
        var oldX = skeleton.x;
        var oldY = skeleton.y;

        skeleton.x = 0;
        skeleton.y = 0;

        sceneRenderer.drawSkeletonDebug(skeleton, src.preMultipliedAlpha);

        skeleton.x = oldX;
        skeleton.y = oldY;
    }

    if (!renderer.nextTypeMatch)
    {
        //  The next object in the display list is not a Spine Game Object or Spine Container, so we end the batch.
        sceneRenderer.end();

        if (!renderer.finalType)
        {
            renderer.rebindPipeline(renderer.pipelines.MultiPipeline);
        }
    }
};

module.exports = SpineGameObjectWebGLRenderer;
<|endoftext|>


<commit_before>// @flow
/* eslint-disable react/sort-comp */
import React, { Component, PropTypes } from "react"
import { findDOMNode } from "react-dom"
import urlify from "../_utils/urlify"

// react-router does not return leading and trailing slashes
// so we need to normalize according to collection data
const splatToUrl = (string) => ("/" + urlify(string))

const isDevelopment = () => process.env.NODE_ENV !== "production"
const isClient = () => typeof window !== "undefined"
const isDevelopmentClient = () => isDevelopment() && isClient

let catchLinks
let browserHistory

if (isClient()) {
  catchLinks = require("../_utils/catch-links").default
  browserHistory = require("../client").browserHistory
}

function find(
  collection: StatinamicCollection,
  pageUrl: string
): Object {
  return collection.find((item) => (
    item.__url === pageUrl ||
    item.__url === pageUrl + "/"||
    item.__resourceUrl === pageUrl
  ))
}

type DefaultProps = {
  defaultLayout: string,
}
type Props = {
  pages: Object,
  params: {
    splat: string
  },
  defaultLayout: string,
  getPage: Function,
  setPageNotFound: Function,
}

type Context = {
  collection: StatinamicCollection,
  layouts: Object
}

class PageContainer extends Component<DefaultProps, Props, void> {
  _content: Element;

  static propTypes = {
    pages: PropTypes.object.isRequired,
    params: PropTypes.object,

    defaultLayout: PropTypes.string,

    // actions
    getPage: PropTypes.func.isRequired,
    setPageNotFound: PropTypes.func.isRequired,
  };

  static contextTypes = {
    collection: PropTypes.array.isRequired,
    layouts: PropTypes.object.isRequired,
  };

  static defaultProps = {
    defaultLayout: "Page",
  };

  componentWillMount() {
    this.preparePage(this.props, this.context)
  }

  componentDidMount() {
    this.catchInternalLink()
  }

  componentWillReceiveProps(nextProps: Props): void {
    this.preparePage(nextProps, this.context)
  }

  componentDidUpdate() {
    this.catchInternalLink()
  }

  catchInternalLink() {
    if (!isClient()) {
      return
    }

    if (this._content) {
      const layoutDOMElement = findDOMNode(this._content)
      if (layoutDOMElement) {
        catchLinks(layoutDOMElement, (href) => {
          const pageUrl = href.replace(process.env.STATINAMIC_PATHNAME, "/")
          if (!find(this.context.collection, pageUrl)) {
            return false
          }
          if (browserHistory) {
            browserHistory.push(pageUrl)
          }
          return true
        })
      }
    }
  }

  preparePage(props: Props, context: Context): void {
    if (!context.layouts[props.defaultLayout]) {
      console.error(
        "statinamic: PageContainer: " +
        `default layout "${ props.defaultLayout }" doesn't exist. ` +
        `Please check your configuration ("layouts" part). ` +
        `If you haven't defined "${ props.defaultLayout }", you should. `
      )
    }

    const pageUrl = splatToUrl(props.params.splat)
    if (isDevelopmentClient()) {
      console.info(`statinamic: PageContainer: '${ pageUrl }' rendering...`)
    }

    const item = find(context.collection, pageUrl)
    if (isClient() && item) {
      // adjust url (eg: missing trailing slash)
      const currentExactPageUrl = window.location.href
        .replace(
          (
            window.location.protocol +
            "//" +
            window.location.host +
            process.env.STATINAMIC_PATHNAME
          ),
          "/"
        )
        .replace(window.location.hash, "")

      if (currentExactPageUrl !== item.__url) {
        console.info(
          `statinamic: PageContainer: ` +
          `replacing by '${ currentExactPageUrl }' to '${ item.__url }'`
        )
        if (browserHistory) {
          browserHistory.replace(item.__url)
        }
      }
    }

    const page = props.pages[pageUrl]
    if (!page) {
      if (item) {
        props.getPage(item.__url, item.__dataUrl)
      }
      else {
        console.error(
          `statinamic: PageContainer: ` +
          `${ pageUrl } is a page not found.`
        )
        props.setPageNotFound(pageUrl)
      }
    }
    else {
      if (page.error) {
        return
      }

      const Layout = this.getLayout(props, context, page)
      if (page.type !== undefined && !Layout) {
        console.error(
          "statinamic: PageContainer: " +
          `Unkown page type: "${ page.type }" component not available in ` +
          `"layouts" property. ` +
          `Please check the "layout" or "type" of page "${ page }" header.`
        )
      }
    }
  }

  getLayout(props: Props, context: Context, page: Object): ReactClass {
    return context.layouts[page.type || props.defaultLayout]
  }

  render() {
    const pageUrl = splatToUrl(this.props.params.splat)
    const page = this.props.pages[pageUrl]

    if (!page) {
      if (isDevelopmentClient()) {
        console.info(`statinamic: PageContainer: '${ pageUrl }' no data`)
      }
      return null
    }
    if (isDevelopmentClient()) {
      console.info(`statinamic: PageContainer: '${ pageUrl }'`, page)
    }

    if (
      typeof page !== "object" ||
      page.toString() !== "[object Object]"
    ) {
      console.info(
        `statinamic: PageContainer: page ${ pageUrl } should be an object`
      )
      return null
    }

    const { PageLoading, PageError } = this.context.layouts
    const Layout = this.getLayout(this.props, this.context, page)

    return (

        {
          !page.error && page.loading && PageLoading &&
          <PageLoading />
        }
        {
          !!page.error && !PageError &&

{ page.error }

{ page.errorText }

        }
        {
          !!page.error && PageError &&
          <PageError { ...page } />
        }
        {
          !page.error && !page.loading && Layout &&
          <Layout ref={ (ref) => this._content = ref } { ...page } />
        }

    )
  }
}

export default PageContainer
<commit_msg>Fix: Super verbose console log in dev mode (server-side)<commit_after>// @flow
/* eslint-disable react/sort-comp */
import React, { Component, PropTypes } from "react"
import { findDOMNode } from "react-dom"
import urlify from "../_utils/urlify"

// react-router does not return leading and trailing slashes
// so we need to normalize according to collection data
const splatToUrl = (string) => ("/" + urlify(string))

const isDevelopment = (): boolean => process.env.NODE_ENV !== "production"
const isClient = (): boolean => typeof window !== "undefined"
const isDevelopmentClient = (): boolean => isDevelopment() && isClient()

let catchLinks
let browserHistory

if (isClient()) {
  catchLinks = require("../_utils/catch-links").default
  browserHistory = require("../client").browserHistory
}

function find(
  collection: StatinamicCollection,
  pageUrl: string
): Object {
  return collection.find((item) => (
    item.__url === pageUrl ||
    item.__url === pageUrl + "/"||
    item.__resourceUrl === pageUrl
  ))
}

type DefaultProps = {
  defaultLayout: string,
}
type Props = {
  pages: Object,
  params: {
    splat: string
  },
  defaultLayout: string,
  getPage: Function,
  setPageNotFound: Function,
}

type Context = {
  collection: StatinamicCollection,
  layouts: Object
}

class PageContainer extends Component<DefaultProps, Props, void> {
  _content: Element;

  static propTypes = {
    pages: PropTypes.object.isRequired,
    params: PropTypes.object,

    defaultLayout: PropTypes.string,

    // actions
    getPage: PropTypes.func.isRequired,
    setPageNotFound: PropTypes.func.isRequired,
  };

  static contextTypes = {
    collection: PropTypes.array.isRequired,
    layouts: PropTypes.object.isRequired,
  };

  static defaultProps = {
    defaultLayout: "Page",
  };

  componentWillMount() {
    this.preparePage(this.props, this.context)
  }

  componentDidMount() {
    this.catchInternalLink()
  }

  componentWillReceiveProps(nextProps: Props): void {
    this.preparePage(nextProps, this.context)
  }

  componentDidUpdate() {
    this.catchInternalLink()
  }

  catchInternalLink() {
    if (!isClient()) {
      return
    }

    if (this._content) {
      const layoutDOMElement = findDOMNode(this._content)
      if (layoutDOMElement) {
        catchLinks(layoutDOMElement, (href) => {
          const pageUrl = href.replace(process.env.STATINAMIC_PATHNAME, "/")
          if (!find(this.context.collection, pageUrl)) {
            return false
          }
          if (browserHistory) {
            browserHistory.push(pageUrl)
          }
          return true
        })
      }
    }
  }

  preparePage(props: Props, context: Context): void {
    if (!context.layouts[props.defaultLayout]) {
      console.error(
        "statinamic: PageContainer: " +
        `default layout "${ props.defaultLayout }" doesn't exist. ` +
        `Please check your configuration ("layouts" part). ` +
        `If you haven't defined "${ props.defaultLayout }", you should. `
      )
    }

    const pageUrl = splatToUrl(props.params.splat)
    if (isDevelopmentClient()) {
      console.info(`statinamic: PageContainer: '${ pageUrl }' rendering...`)
    }

    const item = find(context.collection, pageUrl)
    if (isClient() && item) {
      // adjust url (eg: missing trailing slash)
      const currentExactPageUrl = window.location.href
        .replace(
          (
            window.location.protocol +
            "//" +
            window.location.host +
            process.env.STATINAMIC_PATHNAME
          ),
          "/"
        )
        .replace(window.location.hash, "")

      if (currentExactPageUrl !== item.__url) {
        console.info(
          `statinamic: PageContainer: ` +
          `replacing by '${ currentExactPageUrl }' to '${ item.__url }'`
        )
        if (browserHistory) {
          browserHistory.replace(item.__url)
        }
      }
    }

    const page = props.pages[pageUrl]
    if (!page) {
      if (item) {
        props.getPage(item.__url, item.__dataUrl)
      }
      else {
        console.error(
          `statinamic: PageContainer: ` +
          `${ pageUrl } is a page not found.`
        )
        props.setPageNotFound(pageUrl)
      }
    }
    else {
      if (page.error) {
        return
      }

      const Layout = this.getLayout(props, context, page)
      if (page.type !== undefined && !Layout) {
        console.error(
          "statinamic: PageContainer: " +
          `Unkown page type: "${ page.type }" component not available in ` +
          `"layouts" property. ` +
          `Please check the "layout" or "type" of page "${ page }" header.`
        )
      }
    }
  }

  getLayout(props: Props, context: Context, page: Object): ReactClass {
    return context.layouts[page.type || props.defaultLayout]
  }

  render() {
    const pageUrl = splatToUrl(this.props.params.splat)
    const page = this.props.pages[pageUrl]

    if (!page) {
      if (isDevelopmentClient()) {
        console.info(`statinamic: PageContainer: '${ pageUrl }' no data`)
      }
      return null
    }
    if (isDevelopmentClient()) {
      console.info(`statinamic: PageContainer: '${ pageUrl }'`, page)
    }

    if (
      typeof page !== "object" ||
      page.toString() !== "[object Object]"
    ) {
      console.info(
        `statinamic: PageContainer: page ${ pageUrl } should be an object`
      )
      return null
    }

    const { PageLoading, PageError } = this.context.layouts
    const Layout = this.getLayout(this.props, this.context, page)

    return (

        {
          !page.error && page.loading && PageLoading &&
          <PageLoading />
        }
        {
          !!page.error && !PageError &&

{ page.error }

{ page.errorText }

        }
        {
          !!page.error && PageError &&
          <PageError { ...page } />
        }
        {
          !page.error && !page.loading && Layout &&
          <Layout ref={ (ref) => this._content = ref } { ...page } />
        }

    )
  }
}

export default PageContainer
<|endoftext|>