<commit_before>'use strict';

function modInputs(numChoices, allChoices) {
  var result = $('.choice-wrapper');
  var renderFunc = Handlebars.compile($('#choice-template').html());
  if (numChoices > result.length) {
    var toAdd = numChoices - result.length;
    for (var a = 0; a < toAdd; a++) {
      if (!allChoices) {
        var choiceToAdd = renderFunc({choiceText: '#choice', choiceColor: '#ffffff', baseVal: 0});
        $('#choice-result').append(choiceToAdd);
      }
      else {
        var choiceToAdd = renderFunc({choiceText: allChoices[a].choice_text, choiceColor: allChoices[a].choice_color, baseVal: allChoices[a].value});
        $('#choice-result').append(choiceToAdd);
      }
    }
  } else if (numChoices < result.length) {
    var toRemove = result.length - numChoices;
    for (var a = 1; a <= toRemove; a++) {
      result.eq(result.length - a).remove();
    }
  }
}

$('#poll-choices').on('change', function () {
  modInputs(this.value);
});

$('#test-button').on('click', function (e){
  e.preventDefault();
  window.open(`https://bittoolscod301.herokuapp.com/user=${userInfo.currentUser}`,'pagename','resizable,height=400,width=260,screenX=1000,left=700,screenY=1000,top=350');
  return false;
});

var userChoices;

function renderWidget() {
  $.get(`/choices/${userInfo.currentUser}`, function (data) {
    userChoices = data;
    var renderFunc = Handlebars.compile($('#form-template').html());
    console.log(userChoices);
    if (userChoices.length === 0) {
      var theForm = renderFunc({widgetText: '', textColor: '#000000', fillColor: '#666666', googleFont: 'Baloo'});
      $('#widget-form').prepend(theForm);
      modInputs(2, null);
      $('#poll-choices').val(2);
      // $('#goal').val(500);
    } else {
      var theForm = renderFunc({widgetText: userChoices[0].widget_text, textColor: userChoices[0].text_color, goal: 500, fillColor: userChoices[0].fill_color, googleFont: userChoices[0].google_font});
      $('#widget-form').prepend(theForm);
      modInputs(userChoices.length, userChoices);
      $('#poll-choices').val(userChoices.length);
    }
    $('#browser-source').val(`https://bittoolscod301.herokuapp.com/user=${userInfo.currentUser}`);
  });
};

$('#save-all').click(function(e) {
  e.preventDefault();
  console.log('You clicked SAVE');
  deleteChoices(insertRows);
});

function insertRows() {
  var widgetText = $('#widget-title').val();
  var textColor = $('#widget-color').val();
  var fillColor = $('#fill-color').val();
  // var goal = $('#goal').val();
  var totalChoices = $('.choice-wrapper');
  var userFont = $('#google-font').val();

  for (var a = 0; a < totalChoices.length; a++) {
    var thisChoice = totalChoices.eq(a).find('.choice-input').val();
    var thisColor = totalChoices.eq(a).find('.choice-color').val();
    var thisVal = totalChoices.eq(a).find('.base-value').val();
    insertChoice(userInfo.currentUser, widgetText, textColor, fillColor, thisChoice, thisColor, thisVal, userFont);
  }
}

$('#logout').click(function(e) {
  e.preventDefault();
  localStorage.clear();
  checkLogin();
});

$('#clear-all').click(function(e) {
  e.preventDefault();
  $('#widget-title').val('');
  $('#widget-color').val('#000000');
  $('#fill-color').val('#666666');
  // $('#goal').val(500);
  $('#google-font').val('Baloo');
  var totalChoices = $('.choice-wrapper');

  for (var a = 0; a < totalChoices.length; a++) {
    totalChoices.eq(a).find('.choice-input').val('');
    totalChoices.eq(a).find('.choice-color').val('#ffffff');
    totalChoices.eq(a).find('.base-value').val(0);
  }
});
<commit_msg>fixing goals<commit_after>'use strict';

function modInputs(numChoices, allChoices) {
  var result = $('.choice-wrapper');
  var renderFunc = Handlebars.compile($('#choice-template').html());
  if (numChoices > result.length) {
    var toAdd = numChoices - result.length;
    for (var a = 0; a < toAdd; a++) {
      if (!allChoices) {
        var choiceToAdd = renderFunc({choiceText: '#choice', choiceColor: '#ffffff', baseVal: 0});
        $('#choice-result').append(choiceToAdd);
      }
      else {
        var choiceToAdd = renderFunc({choiceText: allChoices[a].choice_text, choiceColor: allChoices[a].choice_color, baseVal: allChoices[a].value});
        $('#choice-result').append(choiceToAdd);
      }
    }
  } else if (numChoices < result.length) {
    var toRemove = result.length - numChoices;
    for (var a = 1; a <= toRemove; a++) {
      result.eq(result.length - a).remove();
    }
  }
}

$('#poll-choices').on('change', function () {
  modInputs(this.value);
});

$('#test-button').on('click', function (e){
  e.preventDefault();
  window.open(`https://bittoolscod301.herokuapp.com/user=${userInfo.currentUser}`,'pagename','resizable,height=400,width=260,screenX=1000,left=700,screenY=1000,top=350');
  return false;
});

var userChoices;

function renderWidget() {
  $.get(`/choices/${userInfo.currentUser}`, function (data) {
    userChoices = data;
    var renderFunc = Handlebars.compile($('#form-template').html());
    console.log(userChoices);
    if (userChoices.length === 0) {
      var theForm = renderFunc({widgetText: '', textColor: '#000000', fillColor: '#666666', googleFont: 'Baloo'});
      $('#widget-form').prepend(theForm);
      modInputs(2, null);
      $('#poll-choices').val(2);
      // $('#goal').val(500);
    } else {
      var theForm = renderFunc({widgetText: userChoices[0].widget_text, textColor: userChoices[0].text_color, goal: 500, fillColor: userChoices[0].fill_color, googleFont: userChoices[0].google_font});
      $('#widget-form').prepend(theForm);
      modInputs(userChoices.length, userChoices);
      $('#poll-choices').val(userChoices.length);
    }
    $('#browser-source').val(`https://bittoolscod301.herokuapp.com/user=${userInfo.currentUser}`);
  });
};

$('#save-all').click(function(e) {
  e.preventDefault();
  console.log('You clicked SAVE');
  deleteChoices(insertRows);
});

function insertRows() {
  var widgetText = $('#widget-title').val();
  var textColor = $('#widget-color').val();
  var fillColor = $('#fill-color').val();
  var goal = 500;
  var totalChoices = $('.choice-wrapper');
  var userFont = $('#google-font').val();

  for (var a = 0; a < totalChoices.length; a++) {
    var thisChoice = totalChoices.eq(a).find('.choice-input').val();
    var thisColor = totalChoices.eq(a).find('.choice-color').val();
    var thisVal = totalChoices.eq(a).find('.base-value').val();
    insertChoice(userInfo.currentUser, widgetText, textColor, fillColor, goal, thisChoice, thisColor, thisVal, userFont);
  }
}

$('#logout').click(function(e) {
  e.preventDefault();
  localStorage.clear();
  checkLogin();
});

$('#clear-all').click(function(e) {
  e.preventDefault();
  $('#widget-title').val('');
  $('#widget-color').val('#000000');
  $('#fill-color').val('#666666');
  // $('#goal').val(500);
  $('#google-font').val('Baloo');
  var totalChoices = $('.choice-wrapper');

  for (var a = 0; a < totalChoices.length; a++) {
    totalChoices.eq(a).find('.choice-input').val('');
    totalChoices.eq(a).find('.choice-color').val('#ffffff');
    totalChoices.eq(a).find('.base-value').val(0);
  }
});
<|endoftext|>


<commit_before>"use strict";

describe("define", function () {

    var test = {};

    before(function () {
        // Defines a namespace root
        gpf.context().test = test;
    });

    after(function () {
        delete gpf.context().test;
    });

    function _generateNamesValidation (typeName, Exception, names) {

        Object.keys(names).filter(function (name) {
            return !names[name];
        }).forEach(function (invalidName) {
            it("rejects invalid " + typeName + " name (" + invalidName + ")", function () {
                var exceptionCaught,
                    definition = {};
                definition["$" + typeName] = invalidName;
                try {
                    gpf.define(definition);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(exceptionCaught instanceof Exception);
            });
        });

        Object.keys(names).filter(function (name) {
            return names[name];
        }).forEach(function (validName) {
            it("accepts valid " + typeName + " name (" + validName + ")", function () {
                var exceptionCaught,
                    definition = {};
                definition["$" + typeName] = validName;
                try {
                    gpf.define(definition);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(undefined === exceptionCaught);
            });
        });

    }

    function _generateBasicValidations (descriptor) {
        it(descriptor.it, function () {
            var exceptionCaught;
            try {
                gpf.define(descriptor.definition);
            } catch (e) {
                exceptionCaught = e;
            }
            assert(exceptionCaught instanceof descriptor.exception);
        });
    }

    describe("gpf.define", function () {

        it("accepts only one parameter", function () {
            assert(typeof gpf.define === "function");
            assert(gpf.define.length === 1);
        });

        describe("Common validation", function () {

            _generateBasicValidations({
                it: "checks that the entity type is specified",
                definition: {},
                exception: gpf.Error.InvalidEntityType
            });

        });

        describe("Class definition", function () {

            describe("Validation", function () {

                _generateNamesValidation("class", gpf.Error.InvalidClassName, {
                    "1NumberAtTheBeginningIsNotOK": false,
                    "noUppercaseFirstLetterIsNotOK": false,
                    "DollarSignAnywhereIsNotOK$": false,
                    "A": true,
                    "$B": true,
                    "_C": true,
                    "Test123": true
                });

                [{
                    it: "rejects invalid $ property names",
                    definition: {
                        $class: "Test",
                        $test: false
                    },
                    exception: gpf.Error.InvalidEntity$Property

                }, {
                    it: "rejects invalid property names (reserved keywords)",
                    definition: {
                        $class: "Test",
                        "super": false
                    },
                    exception: gpf.Error.InvalidClassProperty

                }, {
                    it: "rejects constructor property if not a method",
                    definition: {
                        $class: "Test",
                        constructor: false
                    },
                    exception: gpf.Error.InvalidClassConstructor

                }].forEach(_generateBasicValidations);

            });

            describe("Implementation", function () {

                var A, a;

                before(function () {
                    A = gpf.define({
                        $class: "A",
                        _member: "defaultValue",
                        getMember: function () {
                            return this._member;
                        },
                        "constructor": function (memberValue) {
                            if (memberValue) {
                                this._member = memberValue;
                            }
                            this._constructorOfA = true;
                        },
                        funcWith3params: function (p1, p2, p3) {
                            return p1 + p2 + p3;
                        },
                        throwError: function () {
                            throw new Error("error");
                        }
                    });

                    a = new A();
                });

                it("prevents constructor functions to be used without new", function () {
                    var exceptionCaught;
                    try {
                        A(); // eslint-disable-line new-cap
                    } catch (e) {
                        exceptionCaught = e;
                    }
                    assert(exceptionCaught instanceof gpf.Error.ClassConstructorFunction);
                });

                it("creates a constructor with the same signature than the constructor property", function () {
                    assert(A.length === 1);
                });

                it("handles instanceof", function () {
                    assert(a instanceof A);
                });

                it("calls constructor property", function () {
                    assert(a._constructorOfA);
                });

                it("exposes methods", function () {
                    assert(typeof a.getMember === "function");
                    assert(a.getMember() === "defaultValue");
                });

                describe("Subclassing", function () {

                    it("prevents invalid override", function () {
                        var exceptionCaught;
                        try {
                            gpf.define({
                                $class: "Test",
                                $extend: A,
                                getMember: false
                            });
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassOverride);
                    });

                    var B, b;

                    before(function () {
                        B = gpf.define({
                            $class: "test.B",
                            $extend: A,
                            "constructor": function (initialValue) {
                                this.$super("valueOfB");
                                this._constructorOfB = initialValue;
                            },
                            getMember: function () {
                                return this.$super() + "-inB";
                            },
                            setMember: function (newValue) {
                                this._member = newValue;
                            },
                            baseTest: function () {
                                return this.$super.getMember();
                            },
                            invalidSuperMember: function () {
                                return this.$super.doesntExist();
                            },
                            noSuperMember: function () {
                                return this.$super();
                            },
                            differentBinding: function () {
                                return this.$super.getMember.call({
                                    _member: "different"
                                });
                            },
                            checkSignature: function () {
                                assert(this.$super.funcWith3params.length === 3);
                            },
                            throwError: function () {
                                this.$super();
                            }
                        });

                        b = new B(3475);
                    });

                    it("handles instanceof", function () {
                        assert(b instanceof A);
                        assert(b instanceof B);
                    });

                    it("handles namespace", function () {
                        assert(test.B === B);
                    });

                    it("calls the constructor function", function () {
                        assert(b._constructorOfB === 3475);
                    });

                    it("calls the proper $super()", function () {
                        assert(b._constructorOfA);
                        assert(b.getMember() === "valueOfB-inB");
                    });

                    it("offers a way to call named base method", function () {
                        assert(b.baseTest() === "valueOfB");
                    });

                    it("fails when accessing an unknown $super member", function () {
                        var exceptionCaught;
                        try {
                            b.invalidSuperMember();
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassSuperMember);
                    });

                    it("fails when accessing inexistent $super", function () {
                        var exceptionCaught;
                        try {
                            b.noSuperMember();
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassSuper);
                    });

                    it("allows calling $super member with a different binding", function () {
                        assert(b.differentBinding() === "different");
                    });

                    it("respects methods signature", function () {
                        b.checkSignature();
                    });

                    it("does not leak $super", function () {
                        assert(undefined === b.$super);
                    });

                    it("does not leak $super on exception", function () {
                        try {
                            b.throwError();
                        } catch (e) {
                            // ignore
                        }
                        assert(undefined === b.$super);
                    });

                    it("handles several versions of $super", function () {
                        var C = gpf.define({
                                $class: "C",
                                $extend: B,
                                testMethod: function () {
                                    return this.$super.getMember();
                                }
                            }),
                            c = new C();
                        assert(c.testMethod() === "valueOfB-inB");
                    });
                });

            });

        });

        describe("Interface definition", function () {

            describe("Validation", function () {

                _generateNamesValidation("interface", gpf.Error.InvalidInterfaceName, {
                    "1NumberAtTheBeginningIsNotOK": false,
                    "noUppercaseFirstLetterIsNotOK": false,
                    "DollarSignAnywhereIsNotOK$": false,
                    "NotStartingWithUppercaseI": false,
                    "A": false,
                    "$B": false,
                    "_C": false,
                    "Test123": false,
                    "ISample": true,
                    "IS": true
                });

                [{
                    it: "rejects interface if all members are not methods",
                    definition: {
                        $interface: "ITest",
                        member: false
                    },
                    exception: gpf.Error.InvalidInterfaceProperty

                }, {
                    it: "rejects invalid property names (reserved keywords)",
                    definition: {
                        $interface: "ITest",
                        "super": function () {
                        }
                    },
                    exception: gpf.Error.InvalidInterfaceProperty

                }, {
                    it: "rejects constructor property",
                    definition: {
                        $interface: "ITest",
                        constructor: function () {
                        }
                    },
                    exception: gpf.Error.InvalidInterfaceProperty

                }].forEach(_generateBasicValidations);

            });

            describe("Implementation", function () {

                var ITest = gpf.define({
                    $interface: "ITest",
                    test: function (value) {
                        return value;
                    }
                });

                it("can't be used as a class extend", function () {
                    var exceptionCaught;
                    try {
                        gpf.define({
                            $class: "Test",
                            $extend: ITest
                        });
                    } catch (e) {
                        exceptionCaught = e;
                    }
                    assert(exceptionCaught instanceof gpf.Error.InvalidClassExtend);
                });

            });

        });

    });

});
<commit_msg>Injecting ES6 tests (#304)<commit_after>"use strict";

describe("define", function () {

    var test = {};

    before(function () {
        // Defines a namespace root
        gpf.context().test = test;
    });

    after(function () {
        delete gpf.context().test;
    });

    function _generateNamesValidation (typeName, Exception, names) {

        Object.keys(names).filter(function (name) {
            return !names[name];
        }).forEach(function (invalidName) {
            it("rejects invalid " + typeName + " name (" + invalidName + ")", function () {
                var exceptionCaught,
                    definition = {};
                definition["$" + typeName] = invalidName;
                try {
                    gpf.define(definition);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(exceptionCaught instanceof Exception);
            });
        });

        Object.keys(names).filter(function (name) {
            return names[name];
        }).forEach(function (validName) {
            it("accepts valid " + typeName + " name (" + validName + ")", function () {
                var exceptionCaught,
                    definition = {};
                definition["$" + typeName] = validName;
                try {
                    gpf.define(definition);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(undefined === exceptionCaught);
            });
        });

    }

    function _generateBasicValidations (descriptor) {
        it(descriptor.it, function () {
            var exceptionCaught;
            try {
                gpf.define(descriptor.definition);
            } catch (e) {
                exceptionCaught = e;
            }
            assert(exceptionCaught instanceof descriptor.exception);
        });
    }

    describe("gpf.define", function () {

        it("accepts only one parameter", function () {
            assert(typeof gpf.define === "function");
            assert(gpf.define.length === 1);
        });

        describe("Common validation", function () {

            _generateBasicValidations({
                it: "checks that the entity type is specified",
                definition: {},
                exception: gpf.Error.InvalidEntityType
            });

        });

        describe("Class definition", function () {

            describe("Validation", function () {

                _generateNamesValidation("class", gpf.Error.InvalidClassName, {
                    "1NumberAtTheBeginningIsNotOK": false,
                    "noUppercaseFirstLetterIsNotOK": false,
                    "DollarSignAnywhereIsNotOK$": false,
                    "A": true,
                    "$B": true,
                    "_C": true,
                    "Test123": true
                });

                [{
                    it: "rejects invalid $ property names",
                    definition: {
                        $class: "Test",
                        $test: false
                    },
                    exception: gpf.Error.InvalidEntity$Property

                }, {
                    it: "rejects invalid property names (reserved keywords)",
                    definition: {
                        $class: "Test",
                        "super": false
                    },
                    exception: gpf.Error.InvalidClassProperty

                }, {
                    it: "rejects constructor property if not a method",
                    definition: {
                        $class: "Test",
                        constructor: false
                    },
                    exception: gpf.Error.InvalidClassConstructor

                }].forEach(_generateBasicValidations);

            });

            describe("Implementation", function () {

                var A, a;

                before(function () {
                    A = gpf.define({
                        $class: "A",
                        _member: "defaultValue",
                        getMember: function () {
                            return this._member;
                        },
                        "constructor": function (memberValue) {
                            if (memberValue) {
                                this._member = memberValue;
                            }
                            this._constructorOfA = true;
                        },
                        funcWith3params: function (p1, p2, p3) {
                            return p1 + p2 + p3;
                        },
                        throwError: function () {
                            throw new Error("error");
                        }
                    });

                    a = new A();
                });

                it("prevents constructor functions to be used without new", function () {
                    var exceptionCaught;
                    try {
                        A(); // eslint-disable-line new-cap
                    } catch (e) {
                        exceptionCaught = e;
                    }
                    assert(exceptionCaught instanceof gpf.Error.ClassConstructorFunction);
                });

                it("creates a constructor with the same signature than the constructor property", function () {
                    assert(A.length === 1);
                });

                it("handles instanceof", function () {
                    assert(a instanceof A);
                });

                it("calls constructor property", function () {
                    assert(a._constructorOfA);
                });

                it("exposes methods", function () {
                    assert(typeof a.getMember === "function");
                    assert(a.getMember() === "defaultValue");
                });

                describe("Subclassing", function () {

                    it("prevents invalid override", function () {
                        var exceptionCaught;
                        try {
                            gpf.define({
                                $class: "Test",
                                $extend: A,
                                getMember: false
                            });
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassOverride);
                    });

                    var B, b;

                    before(function () {
                        B = gpf.define({
                            $class: "test.B",
                            $extend: A,
                            "constructor": function (initialValue) {
                                this.$super("valueOfB");
                                this._constructorOfB = initialValue;
                            },
                            getMember: function () {
                                return this.$super() + "-inB";
                            },
                            setMember: function (newValue) {
                                this._member = newValue;
                            },
                            baseTest: function () {
                                return this.$super.getMember();
                            },
                            invalidSuperMember: function () {
                                return this.$super.doesntExist();
                            },
                            noSuperMember: function () {
                                return this.$super();
                            },
                            differentBinding: function () {
                                return this.$super.getMember.call({
                                    _member: "different"
                                });
                            },
                            checkSignature: function () {
                                assert(this.$super.funcWith3params.length === 3);
                            },
                            throwError: function () {
                                this.$super();
                            }
                        });

                        b = new B(3475);
                    });

                    it("handles instanceof", function () {
                        assert(b instanceof A);
                        assert(b instanceof B);
                    });

                    it("handles namespace", function () {
                        assert(test.B === B);
                    });

                    it("calls the constructor function", function () {
                        assert(b._constructorOfB === 3475);
                    });

                    it("calls the proper $super()", function () {
                        assert(b._constructorOfA);
                        assert(b.getMember() === "valueOfB-inB");
                    });

                    it("offers a way to call named base method", function () {
                        assert(b.baseTest() === "valueOfB");
                    });

                    it("fails when accessing an unknown $super member", function () {
                        var exceptionCaught;
                        try {
                            b.invalidSuperMember();
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassSuperMember);
                    });

                    it("fails when accessing inexistent $super", function () {
                        var exceptionCaught;
                        try {
                            b.noSuperMember();
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassSuper);
                    });

                    it("allows calling $super member with a different binding", function () {
                        assert(b.differentBinding() === "different");
                    });

                    it("respects methods signature", function () {
                        b.checkSignature();
                    });

                    it("does not leak $super", function () {
                        assert(undefined === b.$super);
                    });

                    it("does not leak $super on exception", function () {
                        try {
                            b.throwError();
                        } catch (e) {
                            // ignore
                        }
                        assert(undefined === b.$super);
                    });

                    it("handles several versions of $super", function () {
                        var C = gpf.define({
                                $class: "C",
                                $extend: B,
                                testMethod: function () {
                                    return this.$super.getMember();
                                }
                            }),
                            c = new C();
                        assert(c.testMethod() === "valueOfB-inB");
                    });
                });

            });

        });

        describe("Interface definition", function () {

            describe("Validation", function () {

                _generateNamesValidation("interface", gpf.Error.InvalidInterfaceName, {
                    "1NumberAtTheBeginningIsNotOK": false,
                    "noUppercaseFirstLetterIsNotOK": false,
                    "DollarSignAnywhereIsNotOK$": false,
                    "NotStartingWithUppercaseI": false,
                    "A": false,
                    "$B": false,
                    "_C": false,
                    "Test123": false,
                    "ISample": true,
                    "IS": true
                });

                [{
                    it: "rejects interface if all members are not methods",
                    definition: {
                        $interface: "ITest",
                        member: false
                    },
                    exception: gpf.Error.InvalidInterfaceProperty

                }, {
                    it: "rejects invalid property names (reserved keywords)",
                    definition: {
                        $interface: "ITest",
                        "super": function () {
                        }
                    },
                    exception: gpf.Error.InvalidInterfaceProperty

                }, {
                    it: "rejects constructor property",
                    definition: {
                        $interface: "ITest",
                        constructor: function () {
                        }
                    },
                    exception: gpf.Error.InvalidInterfaceProperty

                }].forEach(_generateBasicValidations);

            });

            describe("Implementation", function () {

                var ITest = gpf.define({
                    $interface: "ITest",
                    test: function (value) {
                        return value;
                    }
                });

                it("can't be used as a class extend", function () {
                    var exceptionCaught;
                    try {
                        gpf.define({
                            $class: "Test",
                            $extend: ITest
                        });
                    } catch (e) {
                        exceptionCaught = e;
                    }
                    assert(exceptionCaught instanceof gpf.Error.InvalidClassExtend);
                });

            });

        });

    });

});

if (gpf.host() === gpf.hosts.nodejs) {

    require(__dirname.replace(/\btest\b.*/, "test/define.es6.js"));

}
<|endoftext|>


<commit_before>import XHRProxy from './xhr-proxy';
import Shaper from './shaper';
import setupThrottledXhr from './setup-throttled-xhr';
import setupCachedXhr from './setup-cached-xhr';
import cache from './cache';

const PASSTHROUGH_EVENTS = ['loadstart', 'timeout', 'abort', 'error'];

const createListenerWrapper = (type, listener, dispatchedEventsList) => {
    return (event) => {
        dispatchedEventsList.push({type, listener, event, propagated: false});
    };
}

class XHR extends XHRProxy {

    static get Shaper() {
        return Shaper;
    }

    static get cache() {
        return cache;
    }

    constructor() {
        super();

        this._cacheInstance = cache.instance;
        this._shaper = new Shaper();
        this._listenersMap = new Map();
        this._dispatchedEventsList = [];
        this._response = null;
        this._responseText = null;
        this._responseXML = null;
        this._headers = null;
        this._readyState = 0;
        this._caching = false;
        this._cacheHit = false;
        this._cacheWrite = true;
        this._onSend = null;

        this.addEventListener('loadend', () => {
            if (this._caching && this._cacheWrite) {
                console.log('CACHE WRITE:', this._xhr.responseURL);
                this._cacheInstance.put(
                    this._xhr.responseURL,
                    this._response,
                    this._responseText,
                    this._responseXML,
                    null,
                    this._xhr.getAllResponseHeaders()
                );
            }
        });

        setupThrottledXhr(this._xhr, this);
    }

    get caching() {
       return this._caching;
    }

    set caching(enabled) {
        this._caching = enabled;
    }

    set cacheInstance(instance) {
        this._cacheInstance = instance;
    }

    get cacheInstance() {
        return this._cacheInstance;
    }

    get isCacheHit() {
        return this._cacheHit;
    }

    set cacheWriteEnabled(enable) {
        this._cacheWrite = enable;
    }

    get enableCacheWrite() {
        return this._cacheWrite;
    }

    get shaper() {
        return this._shaper;
    }

    _dispatchWrappedEventType(type) {
        // it needs to run on the next tick since this is actually
        // triggered from our throttler listeners on the proxy's inner XHR
        setTimeout(() => {
            this._dispatchedEventsList
                .filter((dispatchedEvent) => (dispatchedEvent.type === type && !dispatchedEvent.propagated))
                .forEach((dispatchedEvent) => {
                    dispatchedEvent.propagated = true;
                    dispatchedEvent.listener(dispatchedEvent.event);
                });
        }, 0);
    }

    _handleCacheHitOnSend(cachedResource) {
        this._readyState = 1;
        this._cacheHit = true;

        const onSend = () => {
            setTimeout(() => {
                this._readyState = 2;
                this.onreadystatechange && this.onreadystatechange();
                this._dispatchWrappedEventType('readystatechange');
                this._readyState = 3;
                this.onreadystatechange && this.onreadystatechange();
                this._dispatchWrappedEventType('readystatechange');
                this.onloadstart && this.onloadstart();
                this._dispatchWrappedEventType('loadstart');
                this._response = cachedResource.data;
                this._responseText = cachedResource.dataText;
                this._responseXML = cachedResource.dataXML;
                this._headersAll = cachedResource.headers;
                this._readyState = 4;
                this.onreadystatechange && this.onreadystatechange();
                this._dispatchWrappedEventType('readystatechange');
                this.onreadystatechange && this.onreadystatechange();
                this._dispatchWrappedEventType('readystatechange');
                this.onload && this.onload();
                this._dispatchWrappedEventType('load');
                this.onloadend && this.onloadend();
                this._dispatchWrappedEventType('loadend');
            }, 0);
        };
        this._onSend = onSend;
    }

    _setupWrappedResponseData() {
        try { this._response = this._xhr.response; } catch(e) {console.warn(e)}
        try { this._responseText = this._xhr.responseText; } catch(e) {console.warn(e)}
        try { this._responseXML = this._xhr.responseXML; } catch(e) {console.warn(e)}
    }

    _setupWrappedHeaders() {
        try { this._headersAll = this._xhr.getAllResponseHeaders(); } catch(e) {}
    }

    addEventListener(type, listener, optionsOrUseCapture, wantsUntrusted) {

        if (PASSTHROUGH_EVENTS.includes(type)) {
            return super.addEventListener(type, listener, optionsOrUseCapture, wantsUntrusted);
        }

        const listenerWrapper = createListenerWrapper(type, listener, this._dispatchedEventsList);
        this._listenersMap.set(listener, listenerWrapper);
        return super.addEventListener(type, listenerWrapper, optionsOrUseCapture, wantsUntrusted);
    }

    removeEventListener(type, listener, optionsOrUseCapture) {

        if (PASSTHROUGH_EVENTS.includes(type)) {
            return super.removeEventListener(type, listener, optionsOrUseCapture)
        }

        const listenerWrapper = this._listenersMap.get(listener);
        if (!listenerWrapper) {
            return;
        }
        this._listenersMap.delete(listener);
        return super.removeEventListener(type, listenerWrapper, optionsOrUseCapture);
    }

    open(method, url, async, user, password) {

        if (this._caching) {
            if (!this._cacheInstance) {
                throw new Error('no cache setup');
            }
            console.log('CACHE GET:', url);
            const cachedResource = this._cacheInstance.get(url, false);
            if (cachedResource) {

                console.log('CACHE HIT');

                this._handleCacheHitOnSend(cachedResource);
            }
        }

        return super.open(method, url, async, user, password);
    }

    send(data) {
        if (this._caching && this._cacheHit && this._onSend) {
            return this._onSend();
        }

        return super.send(data);
    }

    getAllResponseHeaders() {
        return this._headersAll;
    }

    get readyState() {
        if (typeof this._readyState === 'number') {
            return this._readyState;
        }
    }

    set onloadend(fn) {
        this._onloadend = fn;
    }

    get onloadend() {
        return this._onloadend;
    }

    set onload(fn) {
        this._onload = fn;
    }

    get onload() {
        return this._onload;
    }

    set onreadystatechange(fn) {
        this._onreadystatechange = fn;
    }

    get onreadystatechange() {
        return this._onreadystatechange;
    }

    set onprogress(fn) {
        this._onprogress = fn;
    }

    get onprogress() {
        return this._onprogress;
    }

    get response() {
        return this._response;
    }
    get responseText() {
        return this._responseText;
    }
    get responseXML() {
        return this._responseXML;
    }
}

export default XHR;<commit_msg>add debug mode to XHR class<commit_after>import XHRProxy from './xhr-proxy';
import Shaper from './shaper';
import setupThrottledXhr from './setup-throttled-xhr';
import setupCachedXhr from './setup-cached-xhr';
import cache from './cache';

const DEBUG = false;

const PASSTHROUGH_EVENTS = ['loadstart', 'timeout', 'abort', 'error'];

const createListenerWrapper = (type, listener, dispatchedEventsList) => {
    return (event) => {
        dispatchedEventsList.push({type, listener, event, propagated: false});
    };
}

class XHR extends XHRProxy {

    static get Shaper() {
        return Shaper;
    }

    static get cache() {
        return cache;
    }

    constructor() {
        super();

        this._cacheInstance = cache.instance;
        this._shaper = new Shaper();
        this._listenersMap = new Map();
        this._dispatchedEventsList = [];
        this._response = null;
        this._responseText = null;
        this._responseXML = null;
        this._headers = null;
        this._readyState = 0;
        this._caching = false;
        this._cacheHit = false;
        this._cacheWrite = true;
        this._onSend = null;

        this.addEventListener('loadend', () => {
            if (this._caching && this._cacheWrite) {
                DEBUG && console.log('CACHE WRITE:', this._xhr.responseURL);
                this._cacheInstance.put(
                    this._xhr.responseURL,
                    this._response,
                    this._responseText,
                    this._responseXML,
                    null,
                    this._xhr.getAllResponseHeaders()
                );
            }
        });

        setupThrottledXhr(this._xhr, this);
    }

    get caching() {
       return this._caching;
    }

    set caching(enabled) {
        this._caching = enabled;
    }

    set cacheInstance(instance) {
        this._cacheInstance = instance;
    }

    get cacheInstance() {
        return this._cacheInstance;
    }

    get isCacheHit() {
        return this._cacheHit;
    }

    set cacheWriteEnabled(enable) {
        this._cacheWrite = enable;
    }

    get enableCacheWrite() {
        return this._cacheWrite;
    }

    get shaper() {
        return this._shaper;
    }

    _dispatchWrappedEventType(type) {
        // it needs to run on the next tick since this is actually
        // triggered from our throttler listeners on the proxy's inner XHR
        setTimeout(() => {
            this._dispatchedEventsList
                .filter((dispatchedEvent) => (dispatchedEvent.type === type && !dispatchedEvent.propagated))
                .forEach((dispatchedEvent) => {
                    dispatchedEvent.propagated = true;
                    dispatchedEvent.listener(dispatchedEvent.event);
                });
        }, 0);
    }

    _handleCacheHitOnSend(cachedResource) {
        this._readyState = 1;
        this._cacheHit = true;

        const onSend = () => {
            setTimeout(() => {
                this._readyState = 2;
                this.onreadystatechange && this.onreadystatechange();
                this._dispatchWrappedEventType('readystatechange');
                this._readyState = 3;
                this.onreadystatechange && this.onreadystatechange();
                this._dispatchWrappedEventType('readystatechange');
                this.onloadstart && this.onloadstart();
                this._dispatchWrappedEventType('loadstart');
                this._response = cachedResource.data;
                this._responseText = cachedResource.dataText;
                this._responseXML = cachedResource.dataXML;
                this._headersAll = cachedResource.headers;
                this._readyState = 4;
                this.onreadystatechange && this.onreadystatechange();
                this._dispatchWrappedEventType('readystatechange');
                this.onreadystatechange && this.onreadystatechange();
                this._dispatchWrappedEventType('readystatechange');
                this.onload && this.onload();
                this._dispatchWrappedEventType('load');
                this.onloadend && this.onloadend();
                this._dispatchWrappedEventType('loadend');
            }, 0);
        };
        this._onSend = onSend;
    }

    _setupWrappedResponseData() {
        try {
            this._response = this._xhr.response;
        } catch(e) {
            DEBUG && console.warn(e)
        }
        try {
            this._responseText = this._xhr.responseText;
        } catch(e) {
            DEBUG && console.warn(e)
        }
        try {
            this._responseXML = this._xhr.responseXML;
        } catch(e) {
            DEBUG && console.warn(e)
        }
    }

    _setupWrappedHeaders() {
        try { this._headersAll = this._xhr.getAllResponseHeaders(); } catch(e) {}
    }

    addEventListener(type, listener, optionsOrUseCapture, wantsUntrusted) {

        if (PASSTHROUGH_EVENTS.includes(type)) {
            return super.addEventListener(type, listener, optionsOrUseCapture, wantsUntrusted);
        }

        const listenerWrapper = createListenerWrapper(type, listener, this._dispatchedEventsList);
        this._listenersMap.set(listener, listenerWrapper);
        return super.addEventListener(type, listenerWrapper, optionsOrUseCapture, wantsUntrusted);
    }

    removeEventListener(type, listener, optionsOrUseCapture) {

        if (PASSTHROUGH_EVENTS.includes(type)) {
            return super.removeEventListener(type, listener, optionsOrUseCapture)
        }

        const listenerWrapper = this._listenersMap.get(listener);
        if (!listenerWrapper) {
            return;
        }
        this._listenersMap.delete(listener);
        return super.removeEventListener(type, listenerWrapper, optionsOrUseCapture);
    }

    open(method, url, async, user, password) {

        if (this._caching) {
            if (!this._cacheInstance) {
                throw new Error('no cache setup');
            }
            DEBUG && console.log('CACHE GET:', url);
            const cachedResource = this._cacheInstance.get(url, false);
            if (cachedResource) {

                DEBUG && console.log('CACHE HIT');

                this._handleCacheHitOnSend(cachedResource);
            }
        }

        return super.open(method, url, async, user, password);
    }

    send(data) {
        if (this._caching && this._cacheHit && this._onSend) {
            return this._onSend();
        }

        return super.send(data);
    }

    getAllResponseHeaders() {
        return this._headersAll;
    }

    get readyState() {
        if (typeof this._readyState === 'number') {
            return this._readyState;
        }
    }

    set onloadend(fn) {
        this._onloadend = fn;
    }

    get onloadend() {
        return this._onloadend;
    }

    set onload(fn) {
        this._onload = fn;
    }

    get onload() {
        return this._onload;
    }

    set onreadystatechange(fn) {
        this._onreadystatechange = fn;
    }

    get onreadystatechange() {
        return this._onreadystatechange;
    }

    set onprogress(fn) {
        this._onprogress = fn;
    }

    get onprogress() {
        return this._onprogress;
    }

    get response() {
        return this._response;
    }
    get responseText() {
        return this._responseText;
    }
    get responseXML() {
        return this._responseXML;
    }
}

export default XHR;<|endoftext|>


<commit_before>var map, layer, styleMap;
OpenLayers.ProxyHost = "proxy.cgi?url=";

function init() {
    map = new OpenLayers.Map({
        div: "map",
        projection: new OpenLayers.Projection("EPSG:900913"),
        displayProjection: new OpenLayers.Projection("EPSG:4326"),
        units: "m",
        maxResolution: 156543.0339,
        maxExtent: new OpenLayers.Bounds(
            -20037508, -20037508, 20037508, 20037508
        )
    });

    var g = new OpenLayers.Layer.Google("Google Layer", {
        sphericalMercator: true
    });
    map.addLayers([g]);

    // prepare to style the data
    styleMap = new OpenLayers.StyleMap({
        strokeColor: "black",
        strokeWidth: 2,
        strokeOpacity: 0.5,
        fillOpacity: 0.2
    });

    // create a color table for state FIPS code
    var colors = ["red", "orange", "yellow", "green", "blue", "purple"];
    var code, fips = {};
    for(var i=1; i<=66; ++i) {
        code = "0" + i;
        code = code.substring(code.length - 2);
        fips[code] = {fillColor: colors[i % colors.length]};
    }
    // add unique value rules with your color lookup
    styleMap.addUniqueValueRules("default", "STATE_FIPS", fips);

    // create a vector layer using the canvas renderer (where available)
    var wfs = new OpenLayers.Layer.Vector("States", {
        strategies: [new OpenLayers.Strategy.BBOX()],
        protocol: new OpenLayers.Protocol.WFS({
            version: "1.1.0",
            srsName: "EPSG:900913",
            url:  "http://demo.opengeo.org/geoserver/wfs",
            featureType: "states",
            featureNS: "http://www.openplans.org/topp"
        }),
        styleMap: styleMap,
        renderers: ["Canvas", "SVG", "VML"]
    });
    map.addLayer(wfs);

    // if you want to use Geographic coords, transform to ESPG:900913
    var ddBounds = new OpenLayers.Bounds(
        -73.839111,40.287907,-68.214111,44.441624
    );
    map.zoomToExtent(
        ddBounds.transform(map.displayProjection, map.getProjectionObject())
    );
}
<commit_msg>Working WFS.<commit_after>var map, layer, styleMap;
OpenLayers.ProxyHost = "proxy.cgi?url=";

function init() {
    map = new OpenLayers.Map({
        div: "map",
        projection: new OpenLayers.Projection("EPSG:900913"),
        displayProjection: new OpenLayers.Projection("EPSG:4326"),
        units: "m",
        maxResolution: 156543.0339,
        maxExtent: new OpenLayers.Bounds(
            -20037508, -20037508, 20037508, 20037508
        )
    });

    var g = new OpenLayers.Layer.Google("Google Layer", {
        sphericalMercator: true
    });
    map.addLayers([g]);

    // prepare to style the data
    styleMap = new OpenLayers.StyleMap({
        strokeColor: "black",
        strokeWidth: 2,
        strokeOpacity: 0.5,
        fillOpacity: 0.2
    });

    // create a color table for state FIPS code
    var colors = ["red", "orange", "yellow", "green", "blue", "purple"];
    var code, fips = {};
    for(var i=1; i<=66; ++i) {
        code = "0" + i;
        code = code.substring(code.length - 2);
        fips[code] = {fillColor: colors[i % colors.length]};
    }
    // add unique value rules with your color lookup
    styleMap.addUniqueValueRules("default", "STATE_FIPS", fips);

    // create a vector layer using the canvas renderer (where available)
    var wfs = new OpenLayers.Layer.Vector("States", {
        strategies: [new OpenLayers.Strategy.BBOX()],
        protocol: new OpenLayers.Protocol.WFS({
            version: "1.1.0",
            srsName: "EPSG:900913",
            url:  "http://v2.suite.opengeo.org/geoserver/wfs",
            featureType: "states",
            featureNS: "http://usa.opengeo.org"
        }),
        styleMap: styleMap,
        renderers: ["Canvas", "SVG", "VML"]
    });
    map.addLayer(wfs);

    // if you want to use Geographic coords, transform to ESPG:900913
    var ddBounds = new OpenLayers.Bounds(
        -73.839111,40.287907,-68.214111,44.441624
    );
    map.zoomToExtent(
        ddBounds.transform(map.displayProjection, map.getProjectionObject())
    );
}
<|endoftext|>


<commit_before>var Example = Example || {};

Example.chains = function() {
    var Engine = Matter.Engine,
        Render = Matter.Render,
        Runner = Matter.Runner,
        Body = Matter.Body,
        Composite = Matter.Composite,
        Composites = Matter.Composites,
        Constraint = Matter.Constraint,
        MouseConstraint = Matter.MouseConstraint,
        Mouse = Matter.Mouse,
        World = Matter.World,
        Bodies = Matter.Bodies;

    // create engine
    var engine = Engine.create(),
        world = engine.world;

    // create renderer
    var render = Render.create({
        element: document.body,
        engine: engine,
        options: {
            width: Math.min(document.documentElement.clientWidth, 800),
            height: Math.min(document.documentElement.clientHeight, 600),
            showAngleIndicator: true,
            showCollisions: true,
            showVelocity: true
        }
    });

    Render.run(render);

    // create runner
    var runner = Runner.create();
    Runner.run(runner, engine);

    // add bodies
    var group = Body.nextGroup(true);

    var ropeA = Composites.stack(200, 100, 4, 2, 10, 10, function(x, y) {
        return Bodies.rectangle(x, y, 50, 20, { collisionFilter: { group: group } });
    });

    Composites.chain(ropeA, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 });
    Composite.add(ropeA, Constraint.create({
        bodyB: ropeA.bodies[0],
        pointB: { x: -25, y: 0 },
        pointA: { x: 200, y: 100 },
        stiffness: 0.5
    }));

    World.add(world, ropeA);

    group = Body.nextGroup(true);

    var ropeB = Composites.stack(500, 100, 5, 2, 10, 10, function(x, y) {
        return Bodies.circle(x, y, 20, { collisionFilter: { group: group } });
    });

    Composites.chain(ropeB, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 });
    Composite.add(ropeB, Constraint.create({
        bodyB: ropeB.bodies[0],
        pointB: { x: -20, y: 0 },
        pointA: { x: 500, y: 100 },
        stiffness: 0.5
    }));

    World.add(world, ropeB);

    // add mouse control
    var mouse = Mouse.create(render.canvas),
        mouseConstraint = MouseConstraint.create(engine, {
            mouse: mouse,
            constraint: {
                stiffness: 0.2,
                render: {
                    visible: false
                }
            }
        });

    World.add(world, mouseConstraint);

    // keep the mouse in sync with rendering
    render.mouse = mouse;

    // fit the render viewport to the scene
    Render.lookAt(render, {
        min: { x: 0, y: 0 },
        max: { x: 700, y: 600 }
    });

    // context for MatterTools.Demo
    return {
        engine: engine,
        runner: runner,
        render: render,
        canvas: render.canvas,
        stop: function() {
            Matter.Render.stop(render);
            Matter.Runner.stop(runner);
        }
    };
};<commit_msg>improved Example.chains using pin constraint<commit_after>var Example = Example || {};

Example.chains = function() {
    var Engine = Matter.Engine,
        Render = Matter.Render,
        Runner = Matter.Runner,
        Body = Matter.Body,
        Composite = Matter.Composite,
        Composites = Matter.Composites,
        Constraint = Matter.Constraint,
        MouseConstraint = Matter.MouseConstraint,
        Mouse = Matter.Mouse,
        World = Matter.World,
        Bodies = Matter.Bodies;

    // create engine
    var engine = Engine.create(),
        world = engine.world;

    // create renderer
    var render = Render.create({
        element: document.body,
        engine: engine,
        options: {
            width: Math.min(document.documentElement.clientWidth, 800),
            height: Math.min(document.documentElement.clientHeight, 600),
            showAngleIndicator: true,
            showCollisions: true,
            showVelocity: true
        }
    });

    Render.run(render);

    // create runner
    var runner = Runner.create();
    Runner.run(runner, engine);

    // add bodies
    var group = Body.nextGroup(true);

    var ropeA = Composites.stack(100, 50, 8, 1, 10, 10, function(x, y) {
        return Bodies.rectangle(x, y, 50, 20, { collisionFilter: { group: group } });
    });

    Composites.chain(ropeA, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 });
    Composite.add(ropeA, Constraint.create({
        bodyB: ropeA.bodies[0],
        pointB: { x: -25, y: 0 },
        pointA: { x: ropeA.bodies[0].position.x, y: ropeA.bodies[0].position.y },
        stiffness: 0.5
    }));

    group = Body.nextGroup(true);

    var ropeB = Composites.stack(350, 50, 10, 1, 10, 10, function(x, y) {
        return Bodies.circle(x, y, 20, { collisionFilter: { group: group } });
    });

    Composites.chain(ropeB, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 });
    Composite.add(ropeB, Constraint.create({
        bodyB: ropeB.bodies[0],
        pointB: { x: -20, y: 0 },
        pointA: { x: ropeB.bodies[0].position.x, y: ropeB.bodies[0].position.y },
        stiffness: 0.5
    }));

    group = Body.nextGroup(true);

    var ropeC = Composites.stack(600, 50, 13, 1, 10, 10, function(x, y) {
        return Bodies.rectangle(x - 20, y, 50, 20, { collisionFilter: { group: group }, chamfer: 5 });
    });

    Composites.chain(ropeC, 0.3, 0, -0.3, 0, { stiffness: 1, length: 0 });
    Composite.add(ropeC, Constraint.create({
        bodyB: ropeC.bodies[0],
        pointB: { x: -20, y: 0 },
        pointA: { x: ropeC.bodies[0].position.x, y: ropeC.bodies[0].position.y },
        stiffness: 0.5
    }));

    World.add(world, [
        ropeA,
        ropeB,
        ropeC,
        Bodies.rectangle(400, 600, 1200, 50.5, { isStatic: true })
    ]);

    // add mouse control
    var mouse = Mouse.create(render.canvas),
        mouseConstraint = MouseConstraint.create(engine, {
            mouse: mouse,
            constraint: {
                stiffness: 0.2,
                render: {
                    visible: false
                }
            }
        });

    World.add(world, mouseConstraint);

    // keep the mouse in sync with rendering
    render.mouse = mouse;

    // fit the render viewport to the scene
    Render.lookAt(render, {
        min: { x: 0, y: 0 },
        max: { x: 700, y: 600 }
    });

    // context for MatterTools.Demo
    return {
        engine: engine,
        runner: runner,
        render: render,
        canvas: render.canvas,
        stop: function() {
            Matter.Render.stop(render);
            Matter.Runner.stop(runner);
        }
    };
};<|endoftext|>


<commit_before>describe("Events", function(){
  var EventTest, ListenTest;
  var spy;

  beforeEach(function(){
    spy = jasmine.createSpy();
    EventTest = Spine.Class.create();
    EventTest.extend(Spine.Events);
  });

  it("can bind/trigger events", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.on('notify', spy2);
    EventTest.on("daddyo", spy);

    EventTest.trigger("somethingElse");
    expect(spy).not.toHaveBeenCalled();

    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can bind/trigger global events", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.on('notify', spy2);
    EventTest.on("daddyo", spy);

    Spine.trigger('somethingElse')
    expect(spy2).not.toHaveBeenCalled();

    Spine.trigger("notify");
    expect(spy2).toHaveBeenCalled();
    expect(spy).not.toHaveBeenCalled();
  });

  it("can listen for events on other objects", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "daddyo", spy);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
  });

  it("should trigger correct events", function(){
    EventTest.on("daddyo", spy);
    EventTest.trigger("motherio");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can bind/trigger multiple events", function(){
    EventTest.on("house car windows", spy);
    EventTest.trigger("car");
    expect(spy).toHaveBeenCalled();
    EventTest.trigger("house");
    EventTest.trigger("windows");
    expect(spy.calls.count()).toBe(3);
  });

  it("can listen for multiple events on other objects", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house car windows", spy);
    EventTest.trigger("car");
    expect(spy).toHaveBeenCalled();
    EventTest.trigger("house");
    EventTest.trigger("windows");
    expect(spy.calls.count()).toBe(3);
  });

  it("can pass data to triggered events", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.on('notify', spy2);
    EventTest.on("yoyo", spy);

    EventTest.trigger("yoyo", 5, 10);
    expect(spy).toHaveBeenCalledWith(5, 10);

    Spine.trigger("notify", 'a message');
    expect(spy2).toHaveBeenCalledWith('a message');
  });

  it("can unbind events", function(){
    EventTest.on("daddyo", spy);
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.on('notify', spy2);

    EventTest.off("daddyo");
    Spine.off('notify');
    EventTest.trigger("daddyo");
    Spine.trigger("notify");
    expect(spy).not.toHaveBeenCalled();
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can unbind all events if no arguments given", function() {
    EventTest.on("yoyo daddyo", spy);
    EventTest.off();
    EventTest.trigger("yoyo");
    expect(spy).not.toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("daddyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can stop listening to events", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "daddyo", spy);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
    spy.calls.reset();
    ListenTest.stopListening(EventTest, "daddyo");
    EventTest.trigger("daddyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can unbind one event", function(){
    EventTest.on("house car windows", spy);
    EventTest.off("car windows");
    EventTest.trigger("car");
    EventTest.trigger("windows");
    expect(spy).not.toHaveBeenCalled();
    EventTest.trigger("house");
    expect(spy).toHaveBeenCalled();
  });

  it("can stopListening to one event", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house car windows", spy)
    ListenTest.stopListening(EventTest, "car windows");
    EventTest.trigger("car");
    EventTest.trigger("windows");
    expect(spy).not.toHaveBeenCalled();
    EventTest.trigger("house");
    expect(spy).toHaveBeenCalled();
  });

  it("can stopListening to a specific callback", function(){
    var spy2 = jasmine.createSpy();
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "keep", spy);
    ListenTest.listenTo(EventTest, "keep", spy2);
    //EventTest.trigger("keep");
    //expect(spy).toHaveBeenCalled();
    //expect(spy2).toHaveBeenCalled();
    ListenTest.stopListening(EventTest, "keep", spy2);
    EventTest.trigger("keep");
    expect(spy).toHaveBeenCalled();
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can stopListening to a specific object", function(){
    ListenTest = Spine.Class.create();
    var EventTest2 = Spine.Class.create();
    var spy2 = jasmine.createSpy();
    ListenTest.extend(Spine.Events);
    EventTest2.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "keep", spy);
    ListenTest.listenTo(EventTest2, "keep", spy2);
    ListenTest.stopListening(EventTest);
    EventTest.trigger("keep");
    EventTest2.trigger("keep");
    expect(spy).not.toHaveBeenCalled();
    expect(spy2).toHaveBeenCalled();
  });

  it("can bind to an event only once", function(){
    EventTest.one("indahouse", spy);
    EventTest.trigger("indahouse");
    expect(spy).toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can bind to a global event only once", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.one('notify', spy2);
    Spine.trigger("notify");
    expect(spy2).toHaveBeenCalled();
    spy2.calls.reset();
    Spine.trigger("notify");
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can listen to to a event only once", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenToOnce(EventTest, 'indahouse', spy)
    EventTest.trigger("indahouse");
    expect(spy).toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can stopListening to a event that is being listened to once", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenToOnce(EventTest, "indahouse", spy)
    ListenTest.stopListening(EventTest, "indahouse");
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can stopListening to all events if no arguments given", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house", spy);
    ListenTest.listenToOnce(EventTest, "indahouse", spy);
    ListenTest.stopListening();
    EventTest.trigger("house");
    expect(spy).not.toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("should allow a callback to unbind itself", function(){
    var a = jasmine.createSpy("a");
    var b = jasmine.createSpy("b");
    var c = jasmine.createSpy("c");

    b.and.callFake(function() {
      EventTest.off("once", b);
    });

    EventTest.on("once", a);
    EventTest.on("once", b);
    EventTest.on("once", c);
    EventTest.trigger("once");

    expect(a).toHaveBeenCalled();
    expect(b).toHaveBeenCalled();
    expect(c).toHaveBeenCalled();

    EventTest.trigger("once");

    expect(a.calls.count()).toBe(2);
    expect(b.calls.count()).toBe(1);
    expect(c.calls.count()).toBe(2);
  });

  it("can cancel propogation", function(){
    EventTest.on("motherio", function(){ return false; });
    EventTest.on("motherio", spy);
    EventTest.trigger("motherio");
    expect(spy).not.toHaveBeenCalled();
  });

  it("should clear events on inherited objects", function(){
    EventTest.on("yoyo", spy);
    var Sub = EventTest.sub();
    Sub.trigger("yoyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("should not unbind all events if given and undefined object", function() {
    EventTest.on("daddyo", spy);
    EventTest.off(undefined);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
  });

  it("should not stopListening to all events if given and undefined object", function() {
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house", spy);
    ListenTest.stopListening(undefined);
    EventTest.trigger("house");
    expect(spy).toHaveBeenCalled();
  });

  it("should stop listening only on the specified events", function() {
    var spy2 = jasmine.createSpy();
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenToOnce(EventTest, "dastardly1", spy);
    ListenTest.listenTo(EventTest, "dastardly2", spy2);
    EventTest.trigger("dastardly2");
    ListenTest.stopListening(EventTest, "dastardly2");
    EventTest.trigger("dastardly1");
    expect(spy).toHaveBeenCalled();
    expect(spy2).toHaveBeenCalled();
  });
});
<commit_msg>spelling: propagation<commit_after>describe("Events", function(){
  var EventTest, ListenTest;
  var spy;

  beforeEach(function(){
    spy = jasmine.createSpy();
    EventTest = Spine.Class.create();
    EventTest.extend(Spine.Events);
  });

  it("can bind/trigger events", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.on('notify', spy2);
    EventTest.on("daddyo", spy);

    EventTest.trigger("somethingElse");
    expect(spy).not.toHaveBeenCalled();

    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can bind/trigger global events", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.on('notify', spy2);
    EventTest.on("daddyo", spy);

    Spine.trigger('somethingElse')
    expect(spy2).not.toHaveBeenCalled();

    Spine.trigger("notify");
    expect(spy2).toHaveBeenCalled();
    expect(spy).not.toHaveBeenCalled();
  });

  it("can listen for events on other objects", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "daddyo", spy);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
  });

  it("should trigger correct events", function(){
    EventTest.on("daddyo", spy);
    EventTest.trigger("motherio");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can bind/trigger multiple events", function(){
    EventTest.on("house car windows", spy);
    EventTest.trigger("car");
    expect(spy).toHaveBeenCalled();
    EventTest.trigger("house");
    EventTest.trigger("windows");
    expect(spy.calls.count()).toBe(3);
  });

  it("can listen for multiple events on other objects", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house car windows", spy);
    EventTest.trigger("car");
    expect(spy).toHaveBeenCalled();
    EventTest.trigger("house");
    EventTest.trigger("windows");
    expect(spy.calls.count()).toBe(3);
  });

  it("can pass data to triggered events", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.on('notify', spy2);
    EventTest.on("yoyo", spy);

    EventTest.trigger("yoyo", 5, 10);
    expect(spy).toHaveBeenCalledWith(5, 10);

    Spine.trigger("notify", 'a message');
    expect(spy2).toHaveBeenCalledWith('a message');
  });

  it("can unbind events", function(){
    EventTest.on("daddyo", spy);
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.on('notify', spy2);

    EventTest.off("daddyo");
    Spine.off('notify');
    EventTest.trigger("daddyo");
    Spine.trigger("notify");
    expect(spy).not.toHaveBeenCalled();
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can unbind all events if no arguments given", function() {
    EventTest.on("yoyo daddyo", spy);
    EventTest.off();
    EventTest.trigger("yoyo");
    expect(spy).not.toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("daddyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can stop listening to events", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "daddyo", spy);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
    spy.calls.reset();
    ListenTest.stopListening(EventTest, "daddyo");
    EventTest.trigger("daddyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can unbind one event", function(){
    EventTest.on("house car windows", spy);
    EventTest.off("car windows");
    EventTest.trigger("car");
    EventTest.trigger("windows");
    expect(spy).not.toHaveBeenCalled();
    EventTest.trigger("house");
    expect(spy).toHaveBeenCalled();
  });

  it("can stopListening to one event", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house car windows", spy)
    ListenTest.stopListening(EventTest, "car windows");
    EventTest.trigger("car");
    EventTest.trigger("windows");
    expect(spy).not.toHaveBeenCalled();
    EventTest.trigger("house");
    expect(spy).toHaveBeenCalled();
  });

  it("can stopListening to a specific callback", function(){
    var spy2 = jasmine.createSpy();
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "keep", spy);
    ListenTest.listenTo(EventTest, "keep", spy2);
    //EventTest.trigger("keep");
    //expect(spy).toHaveBeenCalled();
    //expect(spy2).toHaveBeenCalled();
    ListenTest.stopListening(EventTest, "keep", spy2);
    EventTest.trigger("keep");
    expect(spy).toHaveBeenCalled();
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can stopListening to a specific object", function(){
    ListenTest = Spine.Class.create();
    var EventTest2 = Spine.Class.create();
    var spy2 = jasmine.createSpy();
    ListenTest.extend(Spine.Events);
    EventTest2.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "keep", spy);
    ListenTest.listenTo(EventTest2, "keep", spy2);
    ListenTest.stopListening(EventTest);
    EventTest.trigger("keep");
    EventTest2.trigger("keep");
    expect(spy).not.toHaveBeenCalled();
    expect(spy2).toHaveBeenCalled();
  });

  it("can bind to an event only once", function(){
    EventTest.one("indahouse", spy);
    EventTest.trigger("indahouse");
    expect(spy).toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can bind to a global event only once", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.one('notify', spy2);
    Spine.trigger("notify");
    expect(spy2).toHaveBeenCalled();
    spy2.calls.reset();
    Spine.trigger("notify");
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can listen to to a event only once", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenToOnce(EventTest, 'indahouse', spy)
    EventTest.trigger("indahouse");
    expect(spy).toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can stopListening to a event that is being listened to once", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenToOnce(EventTest, "indahouse", spy)
    ListenTest.stopListening(EventTest, "indahouse");
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can stopListening to all events if no arguments given", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house", spy);
    ListenTest.listenToOnce(EventTest, "indahouse", spy);
    ListenTest.stopListening();
    EventTest.trigger("house");
    expect(spy).not.toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("should allow a callback to unbind itself", function(){
    var a = jasmine.createSpy("a");
    var b = jasmine.createSpy("b");
    var c = jasmine.createSpy("c");

    b.and.callFake(function() {
      EventTest.off("once", b);
    });

    EventTest.on("once", a);
    EventTest.on("once", b);
    EventTest.on("once", c);
    EventTest.trigger("once");

    expect(a).toHaveBeenCalled();
    expect(b).toHaveBeenCalled();
    expect(c).toHaveBeenCalled();

    EventTest.trigger("once");

    expect(a.calls.count()).toBe(2);
    expect(b.calls.count()).toBe(1);
    expect(c.calls.count()).toBe(2);
  });

  it("can cancel propagation", function(){
    EventTest.on("motherio", function(){ return false; });
    EventTest.on("motherio", spy);
    EventTest.trigger("motherio");
    expect(spy).not.toHaveBeenCalled();
  });

  it("should clear events on inherited objects", function(){
    EventTest.on("yoyo", spy);
    var Sub = EventTest.sub();
    Sub.trigger("yoyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("should not unbind all events if given and undefined object", function() {
    EventTest.on("daddyo", spy);
    EventTest.off(undefined);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
  });

  it("should not stopListening to all events if given and undefined object", function() {
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house", spy);
    ListenTest.stopListening(undefined);
    EventTest.trigger("house");
    expect(spy).toHaveBeenCalled();
  });

  it("should stop listening only on the specified events", function() {
    var spy2 = jasmine.createSpy();
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenToOnce(EventTest, "dastardly1", spy);
    ListenTest.listenTo(EventTest, "dastardly2", spy2);
    EventTest.trigger("dastardly2");
    ListenTest.stopListening(EventTest, "dastardly2");
    EventTest.trigger("dastardly1");
    expect(spy).toHaveBeenCalled();
    expect(spy2).toHaveBeenCalled();
  });
});
<|endoftext|>


<commit_before>var demand = require('must');

var keystone = require('../').init(),
	Types = keystone.Field.Types;

/** Test List and Fields */

var Test = keystone.List('Test');

Test.add({
	date: Types.Date,
	datetime: Types.Datetime
});

Test.register();

/** Test Item */

var item = new Test.model();

/** FieldType: Date */

describe("Fields", function() {
	describe("Date", function() {

		it('should parse without error via underscore date', function() {
			item._.date.parse('20131204', 'YYYYMMDD');
		});

		it('should be the date we expect', function() {
			demand(item._.date.format()).to.equal('4th Dec 2013');
			demand(item._.date.format('YYYYMMDD')).to.equal('20131204');
		});

		it('should be a moment object', function() {
			demand(item._.date.moment()._isAMomentObject);
		});

	});
});
<commit_msg>Add updateItem test for field Boolean.<commit_after>var demand = require('must');

var keystone = require('../').init(),
	Types = keystone.Field.Types;

/** Test List and Fields */

var Test = keystone.List('Test');
var item;

before(function() {

Test.add({
	date: Types.Date,
	datetime: Types.Datetime,
	bool: Types.Boolean
});

Test.register();
/** Test Item */

item = new Test.model();
});

/** FieldType: Date */

describe("Fields", function() {
	describe("Date", function() {

		it('should parse without error via underscore date', function() {
			item._.date.parse('20131204', 'YYYYMMDD');
		});

		it('should be the date we expect', function() {
			demand(item._.date.format()).to.equal('4th Dec 2013');
			demand(item._.date.format('YYYYMMDD')).to.equal('20131204');
		});

		it('should be a moment object', function() {
			demand(item._.date.moment()._isAMomentObject);
		});

	});
	describe("Boolean", function() {

		it('should update it\'s model if data passed is boolean true', function() {
			Test.fields.bool.updateItem(item, {
				'bool': true
			});
			demand(item.bool).to.be.true();

		});

       		it('should update it\'s  model if data passed is string \'true\'', function() {
			Test.fields.bool.updateItem(item, {
				'bool': 'true'
			});
			demand(item.bool).to.be.true();

		});

	});
});
<|endoftext|>


<commit_before>/* global describe, it, expect */

import { h } from "../src"

describe("h", () => {
  it("creates an empty vnode", () => {
    expect(
      h("div")
    ).toEqual({
      tag: "div",
      data: {},
      children: []
    })
  })

  it("creates a vnode with a single child", () => {
    expect(
      h("div", {}, ["foo"])
    ).toEqual({
      tag: "div",
      data: {},
      children: ["foo"]
    })

    expect(
      h("div", {}, "foo")
    ).toEqual({
      tag: "div",
      data: {},
      children: ["foo"]
    })
  })

  it("concatenates multiple children string/number", () => {
    expect(
      h("div", {}, "foo", "bar", "baz")
    ).toEqual({
      tag: "div",
      data: {},
      children: ["foobarbaz"]
    })

    expect(
      h("div", {}, ["foo", "bar", "baz"])
    ).toEqual({
      tag: "div",
      data: {},
      children: ["foobarbaz"]
    })

    expect(
      h("div", {}, 1, "foo", 2, "baz", 3)
    ).toEqual({
      tag: "div",
      data: {},
      children: ["1foo2baz3"]
    })

    expect(
      h("div", {}, "foo", h("div", {}, "bar"), "baz", "quux")
    ).toEqual({
      tag: "div",
      data: {},
      children: ["foo", {
        tag: "div",
        data: {},
        children: ["bar"]
      }, "bazquux"]
    })
  })

  it("creates a vnode with props data", () => {
    const props = {
      id: "foo",
      class: "bar",
      style: {
        color: "red"
      }
    }

    expect(h("div", props, "baz")
    ).toEqual({
      tag: "div",
      data: props,
      children: ["baz"]
    })

  })

  it("doesn't create children from null or boolean values", () => {
    const expected = {
      tag: "div",
      data: {},
      children: []
    }

    expect(
      h("div", {}, true)
    ).toEqual(expected)

    expect(
      h("div", {}, false)
    ).toEqual(expected)

    expect(
      h("div", {}, null)
    ).toEqual(expected)
  })

  it("creates a vnode from a component / tag function", () => {
    const Component = (data, children) => h("div", data, children)

    expect(
      h(Component, { id: "foo" }, "bar")
    ).toEqual({
      tag: "div",
      data: { id: "foo" },
      children: ["bar"]
    })

    expect(
      h(Component, { id: "foo" }, [h(Component, { id: "bar" })])
    ).toEqual({
      tag: "div",
      data: { id: "foo" },
      children: [{
        tag: "div",
        data: { id: "bar" },
        children: []
      }]
    })

  })

  it("creates a vnode with a svg namespace if tag is svg", () => {

    expect(
      h("svg", {}, "foo")
    ).toEqual({
      tag: "svg",
      data: {
        ns: "http://www.w3.org/2000/svg"
      },
      children: ["foo"]
    })

    expect(
      h("svg", {}, h("circle", {}))
    ).toEqual({
      tag: "svg",
      data: {
        ns: "http://www.w3.org/2000/svg"
      },
      children: [{
        tag: "circle",
        data: {
          ns: "http://www.w3.org/2000/svg"
        },
        children: []
      }]
    })
  })
})

<commit_msg>Remove svg tests from h.<commit_after>/* global describe, it, expect */

import { h } from "../src"

describe("h", () => {
  it("creates an empty vnode", () => {
    expect(
      h("div")
    ).toEqual({
      tag: "div",
      data: {},
      children: []
    })
  })

  it("creates a vnode with a single child", () => {
    expect(
      h("div", {}, ["foo"])
    ).toEqual({
      tag: "div",
      data: {},
      children: ["foo"]
    })

    expect(
      h("div", {}, "foo")
    ).toEqual({
      tag: "div",
      data: {},
      children: ["foo"]
    })
  })

  it("concatenates multiple children string/number", () => {
    expect(
      h("div", {}, "foo", "bar", "baz")
    ).toEqual({
      tag: "div",
      data: {},
      children: ["foobarbaz"]
    })

    expect(
      h("div", {}, ["foo", "bar", "baz"])
    ).toEqual({
      tag: "div",
      data: {},
      children: ["foobarbaz"]
    })

    expect(
      h("div", {}, 1, "foo", 2, "baz", 3)
    ).toEqual({
      tag: "div",
      data: {},
      children: ["1foo2baz3"]
    })

    expect(
      h("div", {}, "foo", h("div", {}, "bar"), "baz", "quux")
    ).toEqual({
      tag: "div",
      data: {},
      children: ["foo", {
        tag: "div",
        data: {},
        children: ["bar"]
      }, "bazquux"]
    })
  })

  it("creates a vnode with props data", () => {
    const props = {
      id: "foo",
      class: "bar",
      style: {
        color: "red"
      }
    }

    expect(h("div", props, "baz")
    ).toEqual({
      tag: "div",
      data: props,
      children: ["baz"]
    })

  })

  it("doesn't create children from null or boolean values", () => {
    const expected = {
      tag: "div",
      data: {},
      children: []
    }

    expect(
      h("div", {}, true)
    ).toEqual(expected)

    expect(
      h("div", {}, false)
    ).toEqual(expected)

    expect(
      h("div", {}, null)
    ).toEqual(expected)
  })

  it("creates a vnode from a component / tag function", () => {
    const Component = (data, children) => h("div", data, children)

    expect(
      h(Component, { id: "foo" }, "bar")
    ).toEqual({
      tag: "div",
      data: { id: "foo" },
      children: ["bar"]
    })

    expect(
      h(Component, { id: "foo" }, [h(Component, { id: "bar" })])
    ).toEqual({
      tag: "div",
      data: { id: "foo" },
      children: [{
        tag: "div",
        data: { id: "bar" },
        children: []
      }]
    })
  })
})

<|endoftext|>


<commit_before>import request from '../'
import assert from 'assert'

const EQ = assert.strictEqual

let buildP = (url, id) => request(url).then(content => assert(content.indexOf(id) > 0))

describe('basic request with Promise', function () {
  request.Promise = require('yaku')
  it('request with http', () => buildP('http://www.baidu.com/', 'bdstatic'))
  it('request with https', () => buildP('https://www.baidu.com/', 'baidu'))
  it('request without protocol', () => buildP('www.baidu.com/', 'bdstatic'))
})

describe('basic request with callback', function () {
  request.Promise = null
  let build = (url, id, done) =>
    request(url, function (err, content) {
      if (err) done(err)
      assert(content.indexOf(id) > 0)
      done()
    })

  it('request with http', done => build('http://www.baidu.com/', 'bdstatic', done))
  it('request with https', done => build('https://www.baidu.com/', 'baidu', done))
  it('request without protocol', done => build('www.baidu.com', 'bdstatic', done))
})

describe('request options', function () {
  request.Promise = require('yaku')

  it('use object', () =>
    request({host: 'www.baidu.com', protocol: 'http'})
      .then(content => assert(content.indexOf('bdstatic') > 0))
  )
  it('use object with url', () =>
    request({url: 'www.baidu.com'})
      .then(content => assert(content.indexOf('bdstatic') > 0))
  )
})

describe('advanced requests', function () {
  request.Promise = require('yaku')

  it('decode gb2312, handle gzip', () => buildP('http://www.qq.com/', '腾讯'))
  it('handle redirect', () => buildP('www.baidu.cn', '百度'))

  let buildError = (url, errCode) =>
    request(url)
      .then(() => new Error('')).catch(e => EQ(e.code, errCode))

  it('handle Error', () => buildError('zjcbsddsfj.com', 'ENOTFOUND'))
  it('handle HTTP 4XX', () => buildError('www.cnbeta.com/213', 'UNWANTED_STATUS_CODE'))
  it('handle unvalid url', () => buildError('musi/asa', 'UNVALID URL'))
  it('handle unvalid protocol', () => buildError({host: 'music.baidu.com/asa', protocol: 'ftp:'}, 'UNVALID PROTOCOL'))
  it('handle timeout', () => buildError({url: 'www.163.com', timeout: 100}, 'TIMEOUT'))
})
<commit_msg>change test case for passing CI test<commit_after>import request from '../'
import assert from 'assert'

const EQ = assert.strictEqual

let buildP = (url, id) => request(url).then(content => assert(content.indexOf(id) > 0))

describe('basic request with Promise', function () {
  request.Promise = require('yaku')
  it('request with http', () => buildP('http://www.baidu.com/', 'bdstatic'))
  it('request with https', () => buildP('https://www.baidu.com/', 'baidu'))
  it('request without protocol', () => buildP('www.baidu.com/', 'bdstatic'))
})

describe('basic request with callback', function () {
  request.Promise = null
  let build = (url, id, done) =>
    request(url, function (err, content) {
      if (err) done(err)
      assert(content.indexOf(id) > 0)
      done()
    })

  it('request with http', done => build('http://www.baidu.com/', 'bdstatic', done))
  it('request with https', done => build('https://www.baidu.com/', 'baidu', done))
  it('request without protocol', done => build('www.baidu.com', 'bdstatic', done))
})

describe('request options', function () {
  request.Promise = require('yaku')

  it('use object', () =>
    request({host: 'www.baidu.com', protocol: 'http'})
      .then(content => assert(content.indexOf('bdstatic') > 0))
  )
  it('use object with url', () =>
    request({url: 'www.baidu.com'})
      .then(content => assert(content.indexOf('bdstatic') > 0))
  )
})

describe('advanced requests', function () {
  request.Promise = require('yaku')

  it('decode gb2312, handle gzip', () => buildP('http://www.qq.com/', '腾讯'))
  it('handle redirect', () => buildP('qq.com', '腾讯'))

  let buildError = (url, errCode) =>
    request(url)
      .then(() => new Error('')).catch(e => EQ(e.code, errCode))

  it('handle Error', () => buildError('zjcbsddsfj.com', 'ENOTFOUND'))
  it('handle HTTP 4XX', () => buildError('www.cnbeta.com/213', 'UNWANTED_STATUS_CODE'))
  it('handle unvalid url', () => buildError('musi/asa', 'UNVALID URL'))
  it('handle unvalid protocol', () => buildError({host: 'music.baidu.com/asa', protocol: 'ftp:'}, 'UNVALID PROTOCOL'))
  it('handle timeout', () => buildError({url: 'www.163.com', timeout: 100}, 'TIMEOUT'))
})
<|endoftext|>


<commit_before>'use strict'

var test = require('tape')
var isURL = require('../../is/url')

var testCases = [
// ['url',expectedResult]
  ['boom', false, 'simple string'],
  ['perdu.com', true, 'domain.ext'],
  ['http://domain.ext/path?query=string', true, 'with query string'],
  ['https://boom.com/path?query=string%20with%20spaces', true, 'with (uri encoded) spaces (%20) in query string'],
  ['https://boom.com/path?query=string%20with%20spaces#andThis', true, 'with hash']
]

test('isURL', function (t) {
  t.plan(testCases.length)
  testCases.map(function (item) {
    t.equals(isURL(item[0]), item[1])
  })
})
<commit_msg>fix test messages<commit_after>'use strict'

var test = require('tape')
var isURL = require('../../is/url')

var testCases = [
// ['url',expectedResult]
  ['string', false],
  ['domain.ext', true],
  ['http://domain.ext/path?query=string', true],
  ['https://domain.ext/path?query=string%20with%20spaces', true],
  ['https://domain.ext/path#withHash', true],
  ['http://domain.ext/path?query=string#withHash', true]
]

test('isURL', function (t) {
  t.plan(testCases.length)
  testCases.map(function (item) {
    t.equals(isURL(item[0]), item[1], item[0])
  })
})
<|endoftext|>


<commit_before>'use strict';
/*jshint asi: true */

var test = require('tape')
  , parse = require('../lib/parse')
  , layout = require('../lib/layout')
  , render = require('../lib/render')

function inspect(obj, depth) {
  return require('util').inspect(obj, false, depth || 5, true);
}

var src = [
    '
outside
'
  , '
'
  , '
'
  , '
- One Level List
'
  , '
'
  , '
'
  , '
- Two Levels List
'
  , '
'
  , '
'
  , '
'
  , '
'
].join('\n')

test('render parsed: \n' + src + '\nwith list indent "12"', function (t) {
  parse(src, function (err, res) {
    var expected = [
        ''
      , 'outside'
      , '12- One Level List'
      , ''
      , '1212- Two Levels List'
      , ''
      , ''
        ].join('\n')
      , layedout = layout(res, { listIndent: '12' })
      , result = render(layedout)

    t.equals(result, expected, 'returns result that renders to ' + expected)
    t.end()
  });
})

test('render parsed: \n' + src + '\nwith list indent "1234"', function (t) {
  parse(src, function (err, res) {
    var expected = [
        ''
      , 'outside'
      , '1234- One Level List'
      , ''
      , '12341234- Two Levels List'
      , ''
      , ''
        ].join('\n')
      , layedout = layout(res, { listIndent: '1234' })
      , result = render(layedout)

    t.equals(result, expected, 'returns result that renders to ' + expected)
    t.end()
  });
})
<commit_msg>fixing layout tests<commit_after>'use strict';
/*jshint asi: true */

var test = require('tape')
  , parse = require('../lib/parse')
  , layout = require('../lib/layout')
  , render = require('../lib/render')

function inspect(obj, depth) {
  return require('util').inspect(obj, false, depth || 5, true);
}

var src = [
    '
outside
'
  , '
'
  , '
'
  , '
- One Level List
'
  , '
'
  , '
'
  , '
- Two Levels List
'
  , '
'
  , '
'
  , '
'
  , '
'
].join('\n')

test('render parsed: \n' + src + '\nwith list indent "12"', function (t) {
  parse(src, function (err, res) {
    var expected =
          '\n\noutside\n12- One Level List\n'
        + '\n1212- Two Levels List\n\n'
      , layedout = layout(res, { listIndent: '12' })
      , result = render(layedout)

    t.equals(result, expected, 'returns result that renders to ' + expected)
    t.end()
  });
})

test('render parsed: \n' + src + '\nwith list indent "1234"', function (t) {
  parse(src, function (err, res) {
    var expected =
          '\n\noutside\n1234- One Level List\n'
        + '\n12341234- Two Levels List\n\n'
      , layedout = layout(res, { listIndent: '1234' })
      , result = render(layedout)

    t.equals(result, expected, 'returns result that renders to ' + expected)
    t.end()
  });
})
<|endoftext|>