<commit_before>import expect from 'expect.js';
import * as u from '../acceptance_test_utils';
import * as cc from '../../src/cred/country_codes';

describe(".sms acceptance", function() {
  before(u.stubWebApis);
  after(u.restoreWebApis);

  describe("constructing a Lock", function() {
    before(function() {
      this.lock = u.constructLock();
    });

    it("doesn't render a thing", function() {
      expect(u.isRendered(this.lock)).to.not.be.ok();
    });
  });

  describe("opening a Lock", function() {
    before(function() {
      this.lock = u.constructLock();
      u.openLock(this.lock, "sms");

      // Making assertions here because there's no guarantee that the first test
      // will execute before the Lock is opened. TODO: think of a better
      // strategy for writting tests.
      expect(u.isRendered(this.lock)).to.be.ok();
      expect(u.isOpened(this.lock)).to.not.be.ok();
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("opens it after a few ms", function(done) {
      setTimeout(() => {
        expect(u.isOpened(this.lock)).to.be.ok();
        done();
      }, 17);
    });

    it("displays an empty input for the phone number", function() {
      expect(u.qInputValue(this.lock, "phone-number")).to.be("");
    });

    it("displays an input with for the location with a default value", function() {
      expect(u.qInputValue(this.lock, "location")).to.be("United States +1");
    });
  });

  describe("opening the location selector", function() {
    before(function() {
      this.lock = u.constructLock();
      u.openLock(this.lock, "sms");
    });

    after(function() {
      u.clickFirstLocation(this.lock); // necessary for the close button to show up
      u.closeLock(this.lock);
    });

    describe("when clicking the location input", function() {
      before(function() {
        u.clickInput(this.lock, "location");
      });

      it("shows the location selector", function() {
        expect(u.isShowingLocationSelector(this.lock)).to.be.ok();
      });
    });
  });

  describe("filtering locations", function() {
    before(function() {
      this.lock = u.constructLock();
      u.openLock(this.lock, "sms");
      u.clickInput(this.lock, "location");
    });

    after(function() {
      u.clickFirstLocation(this.lock); // necessary for the close button to show up
      u.closeLock(this.lock);
    });

    it("shows all locations available by default", function() {
      expect(u.qLocations(this.lock).length).to.be(cc.countryCodes.size);
    });

    describe("when entering an unexistent location name", function() {
      before(function() {
        u.filterLocations(this.lock, "nowhere");
      });

      it("doesn't show any locations", function() {
        expect(u.qLocations(this.lock).length).to.be(0);
      });
    });

    describe("when entering a few letters that match a few locations", function() {
      before(function() {
        u.filterLocations(this.lock, "au");
      });

      it("shows that locations", function() {
        expect(u.qLocations(this.lock).length).to.be.within(2, 10);
      });
    });

    describe("when entering an exact location name", function() {
      before(function() {
        u.filterLocations(this.lock, "spain");
      });

      it("shows only that location", function() {
        expect(u.qLocations(this.lock).length).to.be(1);
      });
    });
  });

  describe.skip("selecting a location", function() {
    before(function() {
      this.lock = u.constructLock();
      u.openLock(this.lock, "sms");
      u.clickInput(this.lock, "location");
      u.filterLocations(this.lock, "spain");
      u.clickFirstLocation(this.lock);
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("closes the location selector", function(done) {
      // NOTE: to tell whether or not the location selector has been closed, we
      // need to wait for the enter transition to finish.
      setTimeout(() => {
        expect(u.isShowingLocationSelector(this.lock)).to.not.be.ok();
        done();
      }, u.AUXILIARY_PANE_DELAY);
    });

    it("updates the location input", function() {
      expect(u.qInputValue(this.lock, "location")).to.be("Spain +34");
    });

    describe("when submiting", function() {
      before(function() {
        u.fillInput(this.lock, "phone-number", "0303456");
        u.submit(this.lock);
      });

      it("starts the passwordless flow with the given location", function() {
        const params = {phoneNumber: "+340303456",};
        expect(u.hasStartedPasswordless(params)).to.be.ok();
      });
    });
  });

  describe("entering an invalid phone number", function() {
    before(function() {
      this.lock = u.constructLock();
      u.openLock(this.lock, "sms");
      u.fillInput(this.lock, "phone-number", "invalid number");
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("doesn't mark the input as invalid", function() {
      expect(u.isInputInvalid(this.lock, "phone-number")).to.not.be.ok();
    });

    describe("when attempting a submit", function() {
      before(function() {
        u.submit(this.lock);
      });

      it("marks the input as invalid", function() {
        expect(u.isInputInvalid(this.lock, "phone-number")).to.be.ok();
      });

      it("doesn't perform any request", function() {
        expect(u.hasStartedPasswordless(false)).to.be.ok();
        expect(u.isInputInvalid(this.lock, "phone-number")).to.be.ok();
        expect(u.isLoading(this.lock)).to.not.be.ok();
      });

      describe("when fixing the phone number", function() {
        before(function() {
          u.fillInput(this.lock, "phone-number", "0303456");
        });

        it("clears the input error", function() {
          expect(u.isInputInvalid(this.lock, "phone-number")).to.not.be.ok();
        });

        describe("and entering an invalid phone number again", function() {
          before(function() {
            u.fillInput(this.lock, "phone-number", "invalid number");
          });

          it("doesn't mark the input as invalid", function() {
            expect(u.isInputInvalid(this.lock, "phone-number")).to.not.be.ok();
          });
        });
      });
    });
  });

  describe("successfully submitting a phone number", function() {
    before(function() {
      this.lock = u.constructLock();
      this.cb = u.openLock(this.lock, "sms");
      u.fillInput(this.lock, "phone-number", "0303456");
      u.submit(this.lock);
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("shows a loading indicator until a response is obtained", function() {
      expect(u.isLoading(this.lock)).to.be.ok();
    });

    it("starts the passwordless flow", function() {
      const params = {phoneNumber: "+10303456"};
      expect(u.hasStartedPasswordless(params)).to.be.ok();
    });

    describe("when response arrives", function() {
      before(function() {
        u.simulateStartPasswordlessResponse();
      });

      it("hides the loading indicator", function() {
        expect(u.isLoading(this.lock)).to.not.be.ok();
      });

      it("wait until new credential pane appears", function(done) {
        setTimeout(done, u.CRED_PANE_DELAY);
      });

      it("doesn't show an input for the phone number", function() {
        expect(u.qInput(this.lock, "phone-number")).to.not.be.ok();
      });

      it("shows an input for the vcode", function() {
        expect(u.qInput(this.lock, "vcode")).to.be.ok();
      });

      it("doesn't invoke the provided callback", function() {
        expect(this.cb.called).to.not.be.ok();
      });
    });
  });

  describe("unsuccessful attempt to submit a phone number", function() {
    before(function() {
      this.lock = u.constructLock();
      this.cb = u.openLock(this.lock, "sms");
      u.fillInput(this.lock, "phone-number", "0303456");
      u.submit(this.lock);
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("shows a loading indicator until a response is obtained", function() {
      expect(u.isLoading(this.lock)).to.be.ok();
    });

    it("starts the passwordless flow", function() {
      const params = {phoneNumber: "+10303456"};
      expect(u.hasStartedPasswordless(params)).to.be.ok();
    });

    describe("when response arrives", function() {
      before(function() {
        u.simulateStartPasswordlessResponse({});
      });

      it("hides the loading indicator", function() {
        expect(u.isLoading(this.lock)).to.not.be.ok();
      });

      it("still shows an input for the phone number", function() {
        expect(u.qInput(this.lock, "phone-number")).to.be.ok();
      });

      it("doesn't show an input for the vcode", function() {
        expect(u.qInput(this.lock, "vcode")).to.not.be.ok();
      });

      it("doesn't invoke the provided callback", function() {
        expect(this.cb.called).to.not.be.ok();
      });

      it("shows a generic error", function() {
        expect(u.isSomethingWrong(this.lock, u.SMS_GENERIC_ERROR)).to.be.ok();
      });
    });
  });

  describe.skip("submitting an empty vcode", function() {
    before(function() {
      this.lock = u.constructLock();
      this.cb = u.openLock(this.lock, "sms");
      u.fillInput(this.lock, "phone-number", "123456");
      u.submit(this.lock);
      u.simulateStartPasswordlessResponse();
      u.submit(this.lock);
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("marks the input as invalid", function() {
      expect(u.isInputInvalid(this.lock, "vcode")).to.be.ok();
    });

    it("doesn't perform any request", function() {
      expect(u.startPasswordlessCallCount()).to.be(0);
      expect(u.isLoading(this.lock)).to.not.be.ok();
    });

    describe("when filling the vcode", function() {
      before(function() {
        u.fillInput(this.lock, "vcode", "1");
      });

      it("clears the input error", function() {
        expect(u.isInputInvalid(this.lock, "vcode")).to.not.be.ok();
      });

      describe("and clearing the vcode", function() {
        before(function() {
          u.fillInput(this.lock, "vcode", "");
        });

        it("doesn't mark the input as invalid", function() {
          expect(u.isInputInvalid(this.lock, "vcode")).to.not.be.ok();
        });
      });
    });
  });

  describe.skip("successfully submitting the vcode", function() {
    before(function() {
      this.lock = u.constructLock();
      this.cb = u.openLock(this.lock, "sms");
      u.fillInput(this.lock, "phone-number", "123456");
      u.submit(this.lock);
      u.simulateStartPasswordlessResponse();
      u.fillInput(this.lock, "vcode", "0303456");
      u.submit(this.lock);
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("shows a loading indicator until a response is obtained", function() {
      expect(u.isLoading(this.lock)).to.be.ok();
    });

    it("attempts to sign in with the entered cred", function() {
      expect(u.hasSignedInWith("+54123456", "0303456")).to.be.ok();
    })

    describe("when response arrives", function() {
      before(function(done) {
        setTimeout(() => {
          u.simulateSingInResponse();
          done();
        }, 500);
      });

      it("hides the loading indicator", function() {
        expect(u.isLoading(this.lock)).to.not.be.ok();
      });

      // it("doesn't show an input for the vcode", function() {
      //   expect(u.qInput(this.lock, "vcode")).to.not.be.ok();
      // });

      it("invokes the provided callback", function() {
        expect(this.cb.calledOnce).to.be.ok();
        // TODO: "fake arg" is a detail implementation of the utils module, so
        // it should be handled over there.
        expect(this.cb.calledWithExactly(null, "fake arg")).to.be.ok();
      });
    });
  });

  describe.skip("unsuccessful attempt to submit the vcode", function() {
    before(function() {
      this.lock = u.constructLock();
      this.cb = u.openLock(this.lock, "sms");
      u.fillInput(this.lock, "phone-number", "123456");
      u.submit(this.lock);
      u.simulateStartPasswordlessResponse();
      u.fillInput(this.lock, "vcode", "0303456");
      u.submit(this.lock);
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("shows a loading indicator until a response is obtained", function() {
      expect(u.isLoading(this.lock)).to.be.ok();
    });

    it("attempts to sign in with the entered cred", function() {
      expect(u.hasSignedInWith("+54123456", "0303456")).to.be.ok();
    })

    describe("when response arrives", function() {
      before(function() {
        this.error = {description: "invalid email or vcode"};
        u.simulateSingInResponse(this.error);
      });

      it("hides the loading indicator", function() {
        expect(u.isLoading(this.lock)).to.not.be.ok();
      });

      it("still shows an input for the vcode", function() {
        expect(u.qInput(this.lock, "vcode")).to.be.ok();
      });

      it("doesn't close the Lock", function() {
        expect(u.isOpened(this.lock)).to.be.ok();
      });

      it("invokes the provided callback", function() {
        expect(this.cb.calledOnce).to.be.ok();
        expect(this.cb.calledWithExactly(this.error)).to.be.ok();
      });

      it("shows the received error description", function() {
        expect(u.isSomethingWrong(this.lock, this.error.description)).to.be.ok();
      });
    });
  });
});
<commit_msg>Increate "wait" test timeout<commit_after>import expect from 'expect.js';
import * as u from '../acceptance_test_utils';
import * as cc from '../../src/cred/country_codes';

describe(".sms acceptance", function() {
  before(u.stubWebApis);
  after(u.restoreWebApis);

  describe("constructing a Lock", function() {
    before(function() {
      this.lock = u.constructLock();
    });

    it("doesn't render a thing", function() {
      expect(u.isRendered(this.lock)).to.not.be.ok();
    });
  });

  describe("opening a Lock", function() {
    before(function() {
      this.lock = u.constructLock();
      u.openLock(this.lock, "sms");

      // Making assertions here because there's no guarantee that the first test
      // will execute before the Lock is opened. TODO: think of a better
      // strategy for writting tests.
      expect(u.isRendered(this.lock)).to.be.ok();
      expect(u.isOpened(this.lock)).to.not.be.ok();
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("opens it after a few ms", function(done) {
      setTimeout(() => {
        expect(u.isOpened(this.lock)).to.be.ok();
        done();
      }, 17);
    });

    it("displays an empty input for the phone number", function() {
      expect(u.qInputValue(this.lock, "phone-number")).to.be("");
    });

    it("displays an input with for the location with a default value", function() {
      expect(u.qInputValue(this.lock, "location")).to.be("United States +1");
    });
  });

  describe("opening the location selector", function() {
    before(function() {
      this.lock = u.constructLock();
      u.openLock(this.lock, "sms");
    });

    after(function() {
      u.clickFirstLocation(this.lock); // necessary for the close button to show up
      u.closeLock(this.lock);
    });

    describe("when clicking the location input", function() {
      before(function() {
        u.clickInput(this.lock, "location");
      });

      it("shows the location selector", function() {
        expect(u.isShowingLocationSelector(this.lock)).to.be.ok();
      });
    });
  });

  describe("filtering locations", function() {
    before(function() {
      this.lock = u.constructLock();
      u.openLock(this.lock, "sms");
      u.clickInput(this.lock, "location");
    });

    after(function() {
      u.clickFirstLocation(this.lock); // necessary for the close button to show up
      u.closeLock(this.lock);
    });

    it("shows all locations available by default", function() {
      expect(u.qLocations(this.lock).length).to.be(cc.countryCodes.size);
    });

    describe("when entering an unexistent location name", function() {
      before(function() {
        u.filterLocations(this.lock, "nowhere");
      });

      it("doesn't show any locations", function() {
        expect(u.qLocations(this.lock).length).to.be(0);
      });
    });

    describe("when entering a few letters that match a few locations", function() {
      before(function() {
        u.filterLocations(this.lock, "au");
      });

      it("shows that locations", function() {
        expect(u.qLocations(this.lock).length).to.be.within(2, 10);
      });
    });

    describe("when entering an exact location name", function() {
      before(function() {
        u.filterLocations(this.lock, "spain");
      });

      it("shows only that location", function() {
        expect(u.qLocations(this.lock).length).to.be(1);
      });
    });
  });

  describe.skip("selecting a location", function() {
    before(function() {
      this.lock = u.constructLock();
      u.openLock(this.lock, "sms");
      u.clickInput(this.lock, "location");
      u.filterLocations(this.lock, "spain");
      u.clickFirstLocation(this.lock);
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("closes the location selector", function(done) {
      // NOTE: to tell whether or not the location selector has been closed, we
      // need to wait for the enter transition to finish.
      setTimeout(() => {
        expect(u.isShowingLocationSelector(this.lock)).to.not.be.ok();
        done();
      }, u.AUXILIARY_PANE_DELAY);
    });

    it("updates the location input", function() {
      expect(u.qInputValue(this.lock, "location")).to.be("Spain +34");
    });

    describe("when submiting", function() {
      before(function() {
        u.fillInput(this.lock, "phone-number", "0303456");
        u.submit(this.lock);
      });

      it("starts the passwordless flow with the given location", function() {
        const params = {phoneNumber: "+340303456",};
        expect(u.hasStartedPasswordless(params)).to.be.ok();
      });
    });
  });

  describe("entering an invalid phone number", function() {
    before(function() {
      this.lock = u.constructLock();
      u.openLock(this.lock, "sms");
      u.fillInput(this.lock, "phone-number", "invalid number");
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("doesn't mark the input as invalid", function() {
      expect(u.isInputInvalid(this.lock, "phone-number")).to.not.be.ok();
    });

    describe("when attempting a submit", function() {
      before(function() {
        u.submit(this.lock);
      });

      it("marks the input as invalid", function() {
        expect(u.isInputInvalid(this.lock, "phone-number")).to.be.ok();
      });

      it("doesn't perform any request", function() {
        expect(u.hasStartedPasswordless(false)).to.be.ok();
        expect(u.isInputInvalid(this.lock, "phone-number")).to.be.ok();
        expect(u.isLoading(this.lock)).to.not.be.ok();
      });

      describe("when fixing the phone number", function() {
        before(function() {
          u.fillInput(this.lock, "phone-number", "0303456");
        });

        it("clears the input error", function() {
          expect(u.isInputInvalid(this.lock, "phone-number")).to.not.be.ok();
        });

        describe("and entering an invalid phone number again", function() {
          before(function() {
            u.fillInput(this.lock, "phone-number", "invalid number");
          });

          it("doesn't mark the input as invalid", function() {
            expect(u.isInputInvalid(this.lock, "phone-number")).to.not.be.ok();
          });
        });
      });
    });
  });

  describe("successfully submitting a phone number", function() {
    before(function() {
      this.lock = u.constructLock();
      this.cb = u.openLock(this.lock, "sms");
      u.fillInput(this.lock, "phone-number", "0303456");
      u.submit(this.lock);
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("shows a loading indicator until a response is obtained", function() {
      expect(u.isLoading(this.lock)).to.be.ok();
    });

    it("starts the passwordless flow", function() {
      const params = {phoneNumber: "+10303456"};
      expect(u.hasStartedPasswordless(params)).to.be.ok();
    });

    describe("when response arrives", function() {
      before(function() {
        u.simulateStartPasswordlessResponse();
      });

      it("hides the loading indicator", function() {
        expect(u.isLoading(this.lock)).to.not.be.ok();
      });

      it("wait until new credential pane appears", function(done) {
        this.timeout(u.CRED_PANE_DELAY + 1000);
        setTimeout(done, u.CRED_PANE_DELAY);
      });

      it("doesn't show an input for the phone number", function() {
        expect(u.qInput(this.lock, "phone-number")).to.not.be.ok();
      });

      it("shows an input for the vcode", function() {
        expect(u.qInput(this.lock, "vcode")).to.be.ok();
      });

      it("doesn't invoke the provided callback", function() {
        expect(this.cb.called).to.not.be.ok();
      });
    });
  });

  describe("unsuccessful attempt to submit a phone number", function() {
    before(function() {
      this.lock = u.constructLock();
      this.cb = u.openLock(this.lock, "sms");
      u.fillInput(this.lock, "phone-number", "0303456");
      u.submit(this.lock);
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("shows a loading indicator until a response is obtained", function() {
      expect(u.isLoading(this.lock)).to.be.ok();
    });

    it("starts the passwordless flow", function() {
      const params = {phoneNumber: "+10303456"};
      expect(u.hasStartedPasswordless(params)).to.be.ok();
    });

    describe("when response arrives", function() {
      before(function() {
        u.simulateStartPasswordlessResponse({});
      });

      it("hides the loading indicator", function() {
        expect(u.isLoading(this.lock)).to.not.be.ok();
      });

      it("still shows an input for the phone number", function() {
        expect(u.qInput(this.lock, "phone-number")).to.be.ok();
      });

      it("doesn't show an input for the vcode", function() {
        expect(u.qInput(this.lock, "vcode")).to.not.be.ok();
      });

      it("doesn't invoke the provided callback", function() {
        expect(this.cb.called).to.not.be.ok();
      });

      it("shows a generic error", function() {
        expect(u.isSomethingWrong(this.lock, u.SMS_GENERIC_ERROR)).to.be.ok();
      });
    });
  });

  describe.skip("submitting an empty vcode", function() {
    before(function() {
      this.lock = u.constructLock();
      this.cb = u.openLock(this.lock, "sms");
      u.fillInput(this.lock, "phone-number", "123456");
      u.submit(this.lock);
      u.simulateStartPasswordlessResponse();
      u.submit(this.lock);
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("marks the input as invalid", function() {
      expect(u.isInputInvalid(this.lock, "vcode")).to.be.ok();
    });

    it("doesn't perform any request", function() {
      expect(u.startPasswordlessCallCount()).to.be(0);
      expect(u.isLoading(this.lock)).to.not.be.ok();
    });

    describe("when filling the vcode", function() {
      before(function() {
        u.fillInput(this.lock, "vcode", "1");
      });

      it("clears the input error", function() {
        expect(u.isInputInvalid(this.lock, "vcode")).to.not.be.ok();
      });

      describe("and clearing the vcode", function() {
        before(function() {
          u.fillInput(this.lock, "vcode", "");
        });

        it("doesn't mark the input as invalid", function() {
          expect(u.isInputInvalid(this.lock, "vcode")).to.not.be.ok();
        });
      });
    });
  });

  describe.skip("successfully submitting the vcode", function() {
    before(function() {
      this.lock = u.constructLock();
      this.cb = u.openLock(this.lock, "sms");
      u.fillInput(this.lock, "phone-number", "123456");
      u.submit(this.lock);
      u.simulateStartPasswordlessResponse();
      u.fillInput(this.lock, "vcode", "0303456");
      u.submit(this.lock);
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("shows a loading indicator until a response is obtained", function() {
      expect(u.isLoading(this.lock)).to.be.ok();
    });

    it("attempts to sign in with the entered cred", function() {
      expect(u.hasSignedInWith("+54123456", "0303456")).to.be.ok();
    })

    describe("when response arrives", function() {
      before(function(done) {
        setTimeout(() => {
          u.simulateSingInResponse();
          done();
        }, 500);
      });

      it("hides the loading indicator", function() {
        expect(u.isLoading(this.lock)).to.not.be.ok();
      });

      // it("doesn't show an input for the vcode", function() {
      //   expect(u.qInput(this.lock, "vcode")).to.not.be.ok();
      // });

      it("invokes the provided callback", function() {
        expect(this.cb.calledOnce).to.be.ok();
        // TODO: "fake arg" is a detail implementation of the utils module, so
        // it should be handled over there.
        expect(this.cb.calledWithExactly(null, "fake arg")).to.be.ok();
      });
    });
  });

  describe.skip("unsuccessful attempt to submit the vcode", function() {
    before(function() {
      this.lock = u.constructLock();
      this.cb = u.openLock(this.lock, "sms");
      u.fillInput(this.lock, "phone-number", "123456");
      u.submit(this.lock);
      u.simulateStartPasswordlessResponse();
      u.fillInput(this.lock, "vcode", "0303456");
      u.submit(this.lock);
    });

    after(function() {
      u.closeLock(this.lock);
    });

    it("shows a loading indicator until a response is obtained", function() {
      expect(u.isLoading(this.lock)).to.be.ok();
    });

    it("attempts to sign in with the entered cred", function() {
      expect(u.hasSignedInWith("+54123456", "0303456")).to.be.ok();
    })

    describe("when response arrives", function() {
      before(function() {
        this.error = {description: "invalid email or vcode"};
        u.simulateSingInResponse(this.error);
      });

      it("hides the loading indicator", function() {
        expect(u.isLoading(this.lock)).to.not.be.ok();
      });

      it("still shows an input for the vcode", function() {
        expect(u.qInput(this.lock, "vcode")).to.be.ok();
      });

      it("doesn't close the Lock", function() {
        expect(u.isOpened(this.lock)).to.be.ok();
      });

      it("invokes the provided callback", function() {
        expect(this.cb.calledOnce).to.be.ok();
        expect(this.cb.calledWithExactly(this.error)).to.be.ok();
      });

      it("shows the received error description", function() {
        expect(u.isSomethingWrong(this.lock, this.error.description)).to.be.ok();
      });
    });
  });
});
<|endoftext|>


<commit_before>"use strict";

(function (global) {
    var globalXDomainRequest = global.XDomainRequest;

    var fakeXdrSetUp = function () {
        this.fakeXdr = sinon.useFakeXDomainRequest();
    };

    var fakeXdrTearDown = function() {
        if (typeof this.fakeXdr.restore == "function") {
            this.fakeXdr.restore();
        }
    };

    buster.testCase("sinon.FakeXDomainRequest", {
        "is constructor": function () {
            assert.isFunction(sinon.FakeXDomainRequest);
            assert.same(sinon.FakeXDomainRequest.prototype.constructor, sinon.FakeXDomainRequest);
        },
        "implements readyState constants": function () {
            assert.same(sinon.FakeXDomainRequest.UNSENT, 0);
            assert.same(sinon.FakeXDomainRequest.OPENED, 1);
            assert.same(sinon.FakeXDomainRequest.LOADING, 3);
            assert.same(sinon.FakeXDomainRequest.DONE, 4);
        },
        "calls onCreate if listener is set": function () {
            var onCreate = sinon.spy();
            sinon.FakeXDomainRequest.onCreate = onCreate;

            var xhr = new sinon.FakeXDomainRequest();

            assert(onCreate.called);
        },
        "passes new object to onCreate if set": function () {
            var onCreate = sinon.spy();
            sinon.FakeXDomainRequest.onCreate = onCreate;

            var xhr = new sinon.FakeXDomainRequest();

            assert.same(onCreate.getCall(0).args[0], xhr);
        },

        "open": {
            setUp: function () {
                this.xdr = new sinon.FakeXDomainRequest();
            },
            "is method": function () {
                assert.isFunction(this.xdr.open);
            },
            "sets properties on object": function () {
                this.xdr.open("GET", "/my/url");

                assert.equals(this.xdr.method, "GET");
                assert.equals(this.xdr.url, "/my/url");
            },
            "sets responseText to null": function () {
                this.xdr.open("GET", "/my/url");

                assert.isNull(this.xdr.responseText);
            },
            "sets send flag to false": function () {
                this.xdr.open("GET", "/my/url");

                assert.isFalse(this.xdr.sendFlag);
            },
            "sets readyState to OPENED": function () {
                this.xdr.open("GET", "/my/url");

                assert.same(this.xdr.readyState, sinon.FakeXDomainRequest.OPENED);
            },
            "sets requestHeaders to blank object": function () {
                this.xdr.open("GET", "/my/url");

                assert.isObject(this.xdr.requestHeaders);
                assert.equals(this.xdr.requestHeaders, {});
            },

        },

        "send": {
            setUp: function () {
                this.xdr = new sinon.FakeXDomainRequest();
            },

            "throws if request is not open": function () {
                var xdr = new sinon.FakeXDomainRequest();

                assert.exception(function () {
                    xdr.send();
                });
            },
            "throws if send flag is true": function () {
                var xdr = this.xdr;
                xdr.open("GET", "/");
                xdr.sendFlag = true;

                assert.exception(function () {
                    xdr.send();
                });
            },
            "sets GET body to null": function () {
                this.xdr.open("GET", "/");
                this.xdr.send("Data");

                assert.isNull(this.xdr.requestBody);
            },

            "sets HEAD body to null": function () {
                this.xdr.open("HEAD", "/");
                this.xdr.send("Data");

                assert.isNull(this.xdr.requestBody);
            },
            "sets mime to text/plain for all methods": function () {
                var methods = ["GET", "HEAD", "POST"];
                for (var method in methods) {
                    this.xdr.open(method, "/");
                    this.xdr.send("Data");

                    assert.equals(this.xdr.requestHeaders["Content-Type"], "text/plain;charset=utf-8");
                }
            },
            "sets request body to string data": function () {
                this.xdr.open("POST", "/");
                this.xdr.send("Data");

                assert.equals(this.xdr.requestBody, "Data");
            },
            "sets error flag to false": function () {
                this.xdr.open("POST", "/");
                this.xdr.send("Data");

                assert.isFalse(this.xdr.errorFlag);
            },

            "sets send flag to true": function () {
                this.xdr.open("POST", "/");
                this.xdr.send("Data");

                assert.isTrue(this.xdr.sendFlag);
            },
            "calls readyStateChange": function () {
                this.xdr.open("POST", "/", false);
                var spy = sinon.spy();
                this.xdr.readyStateChange = spy;

                this.xdr.send("Data");

                assert.equals(this.xdr.readyState, sinon.FakeXDomainRequest.OPENED);
                assert.isTrue(spy.called);
            },
        },

        "setResponseBody": {
            setUp: function () {
                this.xdr = new sinon.FakeXDomainRequest();
                this.xdr.open("GET", "/");
                this.xdr.send();
            },
            "invokes readyStateChange handler with LOADING state": function () {
                var spy = sinon.spy();
                this.xdr.readyStateChange = spy;

                this.xdr.setResponseBody("Some text goes in here ok?");

                assert(spy.calledWith(sinon.FakeXDomainRequest.LOADING));
            },
            "fire onprogress event": function() {
                var spy = sinon.spy();
                this.xdr.onprogress = spy;

                this.xdr.setResponseBody("Some text goes in here ok?");

                assert.isTrue(spy.called);
            },
            "invokes readyStateChange handler for each 10 byte chunk": function () {
                var spy = sinon.spy();
                this.xdr.readyStateChange = spy;
                this.xdr.chunkSize = 10;

                this.xdr.setResponseBody("Some text goes in here ok?");

                assert.equals(spy.callCount, 4);
            },
            "invokes readyStateChange handler for each x byte chunk": function () {
                var spy = sinon.spy();
                this.xdr.readyStateChange = spy;
                this.xdr.chunkSize = 20;

                this.xdr.setResponseBody("Some text goes in here ok?");

                assert.equals(spy.callCount, 3);
            },
            "invokes readyStateChange handler with partial data": function () {
                var pieces = [];

                var spy = sinon.spy(function () {
                    pieces.push(this.responseText);
                });

                this.xdr.readyStateChange = spy;
                this.xdr.chunkSize = 9;

                this.xdr.setResponseBody("Some text goes in here ok?");

                assert.equals(pieces[1], "Some text");
            },
            "calls readyStateChange with DONE state": function () {
                var spy = sinon.spy();
                this.xdr.readyStateChange = spy;

                this.xdr.setResponseBody("Some text goes in here ok?");

                assert(spy.calledWith(sinon.FakeXDomainRequest.DONE));
            },
            "throws if not open": function () {
                var xdr = new sinon.FakeXDomainRequest();

                assert.exception(function () {
                    xdr.setResponseBody("");
                });
            },
            "throws if body was already sent": function () {
                var xdr = new sinon.FakeXDomainRequest();
                xdr.open("GET", "/");
                xdr.send();
                xdr.setResponseBody("");

                assert.exception(function () {
                    xdr.setResponseBody("");
                });
            },
            "throws if body is not a string": function () {
                var xdr = new sinon.FakeXDomainRequest();
                xdr.open("GET", "/");
                xdr.send();

                assert.exception(function () {
                    xdr.setResponseBody({});
                }, "InvalidBodyException");
            }
        },

        "respond": {
            setUp: function () {
                this.xdr = new sinon.FakeXDomainRequest();
                this.xdr.open("GET", "/");
                var spy = this.spy = sinon.spy();
                this.xdr.onload = spy.call(this);
                this.xdr.send();
            },
            "fire onload event": function () {
                this.onload = this.spy;
                this.xdr.respond(200, {}, "");
                assert.equals(this.spy.callCount, 1);
            },
            "fire onload event with this set to the XHR object": function (done) {
                var xdr = new sinon.FakeXDomainRequest();
                xdr.open("GET", "/");

                xdr.onload = function() {
                    assert.same(this, xdr);
                    done();
                };

                xdr.send();
                xdr.respond(200, {}, "");
            },
            "calls readystate handler with readyState DONE once": function () {
                this.xdr.respond(200, {}, "");

                assert.equals(this.spy.callCount, 1);
            },
            "defaults to status 200, no headers, and blank body": function () {
                this.xdr.respond();

                assert.equals(this.xdr.status, 200);
                assert.equals(this.xdr.responseText, "");
            },
            "sets status": function () {
                this.xdr.respond(201);

                assert.equals(this.xdr.status, 201);
            }
        },

        "simulatetimeout": {
            setUp: function () {
                this.xdr = new sinon.FakeXDomainRequest();
                this.xdr.open("GET", "/");
                this.xdr.send();
                this.xdr.timeout = 100;
            },
            "fires ontimeout event": function() {
                var spy = sinon.spy();
                this.xdr.ontimeout = spy;

                this.xdr.simulatetimeout();

                assert.isTrue(this.xdr.isTimeout);
                assert.isTrue(spy.called);
            },
            "readyState is DONE": function() {
                this.xdr.simulatetimeout();

                assert.equals(this.xdr.readyState, sinon.FakeXDomainRequest.DONE);
            },
            "responseText no longer accessible": function() {
                var ontimeout = function() {
                    var xdr = this;
                    if (typeof xdr.responseText === 'undefined') {
                        throw 'responseText not accessible';
                    }
                };
                var spy = sinon.spy(ontimeout);
                this.xdr.ontimeout = spy;

                this.xdr.simulatetimeout();

                assert.isTrue(spy.called);
                assert.isTrue(spy.threw());
            }
        },

        "abort": {
            setUp: function () {
                this.xdr = new sinon.FakeXDomainRequest();
            },
            "sets aborted flag to true": function () {
                this.xdr.aborted = true;

                this.xdr.abort();

                assert.isTrue(this.xdr.aborted);
            },
            "sets responseText to null": function () {
                this.xdr.responseText = "Partial data";

                this.xdr.abort();

                assert.isNull(this.xdr.responseText);
            },
            "sets errorFlag to true": function () {
                this.xdr.errorFlag = true;

                this.xdr.abort();

                assert.isTrue(this.xdr.errorFlag);
            },
            "fire onerror event": function () {
                var spy = sinon.spy();
                this.xdr.onerror = spy;

                this.xdr.open("GET", "/");
                this.xdr.send();
                this.xdr.abort();

                assert.equals(spy.callCount, 1);
            },
            "sets state to DONE if sent before": function () {
                this.xdr.open("GET", "/");
                this.xdr.send();

                this.xdr.readyStateChange = sinon.spy();

                this.xdr.abort();

                assert(this.xdr.readyStateChange.calledWith(sinon.FakeXDomainRequest.DONE));
            },
            "sets send flag to false if sent before": function () {
                this.xdr.open("GET", "/");
                this.xdr.send();

                this.xdr.abort();

                assert.isFalse(this.xdr.sendFlag);
            },
            "does not dispatch readystatechange event if readyState is unsent": function () {
                this.xdr.readyStateChange = sinon.stub();

                this.xdr.abort();

                assert.isFalse(this.xdr.readyStateChange.called);
            },
            "does not dispatch readystatechange event if readyState is opened but not sent": function () {
                this.xdr.open("GET", "/");
                this.xdr.readyStateChange = sinon.stub();

                this.xdr.abort();

                assert.isFalse(this.xdr.readyStateChange.called);
            }
        },

        "missing native XDR": {
            requiresSupportFor: { "no native XDR": typeof XDomainRequest == "undefined" },
            setUp: fakeXdrSetUp,
            tearDown: fakeXdrTearDown,

            "does not expose XDomainRequest": function () {
                assert.equals(typeof XDomainRequest, "undefined");
            },

            "does not expose XDomainRequest after restore": function () {
                this.fakeXdr.restore();

                assert.equals(typeof XDomainRequest, "undefined");
            }
        },

        "native XDR": {
            requiresSupportFor: { "XDR": typeof XDomainRequest !== "undefined" },
            setUp: fakeXdrSetUp,
            tearDown: fakeXdrTearDown,

            "replaces global XDomainRequest": function () {
                refute.same(XDomainRequest, globalXDomainRequest);
                assert.same(XDomainRequest, sinon.FakeXDomainRequest);
            },

            "restores global XDomainRequest": function () {
                this.fakeXdr.restore();

                assert.same(XDomainRequest, globalXDomainRequest);
            }
        },

    });

})(this);
<commit_msg>Rewrite responseText test for fake_xdomain_request#simulatetimeout<commit_after>"use strict";

(function (global) {
    var globalXDomainRequest = global.XDomainRequest;

    var fakeXdrSetUp = function () {
        this.fakeXdr = sinon.useFakeXDomainRequest();
    };

    var fakeXdrTearDown = function() {
        if (typeof this.fakeXdr.restore == "function") {
            this.fakeXdr.restore();
        }
    };

    buster.testCase("sinon.FakeXDomainRequest", {
        "is constructor": function () {
            assert.isFunction(sinon.FakeXDomainRequest);
            assert.same(sinon.FakeXDomainRequest.prototype.constructor, sinon.FakeXDomainRequest);
        },
        "implements readyState constants": function () {
            assert.same(sinon.FakeXDomainRequest.UNSENT, 0);
            assert.same(sinon.FakeXDomainRequest.OPENED, 1);
            assert.same(sinon.FakeXDomainRequest.LOADING, 3);
            assert.same(sinon.FakeXDomainRequest.DONE, 4);
        },
        "calls onCreate if listener is set": function () {
            var onCreate = sinon.spy();
            sinon.FakeXDomainRequest.onCreate = onCreate;

            var xhr = new sinon.FakeXDomainRequest();

            assert(onCreate.called);
        },
        "passes new object to onCreate if set": function () {
            var onCreate = sinon.spy();
            sinon.FakeXDomainRequest.onCreate = onCreate;

            var xhr = new sinon.FakeXDomainRequest();

            assert.same(onCreate.getCall(0).args[0], xhr);
        },

        "open": {
            setUp: function () {
                this.xdr = new sinon.FakeXDomainRequest();
            },
            "is method": function () {
                assert.isFunction(this.xdr.open);
            },
            "sets properties on object": function () {
                this.xdr.open("GET", "/my/url");

                assert.equals(this.xdr.method, "GET");
                assert.equals(this.xdr.url, "/my/url");
            },
            "sets responseText to null": function () {
                this.xdr.open("GET", "/my/url");

                assert.isNull(this.xdr.responseText);
            },
            "sets send flag to false": function () {
                this.xdr.open("GET", "/my/url");

                assert.isFalse(this.xdr.sendFlag);
            },
            "sets readyState to OPENED": function () {
                this.xdr.open("GET", "/my/url");

                assert.same(this.xdr.readyState, sinon.FakeXDomainRequest.OPENED);
            },
            "sets requestHeaders to blank object": function () {
                this.xdr.open("GET", "/my/url");

                assert.isObject(this.xdr.requestHeaders);
                assert.equals(this.xdr.requestHeaders, {});
            },

        },

        "send": {
            setUp: function () {
                this.xdr = new sinon.FakeXDomainRequest();
            },

            "throws if request is not open": function () {
                var xdr = new sinon.FakeXDomainRequest();

                assert.exception(function () {
                    xdr.send();
                });
            },
            "throws if send flag is true": function () {
                var xdr = this.xdr;
                xdr.open("GET", "/");
                xdr.sendFlag = true;

                assert.exception(function () {
                    xdr.send();
                });
            },
            "sets GET body to null": function () {
                this.xdr.open("GET", "/");
                this.xdr.send("Data");

                assert.isNull(this.xdr.requestBody);
            },

            "sets HEAD body to null": function () {
                this.xdr.open("HEAD", "/");
                this.xdr.send("Data");

                assert.isNull(this.xdr.requestBody);
            },
            "sets mime to text/plain for all methods": function () {
                var methods = ["GET", "HEAD", "POST"];
                for (var method in methods) {
                    this.xdr.open(method, "/");
                    this.xdr.send("Data");

                    assert.equals(this.xdr.requestHeaders["Content-Type"], "text/plain;charset=utf-8");
                }
            },
            "sets request body to string data": function () {
                this.xdr.open("POST", "/");
                this.xdr.send("Data");

                assert.equals(this.xdr.requestBody, "Data");
            },
            "sets error flag to false": function () {
                this.xdr.open("POST", "/");
                this.xdr.send("Data");

                assert.isFalse(this.xdr.errorFlag);
            },

            "sets send flag to true": function () {
                this.xdr.open("POST", "/");
                this.xdr.send("Data");

                assert.isTrue(this.xdr.sendFlag);
            },
            "calls readyStateChange": function () {
                this.xdr.open("POST", "/", false);
                var spy = sinon.spy();
                this.xdr.readyStateChange = spy;

                this.xdr.send("Data");

                assert.equals(this.xdr.readyState, sinon.FakeXDomainRequest.OPENED);
                assert.isTrue(spy.called);
            },
        },

        "setResponseBody": {
            setUp: function () {
                this.xdr = new sinon.FakeXDomainRequest();
                this.xdr.open("GET", "/");
                this.xdr.send();
            },
            "invokes readyStateChange handler with LOADING state": function () {
                var spy = sinon.spy();
                this.xdr.readyStateChange = spy;

                this.xdr.setResponseBody("Some text goes in here ok?");

                assert(spy.calledWith(sinon.FakeXDomainRequest.LOADING));
            },
            "fire onprogress event": function() {
                var spy = sinon.spy();
                this.xdr.onprogress = spy;

                this.xdr.setResponseBody("Some text goes in here ok?");

                assert.isTrue(spy.called);
            },
            "invokes readyStateChange handler for each 10 byte chunk": function () {
                var spy = sinon.spy();
                this.xdr.readyStateChange = spy;
                this.xdr.chunkSize = 10;

                this.xdr.setResponseBody("Some text goes in here ok?");

                assert.equals(spy.callCount, 4);
            },
            "invokes readyStateChange handler for each x byte chunk": function () {
                var spy = sinon.spy();
                this.xdr.readyStateChange = spy;
                this.xdr.chunkSize = 20;

                this.xdr.setResponseBody("Some text goes in here ok?");

                assert.equals(spy.callCount, 3);
            },
            "invokes readyStateChange handler with partial data": function () {
                var pieces = [];

                var spy = sinon.spy(function () {
                    pieces.push(this.responseText);
                });

                this.xdr.readyStateChange = spy;
                this.xdr.chunkSize = 9;

                this.xdr.setResponseBody("Some text goes in here ok?");

                assert.equals(pieces[1], "Some text");
            },
            "calls readyStateChange with DONE state": function () {
                var spy = sinon.spy();
                this.xdr.readyStateChange = spy;

                this.xdr.setResponseBody("Some text goes in here ok?");

                assert(spy.calledWith(sinon.FakeXDomainRequest.DONE));
            },
            "throws if not open": function () {
                var xdr = new sinon.FakeXDomainRequest();

                assert.exception(function () {
                    xdr.setResponseBody("");
                });
            },
            "throws if body was already sent": function () {
                var xdr = new sinon.FakeXDomainRequest();
                xdr.open("GET", "/");
                xdr.send();
                xdr.setResponseBody("");

                assert.exception(function () {
                    xdr.setResponseBody("");
                });
            },
            "throws if body is not a string": function () {
                var xdr = new sinon.FakeXDomainRequest();
                xdr.open("GET", "/");
                xdr.send();

                assert.exception(function () {
                    xdr.setResponseBody({});
                }, "InvalidBodyException");
            }
        },

        "respond": {
            setUp: function () {
                this.xdr = new sinon.FakeXDomainRequest();
                this.xdr.open("GET", "/");
                var spy = this.spy = sinon.spy();
                this.xdr.onload = spy.call(this);
                this.xdr.send();
            },
            "fire onload event": function () {
                this.onload = this.spy;
                this.xdr.respond(200, {}, "");
                assert.equals(this.spy.callCount, 1);
            },
            "fire onload event with this set to the XHR object": function (done) {
                var xdr = new sinon.FakeXDomainRequest();
                xdr.open("GET", "/");

                xdr.onload = function() {
                    assert.same(this, xdr);
                    done();
                };

                xdr.send();
                xdr.respond(200, {}, "");
            },
            "calls readystate handler with readyState DONE once": function () {
                this.xdr.respond(200, {}, "");

                assert.equals(this.spy.callCount, 1);
            },
            "defaults to status 200, no headers, and blank body": function () {
                this.xdr.respond();

                assert.equals(this.xdr.status, 200);
                assert.equals(this.xdr.responseText, "");
            },
            "sets status": function () {
                this.xdr.respond(201);

                assert.equals(this.xdr.status, 201);
            }
        },

        "simulatetimeout": {
            setUp: function () {
                this.xdr = new sinon.FakeXDomainRequest();
                this.xdr.open("GET", "/");
                this.xdr.send();
                this.xdr.timeout = 100;
            },
            "fires ontimeout event": function() {
                var spy = sinon.spy();
                this.xdr.ontimeout = spy;

                this.xdr.simulatetimeout();

                assert.isTrue(this.xdr.isTimeout);
                assert.isTrue(spy.called);
            },
            "readyState is DONE": function() {
                this.xdr.simulatetimeout();

                assert.equals(this.xdr.readyState, sinon.FakeXDomainRequest.DONE);
            },

            "ensures responseText is not accessible": function(){
                var spy = sinon.spy();
                this.xdr.ontimeout = spy;

                this.xdr.simulatetimeout();

                assert.isTrue(spy.called);
                refute.defined(this.xdr.responseText);
            }
        },

        "abort": {
            setUp: function () {
                this.xdr = new sinon.FakeXDomainRequest();
            },
            "sets aborted flag to true": function () {
                this.xdr.aborted = true;

                this.xdr.abort();

                assert.isTrue(this.xdr.aborted);
            },
            "sets responseText to null": function () {
                this.xdr.responseText = "Partial data";

                this.xdr.abort();

                assert.isNull(this.xdr.responseText);
            },
            "sets errorFlag to true": function () {
                this.xdr.errorFlag = true;

                this.xdr.abort();

                assert.isTrue(this.xdr.errorFlag);
            },
            "fire onerror event": function () {
                var spy = sinon.spy();
                this.xdr.onerror = spy;

                this.xdr.open("GET", "/");
                this.xdr.send();
                this.xdr.abort();

                assert.equals(spy.callCount, 1);
            },
            "sets state to DONE if sent before": function () {
                this.xdr.open("GET", "/");
                this.xdr.send();

                this.xdr.readyStateChange = sinon.spy();

                this.xdr.abort();

                assert(this.xdr.readyStateChange.calledWith(sinon.FakeXDomainRequest.DONE));
            },
            "sets send flag to false if sent before": function () {
                this.xdr.open("GET", "/");
                this.xdr.send();

                this.xdr.abort();

                assert.isFalse(this.xdr.sendFlag);
            },
            "does not dispatch readystatechange event if readyState is unsent": function () {
                this.xdr.readyStateChange = sinon.stub();

                this.xdr.abort();

                assert.isFalse(this.xdr.readyStateChange.called);
            },
            "does not dispatch readystatechange event if readyState is opened but not sent": function () {
                this.xdr.open("GET", "/");
                this.xdr.readyStateChange = sinon.stub();

                this.xdr.abort();

                assert.isFalse(this.xdr.readyStateChange.called);
            }
        },

        "missing native XDR": {
            requiresSupportFor: { "no native XDR": typeof XDomainRequest == "undefined" },
            setUp: fakeXdrSetUp,
            tearDown: fakeXdrTearDown,

            "does not expose XDomainRequest": function () {
                assert.equals(typeof XDomainRequest, "undefined");
            },

            "does not expose XDomainRequest after restore": function () {
                this.fakeXdr.restore();

                assert.equals(typeof XDomainRequest, "undefined");
            }
        },

        "native XDR": {
            requiresSupportFor: { "XDR": typeof XDomainRequest !== "undefined" },
            setUp: fakeXdrSetUp,
            tearDown: fakeXdrTearDown,

            "replaces global XDomainRequest": function () {
                refute.same(XDomainRequest, globalXDomainRequest);
                assert.same(XDomainRequest, sinon.FakeXDomainRequest);
            },

            "restores global XDomainRequest": function () {
                this.fakeXdr.restore();

                assert.same(XDomainRequest, globalXDomainRequest);
            }
        },

    });

})(this);
<|endoftext|>


<commit_before>import path from 'path';

import { shell, BrowserWindow } from 'electron';

export function deferURL(event, url) {
  event.preventDefault();
  shell.openExternal(url);
}

export function launch(filename) {
  let iconPath = '';
  if (process.argv[0].match(/electron/i)) {
    iconPath = './static/icon.png';
  } else {
    iconPath = '.cd/resources/app/static/icon.png';
  }

  let win = new BrowserWindow({
    width: 800,
    height: 1000,
    icon: iconPath,
    title: 'nteract',
  });

  const index = path.join(__dirname, '..', '..', 'static', 'index.html');
  win.loadURL(`file://${index}`);

  win.webContents.on('did-finish-load', () => {
    if (filename) {
      win.webContents.send('main:load', filename);
    }
    // TODO: else, we assume it's an empty notebook
    //       assumption right now is that launchNewNotebook will handle the follow on
  });

  win.webContents.on('will-navigate', deferURL);

  // Emitted when the window is closed.
  win.on('closed', () => {
    win = null;
  });
  return win;
}

export function launchNewNotebook(kernelSpecName) {
  const win = launch();
  win.webContents.on('did-finish-load', () => {
    win.webContents.send('main:new', kernelSpecName);
  });
  return win;
}
<commit_msg>fix(icon): resolve full path for icon relatively, once<commit_after>import path from 'path';

import { shell, BrowserWindow } from 'electron';

export function deferURL(event, url) {
  event.preventDefault();
  shell.openExternal(url);
}

const iconPath = path.join(__dirname, '../../static/icon.png');

export function launch(filename) {
  let win = new BrowserWindow({
    width: 800,
    height: 1000,
    icon: iconPath,
    title: 'nteract',
  });

  const index = path.join(__dirname, '..', '..', 'static', 'index.html');
  win.loadURL(`file://${index}`);

  win.webContents.on('did-finish-load', () => {
    if (filename) {
      win.webContents.send('main:load', filename);
    }
    // TODO: else, we assume it's an empty notebook
    //       assumption right now is that launchNewNotebook will handle the follow on
  });

  win.webContents.on('will-navigate', deferURL);

  // Emitted when the window is closed.
  win.on('closed', () => {
    win = null;
  });
  return win;
}

export function launchNewNotebook(kernelSpecName) {
  const win = launch();
  win.webContents.on('did-finish-load', () => {
    win.webContents.send('main:new', kernelSpecName);
  });
  return win;
}
<|endoftext|>


<commit_before>"use strict";

const exec = require("child_process").execFile;
const path = require("path");
let logger = () => {};
let workingDir = __dirname;

var setDir = function(d) {
  // eslint-disable-next-line no-console
  console.log("!!!!!", d);
  workingDir = d;
};

var setLogger = function(l) {
  logger = l;
};

/**
 * lock the screen when the saver deactivates. currently this only works on OSX and Windows
 */
var doLockScreen = function() {
  var cmd;
  let args = [];

  if ( process.platform === "darwin" ) {
    cmd = "/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession";
    args = ["-suspend"];
  }
  else if ( process.platform === "win32" ) {
    // @see http://superuser.com/questions/21179/command-line-cmd-command-to-lock-a-windows-machine
    cmd = "rundll32.exe";
    args = ["user32.dll,LockWorkStation"];
  }
  else {
    cmd = path.join(workingDir, "bin", "lock-screen.sh");
    args = [];
  }

  logger(cmd, args);

  exec(cmd, args, function(error, stdout, stderr) {
    if (error !== null) {
      logger("doLockScreen error: " + error);
      logger("stdout: " + stdout);
      logger("stderr: " + stderr);
    }
  });
};

/**
 * put the display to sleep
 */
var doSleep = function() {
  var cmd;
  let args = [];

  if ( process.platform === "darwin" ) {
    cmd = "pmset";
    args = ["displaysleepnow"];
  }
  else if ( process.platform === "win32" ) {
    // this uses a 3rd party library -- nircmd -- to turn off the monitor
    // http://www.nirsoft.net/utils/nircmd.html
    // NOTE: this doesn't work in development mode right now because the path is wrong
    cmd = path.join(workingDir, "bin", "nircmd.exe");
    args = ["monitor", "off"];
  }
  else {
    // in linux, we use the same command to lock/skeep
    cmd = path.join(workingDir, "bin", "lock-screen.sh");
    args = [];
  }

  logger(cmd, args);

  exec(cmd, args, function(error, stdout, stderr) {
    if (error !== null) {
      logger("doSleep exec error: " + error);
      logger("stdout: " + stdout);
      logger("stderr: " + stderr);
    }
  });
};

exports.setLogger = setLogger;
exports.setDir = setDir;
exports.doLockScreen = doLockScreen;
exports.doSleep = doSleep;
<commit_msg>Remove debugging<commit_after>"use strict";

const exec = require("child_process").execFile;
const path = require("path");
let logger = () => {};
let workingDir = __dirname;

var setDir = function(d) {
  workingDir = d;
};

var setLogger = function(l) {
  logger = l;
};

/**
 * lock the screen when the saver deactivates. currently this only works on OSX and Windows
 */
var doLockScreen = function() {
  var cmd;
  let args = [];

  if ( process.platform === "darwin" ) {
    cmd = "/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession";
    args = ["-suspend"];
  }
  else if ( process.platform === "win32" ) {
    // @see http://superuser.com/questions/21179/command-line-cmd-command-to-lock-a-windows-machine
    cmd = "rundll32.exe";
    args = ["user32.dll,LockWorkStation"];
  }
  else {
    cmd = path.join(workingDir, "bin", "lock-screen.sh");
    args = [];
  }

  logger(cmd, args);

  exec(cmd, args, function(error, stdout, stderr) {
    if (error !== null) {
      logger("doLockScreen error: " + error);
      logger("stdout: " + stdout);
      logger("stderr: " + stderr);
    }
  });
};

/**
 * put the display to sleep
 */
var doSleep = function() {
  var cmd;
  let args = [];

  if ( process.platform === "darwin" ) {
    cmd = "pmset";
    args = ["displaysleepnow"];
  }
  else if ( process.platform === "win32" ) {
    // this uses a 3rd party library -- nircmd -- to turn off the monitor
    // http://www.nirsoft.net/utils/nircmd.html
    // NOTE: this doesn't work in development mode right now because the path is wrong
    cmd = path.join(workingDir, "bin", "nircmd.exe");
    args = ["monitor", "off"];
  }
  else {
    // in linux, we use the same command to lock/skeep
    cmd = path.join(workingDir, "bin", "lock-screen.sh");
    args = [];
  }

  logger(cmd, args);

  exec(cmd, args, function(error, stdout, stderr) {
    if (error !== null) {
      logger("doSleep exec error: " + error);
      logger("stdout: " + stdout);
      logger("stderr: " + stderr);
    }
  });
};

exports.setLogger = setLogger;
exports.setDir = setDir;
exports.doLockScreen = doLockScreen;
exports.doSleep = doSleep;
<|endoftext|>


<commit_before>import webWorkerManager from './webWorkerManager.js';
import decodeJPEGBaseline8BitColor from './decodeJPEGBaseline8BitColor.js';

function addDecodeTask (imageFrame, transferSyntax, pixelData, options) {
  const priority = options.priority || undefined;
  const transferList = options.transferPixelData ? [pixelData.buffer] : undefined;

  return webWorkerManager.addTask(
    'decodeTask',
    {
      imageFrame,
      transferSyntax,
      pixelData,
      options
    }, priority, transferList).promise;
}

function decodeImageFrame (imageFrame, transferSyntax, pixelData, canvas, options = {}) {
  // TODO: Turn this into a switch statement instead
  if (transferSyntax === '1.2.840.10008.1.2') {
    // Implicit VR Little Endian
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.1') {
    // Explicit VR Little Endian
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.2') {
    // Explicit VR Big Endian (retired)
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.1.99') {
    // Deflate transfer syntax (deflated by dicomParser)
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.5') {
    // RLE Lossless
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.50') {
    // JPEG Baseline lossy process 1 (8 bit)

    // Handle 8-bit JPEG Baseline color images using the browser's built-in
    // JPEG decoding
    if (imageFrame.bitsAllocated === 8 &&
       (imageFrame.samplesPerPixel === 3 || imageFrame.samplesPerPixel === 4)) {
      return decodeJPEGBaseline8BitColor(imageFrame, pixelData, canvas);
    }

    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.51') {
    // JPEG Baseline lossy process 2 & 4 (12 bit)
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.57') {
    // JPEG Lossless, Nonhierarchical (Processes 14)
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.70') {
    // JPEG Lossless, Nonhierarchical (Processes 14 [Selection 1])
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.80') {
    // JPEG-LS Lossless Image Compression
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.81') {
    // JPEG-LS Lossy (Near-Lossless) Image Compression
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.90') {
    // JPEG 2000 Lossless
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.91') {
    // JPEG 2000 Lossy
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  }

  /* Don't know if these work...
   // JPEG 2000 Part 2 Multicomponent Image Compression (Lossless Only)
   else if(transferSyntax === "1.2.840.10008.1.2.4.92")
   {
   return cornerstoneWADOImageLoader.decodeJPEG2000(dataSet, frame);
   }
   // JPEG 2000 Part 2 Multicomponent Image Compression
   else if(transferSyntax === "1.2.840.10008.1.2.4.93")
   {
   return cornerstoneWADOImageLoader.decodeJPEG2000(dataSet, frame);
   }
   */

  throw new Error(`No decoder for transfer syntax ${transferSyntax}`);
}

export default decodeImageFrame;
<commit_msg>fix(180): Avoid throwing exception for missing transfer syntax decoder (#181)<commit_after>import webWorkerManager from './webWorkerManager.js';
import decodeJPEGBaseline8BitColor from './decodeJPEGBaseline8BitColor.js';

function addDecodeTask (imageFrame, transferSyntax, pixelData, options) {
  const priority = options.priority || undefined;
  const transferList = options.transferPixelData ? [pixelData.buffer] : undefined;

  return webWorkerManager.addTask(
    'decodeTask',
    {
      imageFrame,
      transferSyntax,
      pixelData,
      options
    }, priority, transferList).promise;
}

function decodeImageFrame (imageFrame, transferSyntax, pixelData, canvas, options = {}) {
  // TODO: Turn this into a switch statement instead
  if (transferSyntax === '1.2.840.10008.1.2') {
    // Implicit VR Little Endian
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.1') {
    // Explicit VR Little Endian
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.2') {
    // Explicit VR Big Endian (retired)
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.1.99') {
    // Deflate transfer syntax (deflated by dicomParser)
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.5') {
    // RLE Lossless
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.50') {
    // JPEG Baseline lossy process 1 (8 bit)

    // Handle 8-bit JPEG Baseline color images using the browser's built-in
    // JPEG decoding
    if (imageFrame.bitsAllocated === 8 &&
       (imageFrame.samplesPerPixel === 3 || imageFrame.samplesPerPixel === 4)) {
      return decodeJPEGBaseline8BitColor(imageFrame, pixelData, canvas);
    }

    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.51') {
    // JPEG Baseline lossy process 2 & 4 (12 bit)
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.57') {
    // JPEG Lossless, Nonhierarchical (Processes 14)
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.70') {
    // JPEG Lossless, Nonhierarchical (Processes 14 [Selection 1])
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.80') {
    // JPEG-LS Lossless Image Compression
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.81') {
    // JPEG-LS Lossy (Near-Lossless) Image Compression
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.90') {
    // JPEG 2000 Lossless
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  } else if (transferSyntax === '1.2.840.10008.1.2.4.91') {
    // JPEG 2000 Lossy
    return addDecodeTask(imageFrame, transferSyntax, pixelData, options);
  }

  /* Don't know if these work...
   // JPEG 2000 Part 2 Multicomponent Image Compression (Lossless Only)
   else if(transferSyntax === "1.2.840.10008.1.2.4.92")
   {
   return cornerstoneWADOImageLoader.decodeJPEG2000(dataSet, frame);
   }
   // JPEG 2000 Part 2 Multicomponent Image Compression
   else if(transferSyntax === "1.2.840.10008.1.2.4.93")
   {
   return cornerstoneWADOImageLoader.decodeJPEG2000(dataSet, frame);
   }
   */

  return new Promise((resolve, reject) => {
    reject(new Error(`No decoder for transfer syntax ${transferSyntax}`));
  });
}

export default decodeImageFrame;
<|endoftext|>


<commit_before>/**
 * jQuery Accordion Live Filter
 * @author Aaron Saray
 */
;(function($) {
    "use strict";

    /**
     * Accordion Live Filter Class
     *
     * @param element The filter field
     * @param options {*} Options object
     * @constructor
     */
    var AccordionLiveFilter = function(element, options) {

        this.settings = $.extend({
            dataAccordionReference: 'alf',
            clearFilterClass: 'alf-filter-clear',
            matchedClass: 'alf-matched',
            expandedClass: 'alf-expanded'
        }, options);

        this.$filterElement = $(element);
        this.$accordion = this.getAccordion();

        this.addAccordionRelationshipsAndHandlers();
        this.addFilterHandler();
        this.addFilterClear();
    };

    /**
     * Gets the associated accordion to the filter field
     *
     * This will throw an error if its not found
     * @returns {*|HTMLElement}
     */
    AccordionLiveFilter.prototype.getAccordion = function() {
        var selector = this.$filterElement.data(this.settings.dataAccordionReference);
        if (!selector) {
            throw new Error('The accordion search filter element needs a data-' + this.settings.dataAccordionReference + ' element with a jquery selector.');
        }

        var $accordion = $(selector);
        if ($accordion.length == 0) {
            throw new Error('The selector ' + selector + ' was not found.');
        }
        return $accordion;
    };

    /**
     * Add the delete button to the item
     */
    AccordionLiveFilter.prototype.addFilterClear = function() {
        var $delete = $('×').addClass(this.settings.clearFilterClass);
        $delete.on('click', function(e) {
            e.preventDefault();
            this.$filterElement.val('');
            $('label', this.$accordion).trigger('contract.alf');
            $('li', this.$accordion).removeClass('potential');
        }.bind(this));
        this.$filterElement.after($delete);
    };

    /**
     * Add handler for the accordion and the relationship between the filter and the accordion
     */
    AccordionLiveFilter.prototype.addAccordionRelationshipsAndHandlers = function() {
        var self = this;

        $('label', this.$accordion).each(function(i, label) {
            var $label = $(label);
            var $ul = $label.next('ul');

            /** here, add the handlers for the label **/
            $label.on('expand.alf', function() {
                $(this).addClass(self.settings.expandedClass);
                $ul.slideDown();
            }).on('contract.alf', function() {
                $(this).removeClass(self.settings.expandedClass);
                $ul.slideUp();
            }).on('click', function() {
                var $label = $(this);
                $label.hasClass(self.settings.expandedClass) ? $label.trigger('contract.alf') : $label.trigger('expand.alf');
            });

            /** now, cache the relationships so we don't always have to traverse **/
            $label.data('alf-child', $ul);
            $ul.data('alf-parent', $label);
        });
    };

    /**
     * Add the filter handler
     */
    AccordionLiveFilter.prototype.addFilterHandler = function() {
        var self = this;

        this.$filterElement.on('keyup change', function() {

            var query = this.value.toLowerCase();

            $('li > ul', self.$accordion).each(function(i, ul) {
                var $ul = $(ul),
                    $ulParent = $ul.data('alf-parent'),
                    $ulChildren = $ul.children(),
                    trigger = 'contract.alf';

                $ulChildren.removeClass(self.settings.matchedClass);
                if (query) {
                    if ($ul.text().toLowerCase().indexOf(query) >= 0) {
                        $ulChildren.each(function(i, li) {
                            var $li = $(li);
                            if ($li.text().toLowerCase().indexOf(query) >= 0) {
                                $li.addClass(self.settings.matchedClass);
                            }
                        });
                        trigger = 'expand.alf';
                    }
                }
                $ulParent.trigger(trigger);
            });
        });

    };

    /**
     * Plugin Proxy for jQuery
     * @param options
     * @returns {*}
     * @constructor
     */
    function Plugin(options) {
        return this.each(function() {
            new AccordionLiveFilter(this, options);
        });
    }

    $.fn.accordionLiveFilter = Plugin;
}(jQuery));

<commit_msg>update js to keep comment<commit_after>/*!
 * jQuery Accordion Live Filter
 * @author Aaron Saray
 */
;(function($) {
    "use strict";

    /**
     * Accordion Live Filter Class
     *
     * @param element The filter field
     * @param options {*} Options object
     * @constructor
     */
    var AccordionLiveFilter = function(element, options) {

        this.settings = $.extend({
            dataAccordionReference: 'alf',
            clearFilterClass: 'alf-filter-clear',
            matchedClass: 'alf-matched',
            expandedClass: 'alf-expanded'
        }, options);

        this.$filterElement = $(element);
        this.$accordion = this.getAccordion();

        this.addAccordionRelationshipsAndHandlers();
        this.addFilterHandler();
        this.addFilterClear();
    };

    /**
     * Gets the associated accordion to the filter field
     *
     * This will throw an error if its not found
     * @returns {*|HTMLElement}
     */
    AccordionLiveFilter.prototype.getAccordion = function() {
        var selector = this.$filterElement.data(this.settings.dataAccordionReference);
        if (!selector) {
            throw new Error('The accordion search filter element needs a data-' + this.settings.dataAccordionReference + ' element with a jquery selector.');
        }

        var $accordion = $(selector);
        if ($accordion.length == 0) {
            throw new Error('The selector ' + selector + ' was not found.');
        }
        return $accordion;
    };

    /**
     * Add the delete button to the item
     */
    AccordionLiveFilter.prototype.addFilterClear = function() {
        var $delete = $('×').addClass(this.settings.clearFilterClass);
        $delete.on('click', function(e) {
            e.preventDefault();
            this.$filterElement.val('');
            $('label', this.$accordion).trigger('contract.alf');
            $('li', this.$accordion).removeClass('potential');
        }.bind(this));
        this.$filterElement.after($delete);
    };

    /**
     * Add handler for the accordion and the relationship between the filter and the accordion
     */
    AccordionLiveFilter.prototype.addAccordionRelationshipsAndHandlers = function() {
        var self = this;

        $('label', this.$accordion).each(function(i, label) {
            var $label = $(label);
            var $ul = $label.next('ul');

            /** here, add the handlers for the label **/
            $label.on('expand.alf', function() {
                $(this).addClass(self.settings.expandedClass);
                $ul.slideDown();
            }).on('contract.alf', function() {
                $(this).removeClass(self.settings.expandedClass);
                $ul.slideUp();
            }).on('click', function() {
                var $label = $(this);
                $label.hasClass(self.settings.expandedClass) ? $label.trigger('contract.alf') : $label.trigger('expand.alf');
            });

            /** now, cache the relationships so we don't always have to traverse **/
            $label.data('alf-child', $ul);
            $ul.data('alf-parent', $label);
        });
    };

    /**
     * Add the filter handler
     */
    AccordionLiveFilter.prototype.addFilterHandler = function() {
        var self = this;

        this.$filterElement.on('keyup change', function() {

            var query = this.value.toLowerCase();

            $('li > ul', self.$accordion).each(function(i, ul) {
                var $ul = $(ul),
                    $ulParent = $ul.data('alf-parent'),
                    $ulChildren = $ul.children(),
                    trigger = 'contract.alf';

                $ulChildren.removeClass(self.settings.matchedClass);
                if (query) {
                    if ($ul.text().toLowerCase().indexOf(query) >= 0) {
                        $ulChildren.each(function(i, li) {
                            var $li = $(li);
                            if ($li.text().toLowerCase().indexOf(query) >= 0) {
                                $li.addClass(self.settings.matchedClass);
                            }
                        });
                        trigger = 'expand.alf';
                    }
                }
                $ulParent.trigger(trigger);
            });
        });

    };

    /**
     * Plugin Proxy for jQuery
     * @param options
     * @returns {*}
     * @constructor
     */
    function Plugin(options) {
        return this.each(function() {
            new AccordionLiveFilter(this, options);
        });
    }

    $.fn.accordionLiveFilter = Plugin;
}(jQuery));

<|endoftext|>