<commit_before>describe("SilverTrack", function() {
  var track = null;
  var plugin = null;

  beforeEach(function() {
    jasmine.Clock.useMock();
    loadFixtures("basic.html");

    $.fx.off = true;

    $.silverTrackPlugin("Generic", {});
    plugin = new SilverTrack.Plugins.Generic();
  });

  describe("Plugin initialization", function() {

    it("should use default values", function() {
      track = helpers.basic();
      expect(track.opts.perPage).toBe(4);
      expect(track.opts.itemClass).toBe("item");
      expect(track.opts.cover).toBe(false);
    });

    it("should allow the user to override the default values", function() {
      track = helpers.basic({perPage: 1, itemClass: "new-class", cover: true});
      expect(track.opts.perPage).toBe(1);
      expect(track.opts.itemClass).toBe("new-class");
      expect(track.opts.cover).toBe(true);
    });

    it("should keep the instance in a data attribute", function() {
      track = helpers.basic();
      expect($("#basic").data("silverTrackInstance")).toBe(track);
    });

    it("should retrieve the instance if initialized again", function() {
      track = helpers.basic();
      expect(helpers.basic()).toBe(track);
    });

    it("should set the 'currentPage' to 1", function() {
      expect(helpers.basic().currentPage).toBe(1);
    });

    it("should hold the reference of the container", function() {
      var container = $("#basic");
      expect(container.silverTrack().container).toBe(container);
    });

    it("should have zero plugins", function() {
      expect(helpers.basic().plugins.length).toBe(0);
    });

  });

  describe("#start", function() {
    beforeEach(function() {
      track = helpers.basic();
      track.install(plugin);
    });

    it("should call 'beforeStart'", function() {
      spyOn(plugin, 'beforeStart');
      track.start();
      expect(plugin.beforeStart).toHaveBeenCalledWith(track);
    });

    it("should calculate 'itemWidth'", function() {
      track.start();
      expect(track.itemWidth).toBe(240);
    });

    it("should set container 'left' to '0px'", function() {
      track.start();
      expect(track.container.css("left")).toBe("0px");
    });

    it("should position the elements", function() {
      track.start();
      var items = $("#basic").find(".item");
      expect($(items[0]).css("left")).toBe("0px");
      expect($(items[1]).css("left")).toBe("240px");
      expect($(items[2]).css("left")).toBe("480px");
    });

    it("should calculate 'totalPages' based on DOM elements", function() {
      track.start();
      expect(track.totalPages).toBe(3);
    });

    describe("with cover", function() {
      beforeEach(function() {
        loadFixtures("cover.html");

        track = helpers.cover();
        track.install(plugin);
      });

      it("should calculate 'coverWidth'", function() {
        track.start();
        expect(track.coverWidth).toBe(956);
      });

      it("should count the cover as one page", function() {
        track.start();
        expect(track.totalPages).toBe(3);
      });
    });
  });

  describe("#goToPage", function() {
    beforeEach(function() {
      track = helpers.basic();
      track.start();
    });

    it("should do nothing if pagination is disabled", function() {
      spyOn(track, "_animate");
      track.paginationEnabled = false;
      expect(track.currentPage).toBe(1);

      track.goToPage(2);
      expect(track._animate).not.toHaveBeenCalled();
      expect(track.currentPage).toBe(1);
    });

    it("should do nothing if newPage is less than currentPage and currentPage is the first page", function() {
      spyOn(track, "_animate");
      expect(track.currentPage).toBe(1);

      track.goToPage(-1);
      expect(track._animate).not.toHaveBeenCalled();
      expect(track.currentPage).toBe(1);
    });

    it("should do nothing if newPage is greater than totalPages", function() {
      spyOn(track, "_animate");
      track.totalPages = 2;
      expect(track.currentPage).toBe(1);
      expect(track.totalPages).toBe(2);

      track.goToPage(3);
      expect(track._animate).not.toHaveBeenCalled();
      expect(track.currentPage).toBe(1);
    });

    it("should do nothing if newPage is equal to currentPage", function() {
      spyOn(track, "_animate");
      track.currentPage = 2;
      expect(track.currentPage).toBe(2);

      track.goToPage(2);
      expect(track._animate).not.toHaveBeenCalled();
      expect(track.currentPage).toBe(2);
    });

    describe("without cover", function() {
      beforeEach(function() {
        track.install(plugin);
        expect(track.currentPage).toBe(1);
        expect(track._calculateContainerLeft()).toBe(0);
        expect(track.itemWidth).toBe(240);
        expect(track.opts.perPage).toBe(4);
      });

      it("should animate to first item of the informed page", function() {
        track.goToPage(2);
        expect(track.currentPage).toBe(2);
        expect(track._calculateContainerLeft()).toBe(240 * 4);
      });

      it("should animate just enough items", function() {
        track.goToPage(3);
        expect(track.currentPage).toBe(3);
        expect(track._calculateContainerLeft()).toBe(240 * 5); // 3 + 1
      });

      describe("going forward", function() {
        it("should call 'beforePagination' with the proper event", function() {
          spyOn(plugin, 'beforePagination');
          track.goToPage(2);
          expect(plugin.beforePagination).toHaveBeenCalledWith(track, {
            name: "next",
            page: 2,
            cover: false
          });
        });
      });

      describe("going backwards", function() {
        it("should call 'beforePagination' with the proper event", function() {
          track.goToPage(2);
          spyOn(plugin, 'beforePagination');
          track.goToPage(1);
          expect(plugin.beforePagination).toHaveBeenCalledWith(track, {
            name: "prev",
            page: 1,
            cover: false
          });
        });
      });
    });

    describe("with cover", function() {
      beforeEach(function() {
        loadFixtures("cover.html");
        track = helpers.cover();
        track.install(plugin);
        track.start();

        expect(track.opts.cover).toBe(true);
        expect(track.currentPage).toBe(1);
        expect(track._calculateContainerLeft()).toBe(0);
        expect(track.itemWidth).toBe(240);
        expect(track.opts.perPage).toBe(4);
      });

      it("should animate to first item of the informed page", function() {
        track.goToPage(2);
        expect(track.currentPage).toBe(2);
        expect(track._calculateContainerLeft()).toBe(956); // shift the cover
      });

      it("should animate just enough items", function() {
        track.goToPage(3);
        expect(track.currentPage).toBe(3);
        expect(track._calculateContainerLeft()).toBe(1196); // 3 + 1
      });

      it("should consider the cover as a page", function() {
        expect(track._getCover().outerWidth(true)).toBe(956);
        track.goToPage(2);
        expect(track.currentPage).toBe(2);
        expect(track._calculateContainerLeft()).toBe(956);

        track.goToPage(1);
        expect(track.currentPage).toBe(1);
        expect(track._calculateContainerLeft()).toBe(0);
      });

      describe("going forward", function() {
        it("should call 'beforePagination' with the proper event", function() {
          spyOn(plugin, 'beforePagination');
          track.goToPage(2);
          expect(plugin.beforePagination).toHaveBeenCalledWith(track, {
            name: "next",
            page: 2,
            cover: false
          });
        });
      });

      describe("going backwards", function() {
        it("should call 'beforePagination' with the proper event", function() {
          track.goToPage(2);
          spyOn(plugin, 'beforePagination');
          track.goToPage(1);
          expect(plugin.beforePagination).toHaveBeenCalledWith(track, {
            name: "prev",
            page: 1,
            cover: true
          });
        });
      });
    });
  });

  describe("#next", function() {
    describe("without cover", function() {
    });

    describe("with cover", function() {
    });
  });

  describe("#hasNext", function() {
    describe("without cover", function() {
    });

    describe("with cover", function() {
    });
  });

  describe("#prev", function() {
    describe("without cover", function() {
    });

    describe("with cover", function() {
    });
  });

  describe("#hasPrev", function() {
    describe("without cover", function() {
    });

    describe("with cover", function() {
    });
  });

  describe("#restart", function() {
    describe("without cover", function() {
    });

    describe("with cover", function() {
    });
  });

  describe("#install", function() {
    describe("without cover", function() {
    });

    describe("with cover", function() {
    });
  });

  describe("Plugins integration", function() {
  });

});
<commit_msg>more tests<commit_after>describe("SilverTrack", function() {
  var track = null;
  var plugin = null;

  beforeEach(function() {
    jasmine.Clock.useMock();
    loadFixtures("basic.html");

    $.fx.off = true;

    $.silverTrackPlugin("Generic", {});
    plugin = new SilverTrack.Plugins.Generic();
  });

  describe("Plugin initialization", function() {

    it("should use default values", function() {
      track = helpers.basic();
      expect(track.opts.perPage).toBe(4);
      expect(track.opts.itemClass).toBe("item");
      expect(track.opts.cover).toBe(false);
    });

    it("should allow the user to override the default values", function() {
      track = helpers.basic({perPage: 1, itemClass: "new-class", cover: true});
      expect(track.opts.perPage).toBe(1);
      expect(track.opts.itemClass).toBe("new-class");
      expect(track.opts.cover).toBe(true);
    });

    it("should keep the instance in a data attribute", function() {
      track = helpers.basic();
      expect($("#basic").data("silverTrackInstance")).toBe(track);
    });

    it("should retrieve the instance if initialized again", function() {
      track = helpers.basic();
      expect(helpers.basic()).toBe(track);
    });

    it("should set the 'currentPage' to 1", function() {
      expect(helpers.basic().currentPage).toBe(1);
    });

    it("should hold the reference of the container", function() {
      var container = $("#basic");
      expect(container.silverTrack().container).toBe(container);
    });

    it("should have zero plugins", function() {
      expect(helpers.basic().plugins.length).toBe(0);
    });

  });

  describe("#start", function() {
    beforeEach(function() {
      track = helpers.basic();
      track.install(plugin);
    });

    it("should call 'beforeStart'", function() {
      spyOn(plugin, 'beforeStart');
      track.start();
      expect(plugin.beforeStart).toHaveBeenCalledWith(track);
    });

    it("should calculate 'itemWidth'", function() {
      track.start();
      expect(track.itemWidth).toBe(240);
    });

    it("should set container 'left' to '0px'", function() {
      track.start();
      expect(track.container.css("left")).toBe("0px");
    });

    it("should position the elements", function() {
      track.start();
      var items = $("#basic").find(".item");
      expect($(items[0]).css("left")).toBe("0px");
      expect($(items[1]).css("left")).toBe("240px");
      expect($(items[2]).css("left")).toBe("480px");
    });

    it("should calculate 'totalPages' based on DOM elements", function() {
      track.start();
      expect(track.totalPages).toBe(3);
    });

    describe("with cover", function() {
      beforeEach(function() {
        loadFixtures("cover.html");

        track = helpers.cover();
        track.install(plugin);
      });

      it("should calculate 'coverWidth'", function() {
        track.start();
        expect(track.coverWidth).toBe(956);
      });

      it("should count the cover as one page", function() {
        track.start();
        expect(track.totalPages).toBe(3);
      });
    });
  });

  describe("#goToPage", function() {
    beforeEach(function() {
      track = helpers.basic();
      track.start();
    });

    it("should do nothing if pagination is disabled", function() {
      spyOn(track, "_animate");
      track.paginationEnabled = false;
      expect(track.currentPage).toBe(1);

      track.goToPage(2);
      expect(track._animate).not.toHaveBeenCalled();
      expect(track.currentPage).toBe(1);
    });

    it("should do nothing if newPage is less than currentPage and currentPage is the first page", function() {
      spyOn(track, "_animate");
      expect(track.currentPage).toBe(1);

      track.goToPage(-1);
      expect(track._animate).not.toHaveBeenCalled();
      expect(track.currentPage).toBe(1);
    });

    it("should do nothing if newPage is greater than totalPages", function() {
      spyOn(track, "_animate");
      track.totalPages = 2;
      expect(track.currentPage).toBe(1);
      expect(track.totalPages).toBe(2);

      track.goToPage(3);
      expect(track._animate).not.toHaveBeenCalled();
      expect(track.currentPage).toBe(1);
    });

    it("should do nothing if newPage is equal to currentPage", function() {
      spyOn(track, "_animate");
      track.currentPage = 2;
      expect(track.currentPage).toBe(2);

      track.goToPage(2);
      expect(track._animate).not.toHaveBeenCalled();
      expect(track.currentPage).toBe(2);
    });

    describe("without cover", function() {
      beforeEach(function() {
        track.install(plugin);
        expect(track.currentPage).toBe(1);
        expect(track._calculateContainerLeft()).toBe(0);
        expect(track.itemWidth).toBe(240);
        expect(track.opts.perPage).toBe(4);
      });

      it("should animate to first item of the informed page", function() {
        track.goToPage(2);
        expect(track.currentPage).toBe(2);
        expect(track._calculateContainerLeft()).toBe(240 * 4);
      });

      it("should animate just enough items", function() {
        track.goToPage(3);
        expect(track.currentPage).toBe(3);
        expect(track._calculateContainerLeft()).toBe(240 * 5); // 3 + 1
      });

      describe("going forward", function() {
        it("should call 'beforePagination' with the proper event", function() {
          spyOn(plugin, 'beforePagination');
          track.goToPage(2);
          expect(plugin.beforePagination).toHaveBeenCalledWith(track, {
            name: "next",
            page: 2,
            cover: false
          });
        });
      });

      describe("going backwards", function() {
        it("should call 'beforePagination' with the proper event", function() {
          track.goToPage(2);
          spyOn(plugin, 'beforePagination');
          track.goToPage(1);
          expect(plugin.beforePagination).toHaveBeenCalledWith(track, {
            name: "prev",
            page: 1,
            cover: false
          });
        });
      });
    });

    describe("with cover", function() {
      beforeEach(function() {
        loadFixtures("cover.html");
        track = helpers.cover();
        track.install(plugin);
        track.start();

        expect(track.opts.cover).toBe(true);
        expect(track.currentPage).toBe(1);
        expect(track._calculateContainerLeft()).toBe(0);
        expect(track.itemWidth).toBe(240);
        expect(track.opts.perPage).toBe(4);
      });

      it("should animate to first item of the informed page", function() {
        track.goToPage(2);
        expect(track.currentPage).toBe(2);
        expect(track._calculateContainerLeft()).toBe(956); // shift the cover
      });

      it("should animate just enough items", function() {
        track.goToPage(3);
        expect(track.currentPage).toBe(3);
        expect(track._calculateContainerLeft()).toBe(1196); // 3 + 1
      });

      it("should consider the cover as a page", function() {
        expect(track._getCover().outerWidth(true)).toBe(956);
        track.goToPage(2);
        expect(track.currentPage).toBe(2);
        expect(track._calculateContainerLeft()).toBe(956);

        track.goToPage(1);
        expect(track.currentPage).toBe(1);
        expect(track._calculateContainerLeft()).toBe(0);
      });

      describe("going forward", function() {
        it("should call 'beforePagination' with the proper event", function() {
          spyOn(plugin, 'beforePagination');
          track.goToPage(2);
          expect(plugin.beforePagination).toHaveBeenCalledWith(track, {
            name: "next",
            page: 2,
            cover: false
          });
        });
      });

      describe("going backwards", function() {
        it("should call 'beforePagination' with the proper event", function() {
          track.goToPage(2);
          spyOn(plugin, 'beforePagination');
          track.goToPage(1);
          expect(plugin.beforePagination).toHaveBeenCalledWith(track, {
            name: "prev",
            page: 1,
            cover: true
          });
        });
      });
    });
  });

  describe("#next", function() {
    it("should call 'goToPage' incrementing currentPage", function() {
      expect(track.currentPage).toBe(1);
      spyOn(track, "goToPage");
      track.next();
      expect(track.goToPage).toHaveBeenCalledWith(2);
    });
  });

  describe("#hasNext", function() {
    it("should be true when currentPage is lower than totalPages", function() {
      track.totalPages = 2;
      expect(track.currentPage).toBe(1);
      expect(track.hasNext()).toBe(true);
    });

    it("should be false when currentPage is equal to totalPages", function() {
      track.currentPage = 2;
      expect(track.currentPage).toBe(2);
      expect(track.hasNext()).toBe(false);
    });
  });

  describe("#prev", function() {
    it("should call 'goToPage' decrementing currentPage", function() {
      track.currentPage = 2;
      expect(track.currentPage).toBe(2);
      spyOn(track, "goToPage");
      track.prev();
      expect(track.goToPage).toHaveBeenCalledWith(1);
    });
  });

  describe("#hasPrev", function() {
    it("should be true when currentPage is greater than 1", function() {
      track.currentPage = 2;
      expect(track.currentPage).toBe(2);
      expect(track.hasPrev()).toBe(true);
    });

    it("should be false when currentPage is 1", function() {
      track.currentPage = 1;
      expect(track.currentPage).toBe(1);
      expect(track.hasPrev()).toBe(false);
    });
  });

  describe("#restart", function() {
    describe("without cover", function() {
    });

    describe("with cover", function() {
    });
  });

  describe("#install", function() {
    describe("without cover", function() {
    });

    describe("with cover", function() {
    });
  });

  describe("Plugins integration", function() {
  });

});
<|endoftext|>


<commit_before>/**
 *  Exports items, layers or whole projects as a svg
 *  Stetson Alpha - Paper.js
 *
 *  var NS="http://www.w3.org/2000/svg";
 *  var svg=document.createElementNS(NS,"svg");
 */

var ExportSVG = function()
{
	var svgObj = null; // xml dom object (svg typed)
	//var blarg = this;

	//initialize the svgObj and what ever else.
	/*function initialize()
	{
		var NS = "http://www.w3.org/2000/svg";
		svgObj = document.createElementNS(NS,"svg");

		console.log(svgObj);

	};*/

	/**
	 *
	 * Takes the whole project and parses
	 * all the layers to be put into svg groups and
	 * groups into svg groups making all the projects
	 * items into one svg.
	 *
	 * takes in a Paper.js Project
	 * returns svg object (xml dom)
	 */
    this.exportProject = function(project)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the layer and then parses all groups
	 * and items into one svg
	 *
	 * takes in a Paper.js Layer
	 * returns svg object (xml dom)
	 */
    this.exportLayer = function(layer)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the group and puts it's items
	 * in a svg file.
	 *
	 * takes in a Paper.js Group
	 * returns svg object (xml dom)
	 */
    this.exportGroup = function(group)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the item and puts it in
	 * a svg file.
	 *
	 * takes in a Paper.js Item
	 * returns svg object (xml dom)
	 */
    this.exportItem = function(item)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the path and puts it in
	 * a svg file.
	 *
	 * takes in a Paper.js Path
	 * returns svg object (xml dom)
	 */
    this.exportPath = function(path)
    {
    	//this.initialize();
    	//console.log(blarg.svgObj);
	var NS = "http://www.w3.org/2000/svg";
	svgObj = document.createElementNS(NS,"svg");
	svgRect = document.createElementNS(NS,"rect");
	svgRect.height.baseVal.value = 50;
	svgRect.width.baseVal.value = 60;
	svgRect.x.baseVal.value = 50;
	svgObj.appendChild(svgRect);

	svgPoint = document.createElementNS(NS,"point");
	svgPoint.setAttribute("x",50);
	svgPoint.setAttribute("y",100);
	svgObj.appendChild(svgPoint);

	svgPath = document.createElementNS(NS, "path");

    	console.log(svgObj);
	var pathClone = path.clone();
	var segArray = pathClone.getSegments();

	var pointArray = new Array();
	var handleInArray = new Array();
	var handleOutArray = new Array();
	for(i = 0; i < segArray.length; i++)
	{
		pointArray[i] = segArray[i].getPoint();
		handleInArray[i] = segArray[i].getHandleIn();
		handleOutArray[i] = segArray[i].getHandleOut();

		console.log("point " + i + ": " + pointArray[i]);
		console.log("HI " + i + ": " + handleInArray[i]);
		console.log("HO " + i + ": " + handleOutArray[i]);
	}
	var pointString = "";
	for(i = 0; i < pointArray.length; i++)
	{
		var x = pointArray[i].getX();
		x = x - (x % 1);
		var y = pointArray[i].getY();
		y = y - (y % 1);
		if(i === 0)
		{
			pointString+= "M " + x + " " + y + " ";
		}
		else
		{
			pointString+= "L " + x + " " + y + " ";
		}
	}
	if(pathClone.getClosed())
	{
		pointString += "z";
	}

	svgPath.setAttribute("d",pointString);

	if(pathClone.strokeColor != undefined)
	{
		var strokeRed = pathClone.strokeColor.red;
		var strokeGreen = pathClone.strokeColor.green;
		var strokeBlue = pathClone.strokeColor.blue;
		var strokeRGB = RGBtoHex(strokeRed, strokeGreen, strokeBlue);
		svgPath.setAttribute("stroke", strokeRGB);
	}

	if(pathClone.fillColor != undefined)
	{
		var fillRed = pathClone.fillColor.red;
		var fillGreen = pathClone.fillColor.green;
		var fillBlue = pathClone.fillColor.blue;
		var fillRGB = RGBtoHex(fillRed, fillGreen, fillBlue);
		svgPath.setAttribute("fill", fillRGB);
	}

	//svgPath.setAttribute("d", pointString);
	//svgPath.setAttribute("stroke", strokeRGB);
	//svgPath.setAttribute("fill", fillRGB);
	svgPath.setAttribute("stroke-width",pathClone.strokeWidth);
	svgObj.appendChild(svgPath);i

	console.log(svgObj);
	return svgObj;
    };

    function RGBConverter(deciColor)
    {
	var decColor = Math.round(deciColor * 255);
	var hexColor = decColor.toString(16);
	hexColor = hexColor.length > 1? hexColor : "0" + hexColor;
	return hexColor;
    };

    function RGBtoHex(red, green, blue)
    {
    	var redVal = RGBConverter(red);
	var greenVal = RGBConverter(green);
	var blueVal = RGBConverter(blue);
	return "#" + redVal + greenVal + blueVal;
    }

    //initialize(); // calls the init function after class is loaded
};
<commit_msg>Made changes to SVGCircles to be able to have an easier time reading the data from the circle. Also, made an SVGRect html to test rectangles. No other changes than that. Still working on telling the types of points from Paths that we make. The curveTo's and arcTo's are giving us the most trouble. LineTo's are points with 0 values for the handles. Jacob will clean up the code for the walkthrough tomorrow. There we can figure out how to solve this problem and hopefully finish up the exportPath method.<commit_after>/**
 *  Exports items, layers or whole projects as a svg
 *  Stetson Alpha - Paper.js
 *
 *  var NS="http://www.w3.org/2000/svg";
 *  var svg=document.createElementNS(NS,"svg");
 */

var ExportSVG = function()
{
	var svgObj = null; // xml dom object (svg typed)
	//var blarg = this;

	//initialize the svgObj and what ever else.
	/*function initialize()
	{
		var NS = "http://www.w3.org/2000/svg";
		svgObj = document.createElementNS(NS,"svg");

		console.log(svgObj);

	};*/

	/**
	 *
	 * Takes the whole project and parses
	 * all the layers to be put into svg groups and
	 * groups into svg groups making all the projects
	 * items into one svg.
	 *
	 * takes in a Paper.js Project
	 * returns svg object (xml dom)
	 */
    this.exportProject = function(project)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the layer and then parses all groups
	 * and items into one svg
	 *
	 * takes in a Paper.js Layer
	 * returns svg object (xml dom)
	 */
    this.exportLayer = function(layer)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the group and puts it's items
	 * in a svg file.
	 *
	 * takes in a Paper.js Group
	 * returns svg object (xml dom)
	 */
    this.exportGroup = function(group)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the item and puts it in
	 * a svg file.
	 *
	 * takes in a Paper.js Item
	 * returns svg object (xml dom)
	 */
    this.exportItem = function(item)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the path and puts it in
	 * a svg file.
	 *
	 * takes in a Paper.js Path
	 * returns svg object (xml dom)
	 */
    this.exportPath = function(path)
    {
    	//this.initialize();
    	//console.log(blarg.svgObj);
	var NS = "http://www.w3.org/2000/svg";
	svgObj = document.createElementNS(NS,"svg");
	svgRect = document.createElementNS(NS,"rect");
	svgRect.height.baseVal.value = 50;
	svgRect.width.baseVal.value = 60;
	svgRect.x.baseVal.value = 50;
	svgObj.appendChild(svgRect);

	svgPoint = document.createElementNS(NS,"point");
	svgPoint.setAttribute("x",50);
	svgPoint.setAttribute("y",100);
	svgObj.appendChild(svgPoint);

	svgPath = document.createElementNS(NS, "path");

    	console.log(svgObj);
	var pathClone = path.clone();
	var segArray = pathClone.getSegments();

	var pointArray = new Array();
	var handleInArray = new Array();
	var handleOutArray = new Array();
	for(i = 0; i < segArray.length; i++)
	{
		console.log(segArray[i].toString());
		pointArray[i] = segArray[i].getPoint();
		handleInArray[i] = segArray[i].getHandleIn();
		handleOutArray[i] = segArray[i].getHandleOut();

		console.log("point " + i + ": " + pointArray[i]);
		console.log("HI " + i + ": " + handleInArray[i]);
		console.log("HO " + i + ": " + handleOutArray[i]);
	}
	var pointString = "";
	for(i = 0; i < pointArray.length; i++)
	{
		var x = pointArray[i].getX();
		//x = x - (x % 1);
		var y = pointArray[i].getY();
		//y = y - (x % 1);
		if(i === 0)
		{
			pointString+= "M " + x + " " + y + " ";
		}
		else
		{
			pointString+= "L " + x + " " + y + " ";
		}
	}
	if(pathClone.getClosed())
	{
		pointString += "z";
	}

	svgPath.setAttribute("d",pointString);

	if(pathClone.strokeColor != undefined)
	{
		var strokeRed = pathClone.strokeColor.red;
		var strokeGreen = pathClone.strokeColor.green;
		var strokeBlue = pathClone.strokeColor.blue;
		var strokeRGB = RGBtoHex(strokeRed, strokeGreen, strokeBlue);
		svgPath.setAttribute("stroke", strokeRGB);
	}

	if(pathClone.fillColor != undefined)
	{
		var fillRed = pathClone.fillColor.red;
		var fillGreen = pathClone.fillColor.green;
		var fillBlue = pathClone.fillColor.blue;
		var fillRGB = RGBtoHex(fillRed, fillGreen, fillBlue);
		svgPath.setAttribute("fill", fillRGB);
	}

	//svgPath.setAttribute("d", pointString);
	//svgPath.setAttribute("stroke", strokeRGB);
	//svgPath.setAttribute("fill", fillRGB);
	svgPath.setAttribute("stroke-width",pathClone.strokeWidth);
	svgObj.appendChild(svgPath);

	console.log(svgObj);
	return svgObj;
    };

    function RGBConverter(deciColor)
    {
	var decColor = Math.round(deciColor * 255);
	var hexColor = decColor.toString(16);
	hexColor = hexColor.length > 1? hexColor : "0" + hexColor;
	return hexColor;
    };

    function RGBtoHex(red, green, blue)
    {
    	var redVal = RGBConverter(red);
	var greenVal = RGBConverter(green);
	var blueVal = RGBConverter(blue);
	return "#" + redVal + greenVal + blueVal;
    }

    //initialize(); // calls the init function after class is loaded
};
<|endoftext|>


<commit_before>/**
 *  Exports items, layers or whole projects as a svg
 *  Stetson Alpha - Paper.js
 *
 *  var NS="http://www.w3.org/2000/svg";
 *  var svg=document.createElementNS(NS,"svg");
 */

var ExportSVG = function()
{
	var svgObj = null; // xml dom object (svg typed)
	//var blarg = this;

	//initialize the svgObj and what ever else.
	/*function initialize()
	{
		var NS = "http://www.w3.org/2000/svg";
		svgObj = document.createElementNS(NS,"svg");

		console.log(svgObj);

	};*/

	/**
	 *
	 * Takes the whole project and parses
	 * all the layers to be put into svg groups and
	 * groups into svg groups making all the projects
	 * items into one svg.
	 *
	 * takes in a Paper.js Project
	 * returns svg object (xml dom)
	 */
    this.exportProject = function(project)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the layer and then parses all groups
	 * and items into one svg
	 *
	 * takes in a Paper.js Layer
	 * returns svg object (xml dom)
	 */
    this.exportLayer = function(layer)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the group and puts it's items
	 * in a svg file.
	 *
	 * takes in a Paper.js Group
	 * returns svg object (xml dom)
	 */
    this.exportGroup = function(group)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the item and puts it in
	 * a svg file.
	 *
	 * takes in a Paper.js Item
	 * returns svg object (xml dom)
	 */
    this.exportItem = function(item)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the path and puts it in
	 * a svg file.
	 *
	 * takes in a Paper.js Path
	 * returns svg object (xml dom)
	 */
    this.exportPath = function(path)
    {
    	//this.initialize();
    	//console.log(blarg.svgObj);
	var pathClone = path.clone();
	var NS = "http://www.w3.org/2000/svg";
	svgObj = document.createElementNS(NS,"svg");
	svgPath = document.createElementNS(NS, "path");

	var segArray = pathClone.getSegments();

	var pointArray = new Array();
	var handleInArray = new Array();
	var handleOutArray = new Array();
	for(i = 0; i < segArray.length; i++)
	{
		console.log(segArray[i].toString());
		pointArray[i] = segArray[i].getPoint();
		handleInArray[i] = segArray[i].getHandleIn();
		handleOutArray[i] = segArray[i].getHandleOut();
	}
	var pointString = "";
	for(i = 0; i < pointArray.length; i++)
	{
		var x = pointArray[i].getX();
		//x = x - (x % 1);
		var y = pointArray[i].getY();
		//y = y - (x % 1);
		if(i === 0)
		{
			pointString+= "M " + x + " " + y + " ";
		}
		else
		{
			pointString+= "L " + x + " " + y + " ";
		}
	}
	if(pathClone.getClosed())
	{
		pointString += "z";
	}

	svgPath.setAttribute("d",pointString);

	if(pathClone.strokeColor != undefined)
	{
		var strokeRed = pathClone.strokeColor.red;
		var strokeGreen = pathClone.strokeColor.green;
		var strokeBlue = pathClone.strokeColor.blue;
		var strokeRGB = RGBtoHex(strokeRed, strokeGreen, strokeBlue);
		svgPath.setAttribute("stroke", strokeRGB);
	}

	if(pathClone.fillColor != undefined)
	{
		var fillRed = pathClone.fillColor.red;
		var fillGreen = pathClone.fillColor.green;
		var fillBlue = pathClone.fillColor.blue;
		var fillRGB = RGBtoHex(fillRed, fillGreen, fillBlue);
		svgPath.setAttribute("fill", fillRGB);
	}
	svgPath.setAttribute("stroke-width",pathClone.strokeWidth);
	svgObj.appendChild(svgPath);
	return svgObj;
    };

    function RGBConverter(deciColor)
    {
	var decColor = Math.round(deciColor * 255);
	var hexColor = decColor.toString(16);
	hexColor = hexColor.length > 1? hexColor : "0" + hexColor;
	return hexColor;
    };

    function RGBtoHex(red, green, blue)
    {
    	var redVal = RGBConverter(red);
	var greenVal = RGBConverter(green);
	var blueVal = RGBConverter(blue);
	return "#" + redVal + greenVal + blueVal;
    }

    //initialize(); // calls the init function after class is loaded
};
<commit_msg>Added comments Code should be easier to understand.<commit_after>/**
 *  Exports items, layers or whole projects as a svg
 *  Stetson Alpha - Paper.js
 *
 *  var NS="http://www.w3.org/2000/svg";
 *  var svg=document.createElementNS(NS,"svg");
 */

var ExportSVG = function()
{
	var svgObj = null; // xml dom object (svg typed)
	//var blarg = this;

	//initialize the svgObj and what ever else.
	/*function initialize()
	{
		var NS = "http://www.w3.org/2000/svg";
		svgObj = document.createElementNS(NS,"svg");

		console.log(svgObj);

	};*/

	/**
	 *
	 * Takes the whole project and parses
	 * all the layers to be put into svg groups and
	 * groups into svg groups making all the projects
	 * items into one svg.
	 *
	 * takes in a Paper.js Project
	 * returns svg object (xml dom)
	 */
    this.exportProject = function(project)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the layer and then parses all groups
	 * and items into one svg
	 *
	 * takes in a Paper.js Layer
	 * returns svg object (xml dom)
	 */
    this.exportLayer = function(layer)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the group and puts it's items
	 * in a svg file.
	 *
	 * takes in a Paper.js Group
	 * returns svg object (xml dom)
	 */
    this.exportGroup = function(group)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the item and puts it in
	 * a svg file.
	 *
	 * takes in a Paper.js Item
	 * returns svg object (xml dom)
	 */
    this.exportItem = function(item)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the path and puts it in
	 * a svg file.
	 *
	 * takes in a Paper.js Path
	 * returns svg object (xml dom)
	 */
    this.exportPath = function(path)
    {
    	//this.initialize();
    	//console.log(blarg.svgObj);
	var pathClone = path.clone();
	var NS = "http://www.w3.org/2000/svg";
	svgObj = document.createElementNS(NS,"svg");
	svgPath = document.createElementNS(NS, "path");

	//Getting all of the segments(a point, a HandleIn and a HandleOut) in the path
	var segArray = pathClone.getSegments();

	var pointArray = new Array();
	var handleInArray = new Array();
	var handleOutArray = new Array();
	for(i = 0; i < segArray.length; i++)
	{

		console.log(segArray[i].toString());
		pointArray[i] = segArray[i].getPoint();
		handleInArray[i] = segArray[i].getHandleIn();
		handleOutArray[i] = segArray[i].getHandleOut();
	}
	//pointstring is formatted in the way the SVG XML will be reading
	//Namely, a point and the way to traverse to that point
	var pointString = "";
	for(i = 0; i < pointArray.length; i++)
	{
		var x = pointArray[i].getX();
		//x = x - (x % 1); //Possible for simplifying
		var y = pointArray[i].getY();
		//y = y - (x % 1);
		if(i === 0)
		{
			//M is moveto, moving to a point without drawing
			pointString+= "M " + x + " " + y + " ";
		}
		else
		{
			//L is lineto, moving to a point with drawing
			pointString+= "L " + x + " " + y + " ";
		}
	}
	if(pathClone.getClosed())
	{
		//Z implies a closed path, connecting the first and last points
		pointString += "z";
	}

	svgPath.setAttribute("d",pointString);

	//If the stroke doesn't have a color, there's no attribute for it
	if(pathClone.strokeColor != undefined)
	{
		//Using rgb, each value between 0 and 1
		var strokeRed = pathClone.strokeColor.red;
		var strokeGreen = pathClone.strokeColor.green;
		var strokeBlue = pathClone.strokeColor.blue;
		var strokeRGB = RGBtoHex(strokeRed, strokeGreen, strokeBlue);
		svgPath.setAttribute("stroke", strokeRGB);
	}

	//If the fill doesn't have a color, there's no attribute for it
	if(pathClone.fillColor != undefined)
	{
		var fillRed = pathClone.fillColor.red;
		var fillGreen = pathClone.fillColor.green;
		var fillBlue = pathClone.fillColor.blue;
		var fillRGB = RGBtoHex(fillRed, fillGreen, fillBlue);
		svgPath.setAttribute("fill", fillRGB);
	}
	svgPath.setAttribute("stroke-width",pathClone.strokeWidth);
	svgObj.appendChild(svgPath); //appends path to svgObj
	return svgObj;
    };

    function RGBConverter(deciColor)
    {
    	//since value is scaled from 0 to 1, must round the
	//multiplication by 255
	var decColor = Math.round(deciColor * 255);
	var hexColor = decColor.toString(16); //to hex
	//R, G, and B need to take up at 2 characters
	hexColor = hexColor.length > 1? hexColor : "0" + hexColor;
	return hexColor;
    };

    function RGBtoHex(red, green, blue)
    {
    	var redVal = RGBConverter(red);
	var greenVal = RGBConverter(green);
	var blueVal = RGBConverter(blue);
	//Returns hex for colors
	return "#" + redVal + greenVal + blueVal;
    }

    //initialize(); // calls the init function after class is loaded
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'

import Factory from 'template-ui/lib/plugins2/digger/factory'
import TabForm from 'template-ui/lib/plugins2/crud/components/TabForm'
import yaml from 'template-ui/lib/utils/yaml'

import apitools from './api/tools'
import config from './config'
import forms from './forms'
import apis from './api'

const icons = config.icons

const folder = {
  type: 'folder',
  form: {
    type: 'normal',
    fields: forms.folder
  },
  title: 'Folder',
  icon: icons.folder,
  children: ['folder', 'item'],
}

const item = {
  type: 'item',
  form: {
    type: 'normal',
    fields: forms.item
  },
  title: 'Item',
  icon: icons.item,
  leaf: true,
}

const bookingFormSchema = {
  type: 'bookingForm',
  form: {
    type: 'normal',
    fields: forms.bookingForm
  },
  title: 'Booking Form',
  icon: icons.bookingForm,
  leaf: true,
}

const bookingFormForm = TabForm({
  title: 'Booking Form',
  icon: icons.bookingForm,
  tabs: [{
    label: 'Details',
    fields: forms.bookingFormCore
  }, {
    label: 'Config',
    fields: forms.bookingFormConfig
  }],
  icons: config.icons,
})

const resourceTypes = {
  folder,
  item,
}

const bookingFormTypes = {
  bookingForm: bookingFormSchema
}

const resource = Factory({
  title: 'Resource',
  name: 'resource',
  api: apis.resource,
  namespace: 'resource',
  types: resourceTypes,
  icons,
  descendentType: 'folder',
  rootItem: {
    name: 'Resources',
  }
})

const bookingForm = Factory({
  title: 'Booking Forms',
  icon: icons.bookingForm,
  name: 'bookingForm',
  api: apis.resource,
  namespace: 'bookingForm',
  types: bookingFormTypes,
  childTypes: ['bookingForm'],
  FormComponent: bookingFormForm,
  icons,
  noTree: true,
  rootItem: {
    name: 'Booking Forms',
  },
  mapData: (data) => {
    const parsed = yaml.load(data.meta.yaml)
    if(parsed.error) {
      alert(parsed.error)
      return data
    }
    data.meta.config = parsed.doc
    return data
  }
})

const diggers = {
  resource,
  bookingForm
}

export default diggers<commit_msg>booking configs in log array<commit_after>import React, { Component, PropTypes } from 'react'

import Factory from 'template-ui/lib/plugins2/digger/factory'
import TabForm from 'template-ui/lib/plugins2/crud/components/TabForm'
import yaml from 'template-ui/lib/utils/yaml'

import apitools from './api/tools'
import config from './config'
import forms from './forms'
import apis from './api'

const icons = config.icons

const folder = {
  type: 'folder',
  form: {
    type: 'normal',
    fields: forms.folder
  },
  title: 'Folder',
  icon: icons.folder,
  children: ['folder', 'item'],
}

const item = {
  type: 'item',
  form: {
    type: 'normal',
    fields: forms.item
  },
  title: 'Item',
  icon: icons.item,
  leaf: true,
}

const bookingFormSchema = {
  type: 'bookingForm',
  form: {
    type: 'normal',
    fields: forms.bookingForm
  },
  title: 'Booking Form',
  icon: icons.bookingForm,
  leaf: true,
}

const bookingFormForm = TabForm({
  title: 'Booking Form',
  icon: icons.bookingForm,
  tabs: [{
    label: 'Details',
    fields: forms.bookingFormCore
  }, {
    label: 'Config',
    fields: forms.bookingFormConfig
  }],
  icons: config.icons,
})

const resourceTypes = {
  folder,
  item,
}

const bookingFormTypes = {
  bookingForm: bookingFormSchema
}

const resource = Factory({
  title: 'Resource',
  name: 'resource',
  api: apis.resource,
  namespace: 'resource',
  types: resourceTypes,
  icons,
  descendentType: 'folder',
  rootItem: {
    name: 'Resources',
  }
})

const bookingForm = Factory({
  title: 'Booking Forms',
  icon: icons.bookingForm,
  name: 'bookingForm',
  api: apis.resource,
  namespace: 'bookingForm',
  types: bookingFormTypes,
  childTypes: ['bookingForm'],
  FormComponent: bookingFormForm,
  icons,
  noTree: true,
  rootItem: {
    name: 'Booking Forms',
  },
  // when saved we keep a log of previous configs
  mapData: (data) => {
    const parsed = yaml.load(data.meta.yaml)
    if(parsed.error) {
      alert(parsed.error)
      return data
    }
    if(!data.meta.configLog) {
      data.meta.configLog = []
    }
    if(data.meta.config) {
      data.meta.configLog.push(data.meta.config)
    }
    data.meta.config = parsed.doc
    return data
  }
})

const diggers = {
  resource,
  bookingForm
}

export default diggers<|endoftext|>


<commit_before>/*
* Paper.js
*
* This file is part of Paper.js, a JavaScript Vector Graphics Library,
* based on Scriptographer.org and designed to be largely API compatible.
* http://paperjs.org/
* http://scriptographer.org/
*
* Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*
*
*
* This class and all methods therein designed by Stetson-Team-Alpha
*/

/**
 * @name ImportSVG
 * @class The ImportSVG object represents an object created using the SVG
 * Canvas that will be converted into a Paper.js object.
 * The SVG object is imported into Paper.js by converting it into items
 * within groups.
 *
 */

var ImportSVG = this.ImportSVG = Base.extend(/** @Lends ImportSVG# */{

	/**
	 * Creates a Paper.js object using data parsed from the selected SVG
	 * Document Object Model (DOM). The SVG object is imported, than a layer
	 * is created (with groups for the items if needed).
	 *
	 * Supports nested groups
	 *
	 * @param {SVG DOM} svg An SVG DOM object with parameters
	 * @return {Layer} A Paper.js layer
	 */

	importSVG: function(svg)
	{
	var layer = new Layer();
	groups = this.importGroup(svg);
	layer.addChild(groups);

	return layer;
	},

	/**
	 * Creates a Paper.js group by parsing a specific GNode of the imported
	 * SVG DOM
	 *
	 * @name ImportSVG#importGroup
	 * @function
	 * @param {XML DOM} svg  A node passed in by the imported SVG
	 * @return {Group} group A Paper.js group
	 *
	 *
	 */
	importGroup: function(svg)
	{
		var group = new Group();
		var child;
		for (var i in svg.childNodes) {
			child = svg.childNodes[i];
			if (child.nodeType != 1) {
				continue;
			}
			item = this.importPath(child);
			group.addChild(item);
		}

		return group;
	},

	/**
	 * Creates a Paper.js Path by parsing
	 * a specific SVG node (rectangle, path, circle, polygon, etc.)
	 * and creating the right Path object based on the SVG type.
	 *
	 * @name ImportSVG#importPath
	 * @function
	 * @param {XML DOM} svg An SVG object
	 * @return {Item} item A Paper.js item
	 */
	importPath: function(svg)
	{
		switch (svg.nodeName.toLowerCase()) {
			case 'line':
				item = this._importLine(svg);
				break;
			case 'rect':
				item = this._importRectangle(svg);
				break;
			case 'ellipse':
				item = this._importOval(svg);
				break;
			case 'g':
				item = this.importGroup(svg);
				break;
			case 'text':
				item = this._importText(svg);
				break;
			default:
			break;
		}

		return item;
	},

	/**
	 * Creates a Path.Circle item in Paper.js using an imported Circle from
	 * SVG
	 *
	 * @name ImportSVG#importCircle
	 * @function
	 * @param {XML DOM} svgCircle An SVG circle node
	 * @return {Path.Circle} circle A Path.Circle item for Paper.js
	 */
	_importCircle: function(svgCircle)
	{
		var cx		= svgCircle.cx.baseVal.value || 0;
		var cy		= svgCircle.cy.baseVal.value || 0;
		var r		= svgCircle.r.baseVal.value || 0;
		var center	= new Point(cx, cy);
		var circle	= new Path.Circle(center, r);

		return circle;
	},

	/**
	 * Creates a Path.Oval item in Paper.js using an imported Oval from SVG
	 *
	 * @name ImportSVG#importOval
	 * @function
	 * @param {XML DOM} svgOval An SVG ellipse node
	 * @return {Path.Oval} oval A Path.Oval item for Paper.js
	 */
	_importOval: function(svgOval)
	{
		var cx			= svgOval.cx.baseVal.value || 0;
		var cy			= svgOval.cy.baseVal.value || 0;
		var rx			= svgOval.rx.baseVal.value || 0;
		var ry			= svgOval.ry.baseVal.value || 0;

		var center		= new Point(cx, cy);
		var offset		= new Point(rx, ry);
		var topLeft		= center.subtract(offset);
		var bottomRight	= center.add(offset);

		var rect		= new Rectangle(topLeft, bottomRight);
		var oval		= new Path.Oval(rect);

		return oval;
	},

	/**
	 * Creates a Path.Rectangle item from an imported SVG rectangle
	 *
	 * @name ImportSVG#importRectangle
	 * @function
	 * @param {XML DOM} svgRectangle An SVG rectangle node
	 * @return {Path.Rectangle} rectangle A Path.Rectangle item for Paper.js
	 */
	 /**
	 * Creates a Path.RoundRectangle item from an imported SVG rectangle
	 * with rounded corners
	 *
	 * @name ImportSVG#importRectangle
	 * @function
	 * @param {XML DOM} svgRectangle An SVG rectangle node with rounded
	 * corners
	 * @return {Path.RoundRectangle} rectangle A Path.Rectangle item for
	 * Paper.js
	_importRectangle: function(svgRectangle)
	{
		var x			= svgRectangle.x.baseVal.value || 0;
		var y			= svgRectangle.y.baseVal.value || 0;
		var rx			= svgRectangle.rx.baseVal.value || 0;
		var ry			= svgRectangle.ry.baseVal.value || 0;
		var width		= svgRectangle.width.baseVal.value || 0;
		var height		= svgRectangle.height.baseVal.value || 0;

		var topLeft		= new Point(x, y);
		var size		= new Size(width, height);
		var rectangle	= new Rectangle(topLeft, size);

		if (rx > 0 || ry > 0) {
			var cornerSize = new Size(rx, ry);
			rectangle = new Path.RoundRectangle(rectangle, cornerSize);
		} else {
			rectangle = new Path.Rectangle(rectangle);
		}

		return rectangle;
	},

	/**
	 * Creates a Path.Line item in Paper.js from an imported SVG line
	 *
	 * @name ImportSVG#importLine
	 * @function
	 * @param {XML DOM} svgLine An SVG line node
	 * @return {Path.Line} line A Path.Line item for Paper.js
	 */
	_importLine: function(svgLine)
	{
		var x1		= svgLine.x1.baseVal.value || 0;
		var y1		= svgLine.y1.baseVal.value || 0;
		var x2		= svgLine.x2.baseVal.value || 0;
		var y2		= svgLine.y2.baseVal.value || 0;

		var from	= new Point(x1, y1);
		var to		= new Point(x2, y2);
		var line	= new Path.Line(from, to);

		return line;
	},

	/**
	 * Creates a PointText item in Paper.js from an imported SVG text node
	 *
	 * @name ImportSVG#importText
	 * @function
	 * @param {XML DOM} svgText An SVG text node
	 * @return {Path.Text} text A PointText item for Paper.js
	 */
	_importText: function(svgText)
	{
		//TODO: Extend this for multiple values
		var x	= svgText.x.baseVal.getItem(0).value || 0;
		var y	= svgText.y.baseVal.getItem(0).value || 0;
		//END:Todo

		var dx; //character kerning
		var dy; //character baseline
		var rotate; //character rotation
		var textLength; //the width of the containing box
		var lengthAdjust; //
		var textContent = svgText.textContent || "";

		var topLeft = new Point(x, y);
		var text = new PointText(topLeft);
		text.content = textContent;
		return text;
	}
});
<commit_msg>Update src/svg/ImportSVG.js<commit_after>/*
* Paper.js
*
* This file is part of Paper.js, a JavaScript Vector Graphics Library,
* based on Scriptographer.org and designed to be largely API compatible.
* http://paperjs.org/
* http://scriptographer.org/
*
* Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*
*
*
* This class and all methods therein designed by Stetson-Team-Alpha
*/

/**
 * @name ImportSVG
 * @class The ImportSVG object represents an object created using the SVG
 * Canvas that will be converted into a Paper.js object.
 * The SVG object is imported into Paper.js by converting it into items
 * within groups.
 *
 */

var ImportSVG = this.ImportSVG = Base.extend(/** @Lends ImportSVG# */{

	/**
	 * Creates a Paper.js object using data parsed from the selected SVG
	 * Document Object Model (DOM). The SVG object is imported, than a layer
	 * is created (with groups for the items if needed).
	 *
	 * Supports nested groups
	 *
	 * @param {SVG DOM} svg An SVG DOM object with parameters
	 * @return {Layer} A Paper.js layer
	 */

	importSVG: function(svg)
	{
	var layer = new Layer();
	groups = this.importGroup(svg);
	layer.addChild(groups);

	return layer;
	},

	/**
	 * Creates a Paper.js group by parsing a specific GNode of the imported
	 * SVG DOM
	 *
	 * @name ImportSVG#importGroup
	 * @function
	 * @param {XML DOM} svg  A node passed in by the imported SVG
	 * @return {Group} group A Paper.js group
	 *
	 *
	 */
	importGroup: function(svg)
	{
		var group = new Group();
		var child;
		for (var i in svg.childNodes) {
			child = svg.childNodes[i];
			if (child.nodeType != 1) {
				continue;
			}
			item = this.importPath(child);
			group.addChild(item);
		}

		return group;
	},

	/**
	 * Creates a Paper.js Path by parsing
	 * a specific SVG node (rectangle, path, circle, polygon, etc.)
	 * and creating the right Path object based on the SVG type.
	 *
	 * @name ImportSVG#importPath
	 * @function
	 * @param {XML DOM} svg An SVG object
	 * @return {Item} item A Paper.js item
	 */
	importPath: function(svg)
	{
		switch (svg.nodeName.toLowerCase()) {
			case 'line':
				item = this._importLine(svg);
				break;
			case 'rect':
				item = this._importRectangle(svg);
				break;
			case 'ellipse':
				item = this._importOval(svg);
				break;
			case 'g':
				item = this.importGroup(svg);
				break;
			case 'text':
				item = this._importText(svg);
				break;
			default:
			break;
		}

		return item;
	},

	/**
	 * Creates a Path.Circle item in Paper.js using an imported Circle from
	 * SVG
	 *
	 * @name ImportSVG#importCircle
	 * @function
	 * @param {XML DOM} svgCircle An SVG circle node
	 * @return {Path.Circle} circle A Path.Circle item for Paper.js
	 */
	_importCircle: function(svgCircle)
	{
		var cx		= svgCircle.cx.baseVal.value || 0;
		var cy		= svgCircle.cy.baseVal.value || 0;
		var r		= svgCircle.r.baseVal.value || 0;
		var center	= new Point(cx, cy);
		var circle	= new Path.Circle(center, r);

		return circle;
	},

	/**
	 * Creates a Path.Oval item in Paper.js using an imported Oval from SVG
	 *
	 * @name ImportSVG#importOval
	 * @function
	 * @param {XML DOM} svgOval An SVG ellipse node
	 * @return {Path.Oval} oval A Path.Oval item for Paper.js
	 */
	_importOval: function(svgOval)
	{
		var cx			= svgOval.cx.baseVal.value || 0;
		var cy			= svgOval.cy.baseVal.value || 0;
		var rx			= svgOval.rx.baseVal.value || 0;
		var ry			= svgOval.ry.baseVal.value || 0;

		var center		= new Point(cx, cy);
		var offset		= new Point(rx, ry);
		var topLeft		= center.subtract(offset);
		var bottomRight	= center.add(offset);

		var rect		= new Rectangle(topLeft, bottomRight);
		var oval		= new Path.Oval(rect);

		return oval;
	},

	/**
	 * Creates a Path.Rectangle item from an imported SVG rectangle
	 *
	 * @name ImportSVG#importRectangle
	 * @function
	 * @param {XML DOM} svgRectangle An SVG rectangle node
	 * @return {Path.Rectangle} rectangle A Path.Rectangle item for Paper.js
	 */
	 /**
	 * Creates a Path.RoundRectangle item from an imported SVG rectangle
	 * with rounded corners
	 *
	 * @name ImportSVG#importRectangle
	 * @function
	 * @param {XML DOM} svgRectangle An SVG rectangle node with rounded
	 * corners
	 * @return {Path.RoundRectangle} rectangle A Path.Rectangle item for
	 * Paper.js
	 */
	_importRectangle: function(svgRectangle)
	{
		var x			= svgRectangle.x.baseVal.value || 0;
		var y			= svgRectangle.y.baseVal.value || 0;
		var rx			= svgRectangle.rx.baseVal.value || 0;
		var ry			= svgRectangle.ry.baseVal.value || 0;
		var width		= svgRectangle.width.baseVal.value || 0;
		var height		= svgRectangle.height.baseVal.value || 0;

		var topLeft		= new Point(x, y);
		var size		= new Size(width, height);
		var rectangle	= new Rectangle(topLeft, size);

		if (rx > 0 || ry > 0) {
			var cornerSize = new Size(rx, ry);
			rectangle = new Path.RoundRectangle(rectangle, cornerSize);
		} else {
			rectangle = new Path.Rectangle(rectangle);
		}

		return rectangle;
	},

	/**
	 * Creates a Path.Line item in Paper.js from an imported SVG line
	 *
	 * @name ImportSVG#importLine
	 * @function
	 * @param {XML DOM} svgLine An SVG line node
	 * @return {Path.Line} line A Path.Line item for Paper.js
	 */
	_importLine: function(svgLine)
	{
		var x1		= svgLine.x1.baseVal.value || 0;
		var y1		= svgLine.y1.baseVal.value || 0;
		var x2		= svgLine.x2.baseVal.value || 0;
		var y2		= svgLine.y2.baseVal.value || 0;

		var from	= new Point(x1, y1);
		var to		= new Point(x2, y2);
		var line	= new Path.Line(from, to);

		return line;
	},

	/**
	 * Creates a PointText item in Paper.js from an imported SVG text node
	 *
	 * @name ImportSVG#importText
	 * @function
	 * @param {XML DOM} svgText An SVG text node
	 * @return {Path.Text} text A PointText item for Paper.js
	 */
	_importText: function(svgText)
	{
		//TODO: Extend this for multiple values
		var x	= svgText.x.baseVal.getItem(0).value || 0;
		var y	= svgText.y.baseVal.getItem(0).value || 0;
		//END:Todo

		var dx; //character kerning
		var dy; //character baseline
		var rotate; //character rotation
		var textLength; //the width of the containing box
		var lengthAdjust; //
		var textContent = svgText.textContent || "";

		var topLeft = new Point(x, y);
		var text = new PointText(topLeft);
		text.content = textContent;
		return text;
	}
});
<|endoftext|>


<commit_before>var utils = require('./utils');
var callMethod = utils.callMethod;
var reportError = utils.reportError;
var errorReporter = utils.errorReporter;
var emoji = require('node-emoji').emoji;

function processCommands(chat_id, text) {
  var commandRegexp = /\/([a-zA-Z0-9_]{1,32})(@MiuBot)?(?:\s|$)/gi;
  var m;
  var wasCommand = {};
  var duplicates = false;
  while ((m = commandRegexp.exec(text)) != null) {
    var command = m[1];
    if (wasCommand[command]) {
      duplicates = true;
      continue;
    }
    wasCommand[command] = true;
    if (command == 'miu') {
      callMethod('sendMessage',
        { chat_id: chat_id,
          text: 'миу'
        }, errorReporter("In 'miu' command")
      );
    } else if (command == 'woof') {
      callMethod('sendSticker',
        { chat_id: chat_id,
          sticker: 'BQADAwADeAUAAmFKuQAB37zscLaXJQQC'
        }, errorReporter("In 'woof' command")
      );
    } else {
      if (chat_id > 0 || m[2]) { // if called in private or in a group by name
        callMethod('sendMessage',
          { chat_id: chat_id,
            text: 'не миу ' + emoji.unamused
          }, errorReporter("In unknown command")
        );
      }
    }
  }
  if (duplicates) {
    callMethod('sendMessage',
      { chat_id: chat_id,
        text: emoji.fearful
      }, errorReporter("In reaction to a lot of commands")
    );
  }
}

function messageReceived(message) {
  var chat_id = message.chat.id;

  if (message.text) {
    processCommands(chat_id, message.text);
    if (message.text.toLowerCase().indexOf("миу") != -1) {
      callMethod('sendMessage', { chat_id: chat_id, text: 'миу ' + emoji.relieved }, errorReporter("In 'miu' reaction"))
    }
    if (message.text.toLowerCase().indexOf("мяу") != -1) {
      callMethod('sendMessage', { chat_id: chat_id, text: 'не "мяу", а "миу"! ' + emoji.angry }, errorReporter("In 'meow' reaction"))
    }
    if (message.text.toLowerCase().indexOf("гав") != -1) {
      callMethod('sendMessage', { chat_id: chat_id, text: 'не "гав", а "/woof"! ' + emoji.smirk_cat }, errorReporter("In 'woof' reaction"))
    }
  }
}

var updatesOffset = 0;
function requestUpdates() {
  callMethod('getUpdates', {timeout: 25, offset: updatesOffset},
    function(error) {
      reportError('In requestUpdates: ' + error);
      setTimeout(requestUpdates, 2000);
    },
    function(data) {
      for (var i in data) {
        var upd = data[i];
        updatesOffset = Math.max(updatesOffset, upd.update_id + 1);
        messageReceived(upd.message);
      }
      requestUpdates();
    }
  );
}

requestUpdates();
<commit_msg>now doesn't react to more than one _command_ per message<commit_after>var utils = require('./utils');
var callMethod = utils.callMethod;
var reportError = utils.reportError;
var errorReporter = utils.errorReporter;
var emoji = require('node-emoji').emoji;

function processCommands(chat_id, text) {
  var commandRegexp = /\/([a-zA-Z0-9_]{1,32})(@MiuBot)?(?:\s|$)/gi;
  var m;
  var wasCommand = {};
  var duplicates = false;
  var saidSomething = false;
  while ((m = commandRegexp.exec(text)) != null) {
    var command = m[1];
    if (wasCommand[command]) {
      duplicates = true;
      continue;
    }
    wasCommand[command] = true;
    if (saidSomething) {
      continue;
    }
    if (command == 'miu') {
      callMethod('sendMessage',
        { chat_id: chat_id,
          text: 'миу'
        }, errorReporter("In 'miu' command")
      );
      saidSomething = true;
    } else if (command == 'woof') {
      callMethod('sendSticker',
        { chat_id: chat_id,
          sticker: 'BQADAwADeAUAAmFKuQAB37zscLaXJQQC'
        }, errorReporter("In 'woof' command")
      );
      saidSomething = true;
    } else {
      if (chat_id > 0 || m[2]) { // if called in private or in a group by name
        callMethod('sendMessage',
          { chat_id: chat_id,
            text: 'не миу ' + emoji.unamused
          }, errorReporter("In unknown command")
        );
        saidSomething = true;
      }
    }
  }
  if (duplicates) {
    callMethod('sendMessage',
      { chat_id: chat_id,
        text: emoji.fearful
      }, errorReporter("In reaction to a lot of commands")
    );
    saidSomething = true;
  }
}

function messageReceived(message) {
  var chat_id = message.chat.id;

  if (message.text) {
    processCommands(chat_id, message.text);
    if (message.text.toLowerCase().indexOf("миу") != -1) {
      callMethod('sendMessage', { chat_id: chat_id, text: 'миу ' + emoji.relieved }, errorReporter("In 'miu' reaction"))
    }
    if (message.text.toLowerCase().indexOf("мяу") != -1) {
      callMethod('sendMessage', { chat_id: chat_id, text: 'не "мяу", а "миу"! ' + emoji.angry }, errorReporter("In 'meow' reaction"))
    }
    if (message.text.toLowerCase().indexOf("гав") != -1) {
      callMethod('sendMessage', { chat_id: chat_id, text: 'не "гав", а "/woof"! ' + emoji.smirk_cat }, errorReporter("In 'woof' reaction"))
    }
  }
}

var updatesOffset = 0;
function requestUpdates() {
  callMethod('getUpdates', {timeout: 25, offset: updatesOffset},
    function(error) {
      reportError('In requestUpdates: ' + error);
      setTimeout(requestUpdates, 2000);
    },
    function(data) {
      for (var i in data) {
        var upd = data[i];
        updatesOffset = Math.max(updatesOffset, upd.update_id + 1);
        messageReceived(upd.message);
      }
      requestUpdates();
    }
  );
}

requestUpdates();
<|endoftext|>


<commit_before>/**
 *  Imports svg into items with groups
 *  Stetson Alpha - Paper.js
 *
 */

var ImportSVG = function()
{
    //initialize
    function initialize()
    {

    };

    /**
     *
     * Takes the svg dom obj and parses the data
     * to create a layer with groups (if needed) with
     * items inside. Should support nested groups.
     *
     * takes in a svg object (xml dom)
     * returns Paper.js Layer
     */
    this.importSVG = function(svg)
    {
        return layer;
    };

    /**
     * Creates a Paper.js Group by parsing
     * a specific svg g node
     *
     * takes in a svg object (xml dom)
     * returns Paper.js Group
     */
    function importGroup(svg)
    {
        return group;
    };

    /**
     * Creates a Paper.js Path by parsing
     * a specific svg node (rect, path, circle, polygon, etc)
     * and creating the right path object based on the svg type.
     *
     * takes in a svg object (xml dom)
     * returns Paper.js Group
     */
    function importPath(svg)
    {
        return path;
    };

    initialize(); // calls the init function after class is loaded
};<commit_msg>Reformat the code to match the rest of Paper.js<commit_after>/**
 *  Imports svg into items with groups
 *  Stetson Alpha - Paper.js
 *
 */

var ImportSVG = this.ImportSVG = Base.extend({
{
    //initialize
    initialize: function()
    {

    },

    /**
     *
     * Takes the svg dom obj and parses the data
     * to create a layer with groups (if needed) with
     * items inside. Should support nested groups.
     *
     * takes in a svg object (xml dom)
     * returns Paper.js Layer
     */
    importSVG: function(svg)
    {
        //TODO: return layer;
    },

    /**
     * Creates a Paper.js Group by parsing
     * a specific svg g node
     *
     * takes in a svg object (xml dom)
     * returns Paper.js Group
     */
    importGroup: function(svg)
    {
        //TODO: return group;
    },

    /**
     * Creates a Paper.js Path by parsing
     * a specific svg node (rect, path, circle, polygon, etc)
     * and creating the right path object based on the svg type.
     *
     * takes in a svg object (xml dom)
     * returns Paper.js Group
     */
    importPath: function(svg)
    {
        //TODO: return path;
    }
});<|endoftext|>


<commit_before>/**
 * Default Configuration
 *
 * Extend the class exported from this module to create your own local
 * configuration objects or use this directly.
 * A configuration file is any ES6 file that exports a single default
 * object containing all of the configuration options.
 *
 * Avoid requiring this file into any file that might need this one.
 * In general game logic should never need this, a config object should
 * be passed around through constructors.
 *
 * Try to keep the structure as flat as possible while grouping things logically
 */

const COLORS = require('../constants/colors');
const GAMES = require('../constants/games');

const Disk = require('../utils/disk');

export default class DefaultConfig {
  constructor({
      username="",
      user0="sculpture0",
      user1="sculpture1",
      user2="sculpture2"
  } = {}) {
    this.user0 = user0;
    this.user1 = user1;
    this.user2 = user2;

    // The username of the current user
    this.username = username || user0;

    // A mapping between usernames and the colors that represent them
    this.COLORS = {
      USERS: {
        // username : color
        [this.user0]: COLORS.USER0,
        [this.user1]: COLORS.USER1,
        [this.user2]: COLORS.USER2
      },
      ERROR: 'error'
    };

    // The sequence of the games to be run. The first game is run on startup
    this.GAMES_SEQUENCE = [
      GAMES.HANDSHAKE,
      GAMES.MOLE,
      GAMES.DISK,
      GAMES.SIMON
    ];

    /******* LIGHTS ********************/
    this.LIGHTS = {
      STRIP_A: '0',
      STRIP_B: '1',
      STRIP_C: '2',
      PERIMETER_STRIP: '3',
      DISK_LIGHT_STRIP: '4',
      HANDSHAKE_STRIP: '5',
      ART_LIGHTS_STRIP: '6'
    }
    this.LIGHTS.GAME_STRIPS = [
      this.LIGHTS.STRIP_A,
      this.LIGHTS.STRIP_B,
      this.LIGHTS.STRIP_C,
    ];

    // These settings effect the default behaviour of panels outside of
    // any custom logic in any of the games
    this.PANEL_DEFAULTS = {
      ACTIVE_INTENSITY: 100,
      INACTIVE_INTENSITY: 0
    };

    /******* GAMES CONFIGURATION *******/

    this.HANDSHAKE_GAME = {
      TRANSITION_OUT_TIME: 4000
    },
    this.MOLE_GAME = {
      INITIAL_PANELS: [
        {stripId: this.LIGHTS.STRIP_A, panelId: '3'},
        {stripId: this.LIGHTS.STRIP_A, panelId: '7'},
        {stripId: this.LIGHTS.STRIP_C, panelId: '6'},
        {stripId: this.LIGHTS.STRIP_B, panelId: '5'}
      ],
      NUM_ACTIVE_PANELS: {
        10: 1, // At panelCount of 10, increase # of simultaneusly active panels
        20: 1,
        25: -1, // At panelCount of 25, decrease # of simultaneusly active panels
        27: -1
      },
      PANEL_LIFETIME: [
        {count: 0, range: [10, 10]}, // Initial timeout
        {count: 4, range: [4, 6]}, // At panelCount of 4, set panel lifetime to 4-6 seconds. Gradually interpolate to next timeout level
        {count: 20, range: [2, 3]},
        {count: 30, range: [1.5, 2]}
      ],
      PANEL_SUCCESS_DELAY: 1000,
      // The intensity to use on the active panels
      ACTIVE_PANEL_INTENSITY: 100,
      // The intensity to use on the active panels
      INACTIVE_PANEL_INTENSITY: 0,
      // The intensity to use on the inactive panels (panels turned to location color)
      COLORED_PANEL_INTENSITY: 75
    };

    this.DISK_GAME = {
      // The user will wins when they reach these positions for each diskId.
      RELATIVE_TOLERANCE: 8, // degrees tolerance for disks relative to each other
      ABSOLUTE_TOLERANCE: 8, // degrees tolerance for the absolute disk positions
      // The intensity of the panels that the user can use to play the sequence
      CONTROL_PANEL_INTENSITY: 20,
      ACTIVE_CONTROL_PANEL_INTENSITY: 100,
      ACTIVE_PERIMETER_INTENSITY: 100,
      INACTIVE_PERIMETER_INTENSITY: 50,
      PERIMETER_COLOR: "white",
      SHADOW_LIGHTS: {
        // stripId: [panelId..]
        '6': ['0', '1', '2']
      },
      SHADOW_LIGHT_INTENSITY: 100,
      LEVELS: [
        // level 0
        // disks: { diskId: target position }
        // perimeter: { stripId: [panelIds..] }
        { disks:     { disk2: 203, disk1: 0, disk0: 175 },
          perimeter: { [this.LIGHTS.PERIMETER_STRIP]: ['0', '2']  }
        },
        // level 1
        { disks:     { disk2: 176,  disk1: 307, disk0: 348 },
          perimeter: { [this.LIGHTS.PERIMETER_STRIP]: ['3', '5']  }
        },
        // level 2
        { disks:     { disk2: 337, disk1: 325,  disk0: 244 },
          perimeter: { [this.LIGHTS.PERIMETER_STRIP]: ['1', '4']  }
        }
      ],
      LIGHT_MAPPING: {
        // diskId: { stripId: panelId }
        disk0: { [this.LIGHTS.DISK_LIGHT_STRIP]: '0' },
        disk1: { [this.LIGHTS.DISK_LIGHT_STRIP]: '1' },
        disk2: { [this.LIGHTS.DISK_LIGHT_STRIP]: '2' }
      },
      CONTROL_MAPPINGS: {
        CLOCKWISE_STRIP: this.LIGHTS.STRIP_C,
        COUNTERCLOCKWISE_STRIP: this.LIGHTS.STRIP_A,

        CLOCKWISE_PANELS: {
          // diskId : [panelId1, ...]
          disk0: ['1', '2'],
          disk1: ['4', '5'],
          disk2: ['7', '8']
        },
        COUNTERCLOCKWISE_PANELS: {
          disk0: ['1', '2'],
          disk1: ['4', '5'],
          disk2: ['7', '8']
        }
      }
    };

    this.SIMON_GAME = {
      PATTERN_LEVELS: [
        // level 0 sequence
        {
          stripId: this.LIGHTS.STRIP_A,
          // Each array of panel IDs is lit up one at a time
          // Each array within this array is called a "frame" in the "sequence"
          panelSequence: [['3'], ['5'], ['7']]
        },
        // level 1 sequence
        {
          stripId: '1',
          panelSequence: [['1'], ['8'], ['5']]
        },
        // level 2 sequence
        {
          stripId: '2',
          panelSequence: [['3'], ['6'], ['2'], ['9']]
        }
      ],
      // The intensity of the panels when they are pressed or when the sequence is playing
      TARGET_PANEL_INTENSITY: 100,
      // The intensity of the panels that the user can use to play the sequence
      AVAILABLE_PANEL_INTENSITY: 1,
      // The delay in ms between sequence frames
      SEQUENCE_ANIMATION_FRAME_DELAY: 500,
      // The delay in ms to wait before replaying the sequence
      // Only replayed if no input is received from the user
      DELAY_BETWEEN_PLAYS: 5000,
      // The time after input to wait for the user to finish the sequence
      INPUT_TIMEOUT: 10000,
      // The default color to set the panels to when
      DEFAULT_SIMON_PANEL_COLOR: "white",
      // Wait while playing final sound
      TRANSITION_OUT_TIME: 10000
    };
  }

  getUserColor(username) {
    return this.COLORS.USERS[username];
  }
}

<commit_msg>Mole game: Disable failure sound<commit_after>/**
 * Default Configuration
 *
 * Extend the class exported from this module to create your own local
 * configuration objects or use this directly.
 * A configuration file is any ES6 file that exports a single default
 * object containing all of the configuration options.
 *
 * Avoid requiring this file into any file that might need this one.
 * In general game logic should never need this, a config object should
 * be passed around through constructors.
 *
 * Try to keep the structure as flat as possible while grouping things logically
 */

const COLORS = require('../constants/colors');
const GAMES = require('../constants/games');

const Disk = require('../utils/disk');

export default class DefaultConfig {
  constructor({
      username="",
      user0="sculpture0",
      user1="sculpture1",
      user2="sculpture2"
  } = {}) {
    this.user0 = user0;
    this.user1 = user1;
    this.user2 = user2;

    // The username of the current user
    this.username = username || user0;

    // A mapping between usernames and the colors that represent them
    this.COLORS = {
      USERS: {
        // username : color
        [this.user0]: COLORS.USER0,
        [this.user1]: COLORS.USER1,
        [this.user2]: COLORS.USER2
      },
      ERROR: 'error'
    };

    // The sequence of the games to be run. The first game is run on startup
    this.GAMES_SEQUENCE = [
      GAMES.HANDSHAKE,
      GAMES.MOLE,
      GAMES.DISK,
      GAMES.SIMON
    ];

    /******* LIGHTS ********************/
    this.LIGHTS = {
      STRIP_A: '0',
      STRIP_B: '1',
      STRIP_C: '2',
      PERIMETER_STRIP: '3',
      DISK_LIGHT_STRIP: '4',
      HANDSHAKE_STRIP: '5',
      ART_LIGHTS_STRIP: '6'
    }
    this.LIGHTS.GAME_STRIPS = [
      this.LIGHTS.STRIP_A,
      this.LIGHTS.STRIP_B,
      this.LIGHTS.STRIP_C,
    ];

    // These settings effect the default behaviour of panels outside of
    // any custom logic in any of the games
    this.PANEL_DEFAULTS = {
      ACTIVE_INTENSITY: 100,
      INACTIVE_INTENSITY: 0
    };

    /******* GAMES CONFIGURATION *******/

    this.HANDSHAKE_GAME = {
      TRANSITION_OUT_TIME: 4000
    },
    this.MOLE_GAME = {
      INITIAL_PANELS: [
        {stripId: this.LIGHTS.STRIP_A, panelId: '3'},
        {stripId: this.LIGHTS.STRIP_A, panelId: '7'},
        {stripId: this.LIGHTS.STRIP_C, panelId: '6'},
        {stripId: this.LIGHTS.STRIP_B, panelId: '5'}
      ],
      NUM_ACTIVE_PANELS: {
        10: 1, // At panelCount of 10, increase # of simultaneusly active panels
        20: 1,
        25: -1, // At panelCount of 25, decrease # of simultaneusly active panels
        27: -1
      },
      PANEL_LIFETIME: [
        {count: 0, range: [10, 10]}, // Initial timeout
        {count: 4, range: [4, 6]}, // At panelCount of 4, set panel lifetime to 4-6 seconds. Gradually interpolate to next timeout level
        {count: 20, range: [2, 3]},
        {count: 30, range: [1.5, 2]}
      ],
      PANEL_SUCCESS_DELAY: 1000,
      // The intensity to use on the active panels
      ACTIVE_PANEL_INTENSITY: 100,
      // The intensity to use on the active panels
      INACTIVE_PANEL_INTENSITY: 0,
      // The intensity to use on the inactive panels (panels turned to location color)
      COLORED_PANEL_INTENSITY: 75,
      ENABLE_FAILURE_SOUND: false
    };

    this.DISK_GAME = {
      // The user will wins when they reach these positions for each diskId.
      RELATIVE_TOLERANCE: 8, // degrees tolerance for disks relative to each other
      ABSOLUTE_TOLERANCE: 8, // degrees tolerance for the absolute disk positions
      // The intensity of the panels that the user can use to play the sequence
      CONTROL_PANEL_INTENSITY: 20,
      ACTIVE_CONTROL_PANEL_INTENSITY: 100,
      ACTIVE_PERIMETER_INTENSITY: 100,
      INACTIVE_PERIMETER_INTENSITY: 50,
      PERIMETER_COLOR: "white",
      SHADOW_LIGHTS: {
        // stripId: [panelId..]
        '6': ['0', '1', '2']
      },
      SHADOW_LIGHT_INTENSITY: 100,
      LEVELS: [
        // level 0
        // disks: { diskId: target position }
        // perimeter: { stripId: [panelIds..] }
        { disks:     { disk2: 203, disk1: 0, disk0: 175 },
          perimeter: { [this.LIGHTS.PERIMETER_STRIP]: ['0', '2']  }
        },
        // level 1
        { disks:     { disk2: 176,  disk1: 307, disk0: 348 },
          perimeter: { [this.LIGHTS.PERIMETER_STRIP]: ['3', '5']  }
        },
        // level 2
        { disks:     { disk2: 337, disk1: 325,  disk0: 244 },
          perimeter: { [this.LIGHTS.PERIMETER_STRIP]: ['1', '4']  }
        }
      ],
      LIGHT_MAPPING: {
        // diskId: { stripId: panelId }
        disk0: { [this.LIGHTS.DISK_LIGHT_STRIP]: '0' },
        disk1: { [this.LIGHTS.DISK_LIGHT_STRIP]: '1' },
        disk2: { [this.LIGHTS.DISK_LIGHT_STRIP]: '2' }
      },
      CONTROL_MAPPINGS: {
        CLOCKWISE_STRIP: this.LIGHTS.STRIP_C,
        COUNTERCLOCKWISE_STRIP: this.LIGHTS.STRIP_A,

        CLOCKWISE_PANELS: {
          // diskId : [panelId1, ...]
          disk0: ['1', '2'],
          disk1: ['4', '5'],
          disk2: ['7', '8']
        },
        COUNTERCLOCKWISE_PANELS: {
          disk0: ['1', '2'],
          disk1: ['4', '5'],
          disk2: ['7', '8']
        }
      }
    };

    this.SIMON_GAME = {
      PATTERN_LEVELS: [
        // level 0 sequence
        {
          stripId: this.LIGHTS.STRIP_A,
          // Each array of panel IDs is lit up one at a time
          // Each array within this array is called a "frame" in the "sequence"
          panelSequence: [['3'], ['5'], ['7']]
        },
        // level 1 sequence
        {
          stripId: '1',
          panelSequence: [['1'], ['8'], ['5']]
        },
        // level 2 sequence
        {
          stripId: '2',
          panelSequence: [['3'], ['6'], ['2'], ['9']]
        }
      ],
      // The intensity of the panels when they are pressed or when the sequence is playing
      TARGET_PANEL_INTENSITY: 100,
      // The intensity of the panels that the user can use to play the sequence
      AVAILABLE_PANEL_INTENSITY: 1,
      // The delay in ms between sequence frames
      SEQUENCE_ANIMATION_FRAME_DELAY: 500,
      // The delay in ms to wait before replaying the sequence
      // Only replayed if no input is received from the user
      DELAY_BETWEEN_PLAYS: 5000,
      // The time after input to wait for the user to finish the sequence
      INPUT_TIMEOUT: 10000,
      // The default color to set the panels to when
      DEFAULT_SIMON_PANEL_COLOR: "white",
      // Wait while playing final sound
      TRANSITION_OUT_TIME: 10000
    };
  }

  getUserColor(username) {
    return this.COLORS.USERS[username];
  }
}

<|endoftext|>


<commit_before>import Class from "./class.js"
import { Pair } from "./pair.js"
import _ from "../deps/underscore-1.10.2-esm.js"

  //
  // Parser
  // copied from jsScheme - should be rewrriten (support #0=, etc)
  //
  const Parser = Class.create({
    initialize: function(txt){
      this.tokens = this.tokenize(txt);
      this.i = 0;
    },

    inspect: function(){
      return [
        "#<Parser:",
        this.i, "/", this.tokens.length, " ",
        BiwaScheme.inspect(this.tokens),
        ">"
      ].join("");
    },

    tokenize: function(txt) {
      var tokens = new Array(), oldTxt=null;
      var in_srfi_30_comment = 0;

      while( txt != "" && oldTxt != txt ) {
        oldTxt = txt;
        txt = txt.replace( /^\s*(;[^\r\n]*(\r|\n|$)|#;|#\||#\\[^\w]|#?(\(|\[|{)|\)|\]|}|\'|`|,@|,|\+inf\.0|-inf\.0|\+nan\.0|\"(\\(.|$)|[^\"\\])*(\"|$)|[^\s()\[\]{}]+)/,
        function($0,$1) {
          var t = $1;

          if (t == "#|") {
            in_srfi_30_comment++;
            return "";
          }
          else if (in_srfi_30_comment > 0) {
            if ( /(.*\|#)/.test(t) ) {
              in_srfi_30_comment--;
              if (in_srfi_30_comment < 0) {
                throw new BiwaScheme.Error("Found an extra comment terminator: `|#'")
              }
              // Push back the rest substring to input stream.
              return t.substring(RegExp.$1.length, t.length);
            }
            else {
              return "";
            }
          }
          else {
            if( t.charAt(0) != ';' ) tokens[tokens.length]=t;
            return "";
          }
        } );
      }
      return tokens;
    },

    sexpCommentMarker: new Object,
    getObject: function() {
      var r = this.getObject0();

      if (r != this.sexpCommentMarker)
        return r;

      r = this.getObject();
      if (r == BiwaScheme.Parser.EOS)
        throw new BiwaScheme.Error("Readable object not found after S exression comment");

      r = this.getObject();
      return r;
    },

    getList: function( close ) {
      var list = BiwaScheme.nil, prev = list;
      while( this.i < this.tokens.length ) {

        this.eatObjectsInSexpComment("Input stream terminated unexpectedly(in list)");

        if( this.tokens[ this.i ] == ')' || this.tokens[ this.i ] == ']' || this.tokens[ this.i ] == '}' ) {
          this.i++; break;
        }

        if( this.tokens[ this.i ] == '.' ) {
          this.i++;
          var o = this.getObject();
          if( o != BiwaScheme.Parser.EOS && list != BiwaScheme.nil ) {
            prev.cdr = o;
          }
        } else {
            var cur = new BiwaScheme.Pair( this.getObject(), BiwaScheme.nil);
            if( list == BiwaScheme.nil ) list = cur;
            else prev.cdr = cur;
            prev = cur;
        }
      }
      return list;
    },

    getVector: function( close ) {
      var arr = new Array();
      while( this.i < this.tokens.length ) {

        this.eatObjectsInSexpComment("Input stream terminated unexpectedly(in vector)");

        if( this.tokens[ this.i ] == ')' ||
        this.tokens[ this.i ] == ']' ||
        this.tokens[ this.i ] == '}' ) { this.i++; break; }
        arr[ arr.length ] = this.getObject();
      }
      return arr;
    },

    eatObjectsInSexpComment: function(err_msg) {
      while( this.tokens[ this.i ] == '#;' ) {
        this.i++;
        if ((this.getObject() == BiwaScheme.Parser.EOS) || (this.i >= this.tokens.length))
          throw new BiwaScheme.Error(err_msg);
      }
    },

    getObject0: function() {
      if( this.i >= this.tokens.length )
        return BiwaScheme.Parser.EOS;

      var t = this.tokens[ this.i++ ];
      // if( t == ')' ) return null;

      if (t == '#;')
        return this.sexpCommentMarker;

      var s = t == "'"  ? 'quote' :
              t == "`"  ? 'quasiquote' :
              t == ","  ? 'unquote' :
              t == ",@" ? 'unquote-splicing' : false;

      if( s || t == '(' || t == '#(' || t == '[' || t == '#[' || t == '{' || t == '#{' ) {
        return s ? new BiwaScheme.Pair( BiwaScheme.Sym(s), new BiwaScheme.Pair( this.getObject(), BiwaScheme.nil ))
        : (t=='(' || t=='[' || t=='{') ? this.getList(t) : this.getVector(t);
      }
      else {
        switch(t){
          case "+inf.0" : return Infinity;
          case "-inf.0" : return -Infinity;
          case "+nan.0" : return NaN;
        }

        var n;
        if( /^#x[0-9a-z]+$/i.test(t) ) {  // #x... Hex
          n = new Number('0x'+t.substring(2,t.length) );
        }
        else if( /^#d[0-9\.]+$/i.test(t) ) {  // #d... Decimal
          n = new Number( t.substring(2,t.length) );
        }
        else{
          n = new Number(t);  // use constrictor as parser
        }

        if( ! isNaN(n) ) {
          return n.valueOf();
        } else if( t == '#f' || t == '#F' ) {
          return false;
        } else if( t == '#t' || t == '#T' ) {
          return true;
        } else if( t.toLowerCase() == '#\\newline' ) {
          return BiwaScheme.Char.get('\n');
        } else if( t.toLowerCase() == '#\\space' ) {
          return BiwaScheme.Char.get(' ');
        } else if( t.toLowerCase() == '#\\tab' ) {
          return BiwaScheme.Char.get('\t');
        } else if( /^#\\.$/.test(t) ) {
          return BiwaScheme.Char.get( t.charAt(2) );
        } else if( /^#\\x[a-zA-Z0-9]+$/.test(t) ) {
          var scalar = parseInt(t.slice(3), 16);
          // R6RS 11.11 (surrogate codepoints)
          if (scalar >= 0xD800 && scalar <= 0xDFFF) {
            throw new BiwaScheme.Error("Character in Unicode excluded range.");
          }
          // ECMA-262 4.3.16 -- Basically, strings are sequences of 16-bit
          // unsigned integers, so anything greater than 0xFFFF won't fit.
          // NOTE: This violates R6RS which requires the full Unicode range!
          else if (scalar > 0xFFFF) {
            throw new BiwaScheme.Error("Character literal out of range.");
          } else {
            return BiwaScheme.Char.get(String.fromCharCode(scalar));
          }
        } else if( /^\"(\\(.|$)|[^\"\\])*\"?$/.test(t) ) {
          return t.replace(/(\r?\n|\\n)/g, "\n").replace( /^\"|\\(.|$)|\"$/g, function($0,$1) {
            return $1 ? $1 : '';
          } );
        } else return BiwaScheme.Sym(t);  // 2Do: validate !!
      }
    }
  });
  // indicates end of source file
  Parser.EOS = new Object();

export default Parser;
<commit_msg>style: Deindent<commit_after>import Class from "./class.js"
import { Pair } from "./pair.js"
import _ from "../deps/underscore-1.10.2-esm.js"

//
// Parser
// copied from jsScheme - should be rewrriten (support #0=, etc)
//
const Parser = Class.create({
  initialize: function(txt){
    this.tokens = this.tokenize(txt);
    this.i = 0;
  },

  inspect: function(){
    return [
      "#<Parser:",
      this.i, "/", this.tokens.length, " ",
      BiwaScheme.inspect(this.tokens),
      ">"
    ].join("");
  },

  tokenize: function(txt) {
    var tokens = new Array(), oldTxt=null;
    var in_srfi_30_comment = 0;

    while( txt != "" && oldTxt != txt ) {
      oldTxt = txt;
      txt = txt.replace( /^\s*(;[^\r\n]*(\r|\n|$)|#;|#\||#\\[^\w]|#?(\(|\[|{)|\)|\]|}|\'|`|,@|,|\+inf\.0|-inf\.0|\+nan\.0|\"(\\(.|$)|[^\"\\])*(\"|$)|[^\s()\[\]{}]+)/,
      function($0,$1) {
        var t = $1;

        if (t == "#|") {
          in_srfi_30_comment++;
          return "";
        }
        else if (in_srfi_30_comment > 0) {
          if ( /(.*\|#)/.test(t) ) {
            in_srfi_30_comment--;
            if (in_srfi_30_comment < 0) {
              throw new BiwaScheme.Error("Found an extra comment terminator: `|#'")
            }
            // Push back the rest substring to input stream.
            return t.substring(RegExp.$1.length, t.length);
          }
          else {
            return "";
          }
        }
        else {
          if( t.charAt(0) != ';' ) tokens[tokens.length]=t;
          return "";
        }
      } );
    }
    return tokens;
  },

  sexpCommentMarker: new Object,
  getObject: function() {
    var r = this.getObject0();

    if (r != this.sexpCommentMarker)
      return r;

    r = this.getObject();
    if (r == BiwaScheme.Parser.EOS)
      throw new BiwaScheme.Error("Readable object not found after S exression comment");

    r = this.getObject();
    return r;
  },

  getList: function( close ) {
    var list = BiwaScheme.nil, prev = list;
    while( this.i < this.tokens.length ) {

      this.eatObjectsInSexpComment("Input stream terminated unexpectedly(in list)");

      if( this.tokens[ this.i ] == ')' || this.tokens[ this.i ] == ']' || this.tokens[ this.i ] == '}' ) {
        this.i++; break;
      }

      if( this.tokens[ this.i ] == '.' ) {
        this.i++;
        var o = this.getObject();
        if( o != BiwaScheme.Parser.EOS && list != BiwaScheme.nil ) {
          prev.cdr = o;
        }
      } else {
          var cur = new BiwaScheme.Pair( this.getObject(), BiwaScheme.nil);
          if( list == BiwaScheme.nil ) list = cur;
          else prev.cdr = cur;
          prev = cur;
      }
    }
    return list;
  },

  getVector: function( close ) {
    var arr = new Array();
    while( this.i < this.tokens.length ) {

      this.eatObjectsInSexpComment("Input stream terminated unexpectedly(in vector)");

      if( this.tokens[ this.i ] == ')' ||
      this.tokens[ this.i ] == ']' ||
      this.tokens[ this.i ] == '}' ) { this.i++; break; }
      arr[ arr.length ] = this.getObject();
    }
    return arr;
  },

  eatObjectsInSexpComment: function(err_msg) {
    while( this.tokens[ this.i ] == '#;' ) {
      this.i++;
      if ((this.getObject() == BiwaScheme.Parser.EOS) || (this.i >= this.tokens.length))
        throw new BiwaScheme.Error(err_msg);
    }
  },

  getObject0: function() {
    if( this.i >= this.tokens.length )
      return BiwaScheme.Parser.EOS;

    var t = this.tokens[ this.i++ ];
    // if( t == ')' ) return null;

    if (t == '#;')
      return this.sexpCommentMarker;

    var s = t == "'"  ? 'quote' :
            t == "`"  ? 'quasiquote' :
            t == ","  ? 'unquote' :
            t == ",@" ? 'unquote-splicing' : false;

    if( s || t == '(' || t == '#(' || t == '[' || t == '#[' || t == '{' || t == '#{' ) {
      return s ? new BiwaScheme.Pair( BiwaScheme.Sym(s), new BiwaScheme.Pair( this.getObject(), BiwaScheme.nil ))
      : (t=='(' || t=='[' || t=='{') ? this.getList(t) : this.getVector(t);
    }
    else {
      switch(t){
        case "+inf.0" : return Infinity;
        case "-inf.0" : return -Infinity;
        case "+nan.0" : return NaN;
      }

      var n;
      if( /^#x[0-9a-z]+$/i.test(t) ) {  // #x... Hex
        n = new Number('0x'+t.substring(2,t.length) );
      }
      else if( /^#d[0-9\.]+$/i.test(t) ) {  // #d... Decimal
        n = new Number( t.substring(2,t.length) );
      }
      else{
        n = new Number(t);  // use constrictor as parser
      }

      if( ! isNaN(n) ) {
        return n.valueOf();
      } else if( t == '#f' || t == '#F' ) {
        return false;
      } else if( t == '#t' || t == '#T' ) {
        return true;
      } else if( t.toLowerCase() == '#\\newline' ) {
        return BiwaScheme.Char.get('\n');
      } else if( t.toLowerCase() == '#\\space' ) {
        return BiwaScheme.Char.get(' ');
      } else if( t.toLowerCase() == '#\\tab' ) {
        return BiwaScheme.Char.get('\t');
      } else if( /^#\\.$/.test(t) ) {
        return BiwaScheme.Char.get( t.charAt(2) );
      } else if( /^#\\x[a-zA-Z0-9]+$/.test(t) ) {
        var scalar = parseInt(t.slice(3), 16);
        // R6RS 11.11 (surrogate codepoints)
        if (scalar >= 0xD800 && scalar <= 0xDFFF) {
          throw new BiwaScheme.Error("Character in Unicode excluded range.");
        }
        // ECMA-262 4.3.16 -- Basically, strings are sequences of 16-bit
        // unsigned integers, so anything greater than 0xFFFF won't fit.
        // NOTE: This violates R6RS which requires the full Unicode range!
        else if (scalar > 0xFFFF) {
          throw new BiwaScheme.Error("Character literal out of range.");
        } else {
          return BiwaScheme.Char.get(String.fromCharCode(scalar));
        }
      } else if( /^\"(\\(.|$)|[^\"\\])*\"?$/.test(t) ) {
        return t.replace(/(\r?\n|\\n)/g, "\n").replace( /^\"|\\(.|$)|\"$/g, function($0,$1) {
          return $1 ? $1 : '';
        } );
      } else return BiwaScheme.Sym(t);  // 2Do: validate !!
    }
  }
});
// indicates end of source file
Parser.EOS = new Object();

export default Parser;
<|endoftext|>


<commit_before>//
// Syntax
//
BiwaScheme.Syntax = BiwaScheme.Class.create({
  initialize: function(sname, func){
    this.sname = sname;
    this.func = func;
  },
  transform: function(x){
    if (!this.func){
      throw new BiwaScheme.Bug("sorry, syntax "+this.sname+
                               " is a pseudo syntax now");
    }
    return this.func(x);
  },
  inspect: function(){
    return "#<Syntax " + this.sname +">";
  }
})

// A built-in syntax did not have associated Syntax object.
// Following code installed dummy Syntax objects to built-in syntax.
BiwaScheme.TopEnv["define"] = new BiwaScheme.Syntax("define");
BiwaScheme.TopEnv["begin"]  = new BiwaScheme.Syntax("begin");
BiwaScheme.TopEnv["quote"]  = new BiwaScheme.Syntax("quote");
BiwaScheme.TopEnv["lambda"] = new BiwaScheme.Syntax("lambda");
BiwaScheme.TopEnv["if"]     = new BiwaScheme.Syntax("if");
BiwaScheme.TopEnv["set!"]   = new BiwaScheme.Syntax("set!");
<commit_msg>Move pseudo syntaxes to CoreEnv<commit_after>//
// Syntax
//
BiwaScheme.Syntax = BiwaScheme.Class.create({
  initialize: function(sname, func){
    this.sname = sname;
    this.func = func;
  },
  transform: function(x){
    if (!this.func){
      throw new BiwaScheme.Bug("sorry, syntax "+this.sname+
                               " is a pseudo syntax now");
    }
    return this.func(x);
  },
  inspect: function(){
    return "#<Syntax " + this.sname +">";
  }
})

// A built-in syntax did not have associated Syntax object.
// Following code installed dummy Syntax objects to built-in syntax.
BiwaScheme.CoreEnv["define"] = new BiwaScheme.Syntax("define");
BiwaScheme.CoreEnv["begin"]  = new BiwaScheme.Syntax("begin");
BiwaScheme.CoreEnv["quote"]  = new BiwaScheme.Syntax("quote");
BiwaScheme.CoreEnv["lambda"] = new BiwaScheme.Syntax("lambda");
BiwaScheme.CoreEnv["if"]     = new BiwaScheme.Syntax("if");
BiwaScheme.CoreEnv["set!"]   = new BiwaScheme.Syntax("set!");
<|endoftext|>


<commit_before>var sdf = require("../src/simpleDateFormat.js");

describe("simple date format with default locale", function () {
  /*
   * All the tests below assumes the SimpleDateFormat's default locale is
   * EN_US which means every text in English and the first day of the week
   * is Sunday.
   */

	it("formats era designator", function() {
    var d = new Date();
    expect(new sdf.SimpleDateFormat("G").format(d)).toBe("AD");
  });

  it("formats year", function() {
    var d = new Date(89, 11, 6);
    expect(new sdf.SimpleDateFormat("y").format(d)).toBe("1989");
    expect(new sdf.SimpleDateFormat("yy").format(d)).toBe("89");
    expect(new sdf.SimpleDateFormat("yyy").format(d)).toBe("1989");
    expect(new sdf.SimpleDateFormat("yyyy").format(d)).toBe("1989");
  });

  it("formats week year", function() {
    /*
     * A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the
     * first and last weeks (inclusive) have the same week year value.
     * Therefore, the first and last days of a week year may have different
     * calendar year values.
     *
     * For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is
     * MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible
     * setting), then week 1 of 1998 starts on December 29, 1997, and ends on
     * January 4, 1998. The week year is 1998 for the last three days of
     * calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week
     * 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the
     * first three days of 1998 then are part of week 53 of 1997 and their week
     * year is 1997.
     */

    var d = new Date(97, 11, 28);
    expect(new sdf.SimpleDateFormat("Y").format(d)).toBe("1998");
    expect(new sdf.SimpleDateFormat("YY").format(d)).toBe("98");
    expect(new sdf.SimpleDateFormat("YYY").format(d)).toBe("1998");
    expect(new sdf.SimpleDateFormat("YYYY").format(d)).toBe("1998");
  });

  it("formats month in year (context sensitive)", function() {
    var d = new Date(17, 5, 5);
    expect(new sdf.SimpleDateFormat("M")).toBe("6");
    expect(new sdf.SimpleDateFormat("MM")).toBe("06");
    expect(new sdf.SimpleDateFormat("MMM")).toBe("Jul");
    expect(new sdf.SimpleDateFormat("MMMM")).toBe("July");
  });

  it("formats month in year (standalone form)", function() {
    /*
     * In English there is no difference in standalon and context sensitive
     * forms, however here is a thread that explains a the difference between
     * them:
     * http://stackoverflow.com/questions/32840336/standalone-form-of-month-name-in-java-date-format
     */

    var d = new Date(17, 5, 5);
    expect(new sdf.SimpleDateFormat("L")).toBe("6");
    expect(new sdf.SimpleDateFormat("LL")).toBe("06");
    expect(new sdf.SimpleDateFormat("LLL")).toBe("Jul");
    expect(new sdf.SimpleDateFormat("LLLL")).toBe("July");
  });

  it("formats week in year", function() {
    var d = new Date(97, 11, 28);
    expect(new sdf.SimpleDateFormat("w").format(d)).toBe("1");
    expect(new sdf.SimpleDateFormat("ww").format(d)).toBe("01");
  });

  it("formats week in month", function() {
    var d = new Date(97, 11, 28);
    expect(new sdf.SimpleDateFormat("W").format(d)).toBe("5");
  });

  it("formats day in year", function() {
    var d = new Date(97, 0, 3);
    expect(new sdf.SimpleDateFormat("D").format(d)).toBe("3");
    expect(new sdf.SimpleDateFormat("DD").format(d)).toBe("03");
    expect(new sdf.SimpleDateFormat("DDD").format(d)).toBe("003");
  });

  it("formats day in month", function() {
    var d = new Date(17, 5, 5);
    expect(new sdf.SimpleDateFormat("d")).toBe("5");
    expect(new sdf.SimpleDateFormat("dd")).toBe("05");
  });

  it("formats the day of week in month", function() {
    //it is the second Wendesday in May
    var d = new Date(17, 4, 10);
    expect(new sdf.SimpleDateFormat("F")).toBe("2");
  });

  it("formats the day name in week", function() {
    var d = new Date(17, 4, 10);
    expect(new sdf.SimpleDateFormat("E").format(d)).toBe("Wed");
    expect(new sdf.SimpleDateFormat("EE").format(d)).toBe("Wed");
    expect(new sdf.SimpleDateFormat("EEE").format(d)).toBe("Wed");
    expect(new sdf.SimpleDateFormat("EEEE").format(d)).toBe("Wednesday");
  });
});
<commit_msg>Fix year parameters in date construction.<commit_after>var sdf = require("../src/simpleDateFormat.js");

describe("simple date format with default locale", function () {
  /*
   * All the tests below assumes the SimpleDateFormat's default locale is
   * EN_US which means every text in English and the first day of the week
   * is Sunday.
   */

	it("formats era designator", function() {
    var d = new Date();
    expect(new sdf.SimpleDateFormat("G").format(d)).toBe("AD");
  });

  it("formats year", function() {
    var d = new Date(89, 11, 6);
    expect(new sdf.SimpleDateFormat("y").format(d)).toBe("1989");
    expect(new sdf.SimpleDateFormat("yy").format(d)).toBe("89");
    expect(new sdf.SimpleDateFormat("yyy").format(d)).toBe("1989");
    expect(new sdf.SimpleDateFormat("yyyy").format(d)).toBe("1989");
  });

  it("formats week year", function() {
    /*
     * A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the
     * first and last weeks (inclusive) have the same week year value.
     * Therefore, the first and last days of a week year may have different
     * calendar year values.
     *
     * For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is
     * MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible
     * setting), then week 1 of 1998 starts on December 29, 1997, and ends on
     * January 4, 1998. The week year is 1998 for the last three days of
     * calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week
     * 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the
     * first three days of 1998 then are part of week 53 of 1997 and their week
     * year is 1997.
     */

    var d = new Date(97, 11, 28);
    expect(new sdf.SimpleDateFormat("Y").format(d)).toBe("1998");
    expect(new sdf.SimpleDateFormat("YY").format(d)).toBe("98");
    expect(new sdf.SimpleDateFormat("YYY").format(d)).toBe("1998");
    expect(new sdf.SimpleDateFormat("YYYY").format(d)).toBe("1998");
  });

  it("formats month in year (context sensitive)", function() {
    var d = new Date(17, 5, 5);
    expect(new sdf.SimpleDateFormat("M")).toBe("6");
    expect(new sdf.SimpleDateFormat("MM")).toBe("06");
    expect(new sdf.SimpleDateFormat("MMM")).toBe("Jul");
    expect(new sdf.SimpleDateFormat("MMMM")).toBe("July");
  });

  it("formats month in year (standalone form)", function() {
    /*
     * In English there is no difference in standalon and context sensitive
     * forms, however here is a thread that explains a the difference between
     * them:
     * http://stackoverflow.com/questions/32840336/standalone-form-of-month-name-in-java-date-format
     */

    var d = new Date(17, 5, 5);
    expect(new sdf.SimpleDateFormat("L")).toBe("6");
    expect(new sdf.SimpleDateFormat("LL")).toBe("06");
    expect(new sdf.SimpleDateFormat("LLL")).toBe("Jul");
    expect(new sdf.SimpleDateFormat("LLLL")).toBe("July");
  });

  it("formats week in year", function() {
    var d = new Date(97, 11, 28);
    expect(new sdf.SimpleDateFormat("w").format(d)).toBe("1");
    expect(new sdf.SimpleDateFormat("ww").format(d)).toBe("01");
  });

  it("formats week in month", function() {
    var d = new Date(97, 11, 28);
    expect(new sdf.SimpleDateFormat("W").format(d)).toBe("5");
  });

  it("formats day in year", function() {
    var d = new Date(97, 0, 3);
    expect(new sdf.SimpleDateFormat("D").format(d)).toBe("3");
    expect(new sdf.SimpleDateFormat("DD").format(d)).toBe("03");
    expect(new sdf.SimpleDateFormat("DDD").format(d)).toBe("003");
  });

  it("formats day in month", function() {
    var d = new Date(117, 5, 5);
    expect(new sdf.SimpleDateFormat("d")).toBe("5");
    expect(new sdf.SimpleDateFormat("dd")).toBe("05");
  });

  it("formats the day of week in month", function() {
    //it is the second Wendesday in May
    var d = new Date(117, 4, 10);
    expect(new sdf.SimpleDateFormat("F")).toBe("2");
  });

  it("formats the day name in week", function() {
    var d = new Date(117, 4, 10);
    expect(new sdf.SimpleDateFormat("E").format(d)).toBe("Wed");
    expect(new sdf.SimpleDateFormat("EE").format(d)).toBe("Wed");
    expect(new sdf.SimpleDateFormat("EEE").format(d)).toBe("Wed");
    expect(new sdf.SimpleDateFormat("EEEE").format(d)).toBe("Wednesday");
  });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var chil<commit_msg>Update character<commit_after>var fs = require('fs');
var child<|endoftext|>