<commit_before>/**
 * Copyright (c) 2012, Jason Mulligan <jason.mulligan@avoidwork.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of abaaso.tabs nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL JASON MULLIGAN BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * abaaso.tabs
 *
 * UI tabs module
 *
 * @author Jason Mulligan <jason.mulligan@avoidwork.com>
 * @link http://avoidwork.com
 * @requires abaaso 1.8
 * @requires abaaso.route
 * @version 1.2
 */
(function (window) {
	"use strict";

	var tabs = (function () {
		var $ = window[abaaso.aliased],
		    create, active;

		/**
		 * Sets "active" class on tabs based on hash parsing
		 *
		 * @param  {String} arg Hash delimited by "/"
		 * @return {Array} Tabs that received "active"
		 */
		active = function (arg) {
			var hash = arg.explode("/"),
			    tabs = [];

			$("ul.tab a.active").removeClass("active");
			$(".tab").addClass("hidden");
			$(".root").removeClass("hidden");

			if (hash.first() === "#!") hash.shift();
			hash.each(function (i) {
				tabs.concat($("ul.tab a[data-hash=\"" + i + "\"]").addClass("active"));
				$(".tab[data-hash=\"" + i + "\"]").removeClass("hidden");
			});

			return tabs;
		};

		/**
		 * Add a tab widget to a target Element
		 *
		 * @param  {Object} target   Element to receive the tabs
		 * @param  {Object} children Tabs to add to this widget
		 * @param  {Object} args     Properties to set on the tabs
		 * @param  {String} route    URI route to prepend
		 * @return {Object} Element
		 */
		create = function (target, children, args, route, first) {
			var obj, hash, x, item, array, section, fn, dhash;

			args instanceof Object ? args["class"] = "tab" : args = {"class": "tab"};

			route   = typeof route === "undefined" ? "" : route;
			array   = (children instanceof Array);
			obj     = target.create("ul", args);
			section = target.create("section", {"class": "tab"});
			first   = (typeof first === "undefined" || first === true);

			switch (true) {
				case !route.isEmpty():
					dhash = route.replace(/^\/{1,1}/, "");
					obj.update({"data-hash": dhash});
					section.update({"data-hash": dhash});
					break;
				case route.isEmpty():
					obj.addClass("root");
					section.addClass("root");
					break;
			}

			for (x in children) {
				(function () {
					var i = x, h, w, y, z;

					if (!children.hasOwnProperty(i)) return;
					item = array ? children[parseInt(i)] : i;
					hash = route + "/" + item.toLowerCase();
					h    = hash.replace(/^\/{1,1}/, "");
					fn   = !array && typeof children[item] === "function" ? children[item] : function () { void(0); };

					$.route.set(h, fn);
					obj.create("li").create("a", {href: "#!" + hash, "data-hash": item.toLowerCase()}).html(item);
					switch (true) {
						case String(children[i]).isEmpty():
						case typeof children[i] === "function":
						case children[i] === null:
							section.create("section", {"class": "tab hidden", "data-hash": h});
							break;
						case typeof children[i] === "object":
							z = children[array ? parseInt(i) : i];
							section.tabs(z, null, hash, first);
							w = $("section[data-hash=\"" + h + "\"]");
							for (y in z) {
								if (!z.hasOwnProperty(y)) continue;
								if (z instanceof Array) y = z[parseInt(y)].toLowerCase();
								w.create("section", {"class": "tab hidden", "data-hash": y});
							}
							break;
					}
				})();
			}

			return target;
		};

		// Setting "active" tab class based on hash parsing
		$.on("hash", function (hash) { active(hash); }, "tabs");

		// Hooking into prototype chain
		Element.prototype.tabs = function (children, args, route, first) { return create(this, children, args, route, first); };

		// @constructor
		return {
			active : active,
			create : create
		};
	}),
	fn = function () { abaaso.module("tabs", tabs()); };

	// AMD support
	typeof define === "function" ? define("abaaso.tabs", ["abaaso", "abaaso.route"], fn) : abaaso.on("init", fn, "abaaso.tabs");
})(window);<commit_msg>Corrected nested tab generation<commit_after>/**
 * Copyright (c) 2012, Jason Mulligan <jason.mulligan@avoidwork.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of abaaso.tabs nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL JASON MULLIGAN BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * abaaso.tabs
 *
 * UI tabs module
 *
 * @author Jason Mulligan <jason.mulligan@avoidwork.com>
 * @link http://avoidwork.com
 * @requires abaaso 1.9
 * @requires abaaso.route
 * @version 1.3
 */
(function (window) {
	"use strict";

	var tabs = (function () {
		var $ = window[abaaso.aliased],
		    create, active;

		/**
		 * Sets "active" class on tabs based on hash parsing
		 *
		 * @param  {String} arg Hash delimited by "/"
		 * @return {Array} Tabs that received "active"
		 */
		active = function (arg) {
			var hash = arg.explode("/"),
			    tabs = [];

			$("ul.tab a.active").removeClass("active");
			$(".tab").addClass("hidden");
			$(".root").removeClass("hidden");

			if (hash.first() === "#!") hash.shift();
			hash.each(function (i) {
				tabs.concat($("ul.tab a[data-hash=\"" + i + "\"]").addClass("active"));
				$(".tab[data-hash=\"" + i + "\"]").removeClass("hidden");
			});

			return tabs;
		};

		/**
		 * Add a tab widget to a target Element
		 *
		 * @param  {Object} target   Element to receive the tabs
		 * @param  {Object} children Tabs to add to this widget
		 * @param  {Object} args     Properties to set on the tabs
		 * @param  {String} route    URI route to prepend
		 * @return {Object} Element
		 */
		create = function (target, children, args, route, first) {
			var obj, hash, x, item, array, section, fn, dhash;

			args instanceof Object ? args["class"] = "tab" : args = {"class": "tab"};

			route   = typeof route === "undefined" ? "" : route;
			array   = (children instanceof Array);
			obj     = target.create("ul", args);
			section = target.create("section", {"class": "tab"});
			first   = (typeof first === "undefined" || first === true);

			switch (true) {
				case !route.isEmpty():
					dhash = route.replace(/^\/{1,1}/, "");
					obj.update({"data-hash": dhash});
					section.update({"data-hash": dhash});
					break;
				case route.isEmpty():
					obj.addClass("root");
					section.addClass("root");
					break;
			}

			// Fix the iteration here
			children.each(function (i, k) {
				var h, w, y;

				item = array ? i : k;
				hash = route + "/" + item.toLowerCase();
				h    = hash.replace(/^\/{1,1}/, "");
				fn   = typeof i === "function" ? i : function () { void(0); };

				$.route.set(h, fn);
				obj.create("li").create("a", {href: "#!" + hash, "data-hash": item.toLowerCase()}).html(item);
				switch (true) {
					case String(i).isEmpty():
					case typeof i === "function":
					case i === null:
						section.create("section", {"class": "tab hidden", "data-hash": h});
						break;
					case typeof i === "object":
						section.tabs(i, null, hash, first);
						w = $("section[data-hash=\"" + h + "\"]");
						i.each(function (e, f) {
							var x = typeof e === "object" ? f : e;
							w.create("section", {"class": "tab hidden", "data-hash": x.toLowerCase()});
						});
						break;
				}
			});

			return target;
		};

		// Setting "active" tab class based on hash parsing
		$.on("hash", function (hash) { active(hash); }, "tabs");

		// Hooking into prototype chain
		Element.prototype.tabs = function (children, args, route, first) { return create(this, children, args, route, first); };

		// @constructor
		return {
			active : active,
			create : create
		};
	}),
	fn = function () { abaaso.module("tabs", tabs()); };

	// AMD support
	typeof define === "function" ? define("abaaso.tabs", ["abaaso", "abaaso.route"], fn) : abaaso.on("init", fn, "abaaso.tabs");
})(window);<|endoftext|>


<commit_before>// load any incoming URL parameters. you could just use the
// URLSearchParams object directly to manage these variables, but
// having them in a hash is a little easier sometimes.
var tmpParams = new URLSearchParams(document.location.search);
window.urlParams = {};

for(let k of tmpParams.keys() ) {
  window.urlParams[k] = tmpParams.get(k);
}

var r, g, b;

var block_width_count;
var block_height_count;

var block_width;
var block_height;

var last_x = 0;
var last_y = 0;

var img;
var tweenCount = 3;
var tween_rate = 250;

function preload() {
  var imgUrl = unescape(decodeURIComponent(window.urlParams.screenshot));
  img = loadImage(imgUrl);
}

function getFactors(integer){
  var factors = [],
      quotient = 0;

  for(var i = 1; i <= integer; i++){
    quotient = integer/i;

    if(quotient === Math.floor(quotient)){
      factors.push(i);
    }
  }
  return factors;
}

function setup() {
  r = random(255);
  g = random(255);
  b = random(255);

  // figure out the screen dimensions
  if ( typeof(window.urlParams) !== "undefined" ) {
    display_width = window.urlParams.width;
    display_height = window.urlParams.height;
  }
  else {
    display_width = screen.width;
    display_height = screen.height;
  }

  // note -- if you don't do this, width/height will be strings!
  display_width = parseInt(display_width, 10);
  display_height = parseInt(display_height, 10);

  var widths = getFactors(display_width);
  var heights = getFactors(display_height);

//  block_width_count = widths[Math.floor(widths.length/2)];
//  block_height_count = heights[Math.floor(heights.length/2)];

  block_width_count = random(widths);
  block_height_count = random(heights);

  block_width = (display_width / block_width_count);
  block_height = (display_height / block_height_count);

  // place sketch on screen
  var c = createCanvas(display_width, display_height);
  c.parent("wrapper");

  frameRate(15);
  noStroke();

  // start animations!
  for ( var i = 0; i < tweenCount; i++ ) {
    nextTween();
  }

}

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

function avg(i) {
  var sum = 0;

  i.loadPixels();
  for ( var j = 0; j < i.pixels.length; j++ ) {
    sum += i.pixels[j];
  }
  i.updatePixels();

  return sum / i.pixels.length;
}

function getBlock(bx, by) {
  var x = block_width * bx;
  var y = block_height * by;

  return img.get(x, y, block_width, block_height);
}

function nextTween() {
  var tween;

  var x = getRandomInt(0, block_width_count);
  var y = getRandomInt(0, block_height_count);

  if ( last_x >= block_width_count ) {
    last_x = 0;
    last_y = last_y + 1;

    if ( last_y >= block_height_count ) {
      last_y = 0;
    }
  }

  var b1 = getBlock(last_x, last_y);
  var b2 = getBlock(x, y);

  var start = {
    alpha: 255,
    x1: last_x * block_width,
    y1: last_y * block_height,
    x2: x * block_width,
    y2: y * block_height,
    b1: b1,
    b2: b2,
  };

  var flip = avg(b1) > avg(b2);

  if ( flip ) {
    img.copy(b1,
             0, 0,
             block_width, block_height,
             start.x2, start.y2,
             block_width, block_height);
    img.copy(b2,
             0, 0,
             block_width, block_height,
             start.x1, start.y1,
             block_width, block_height);
  }
  else {
    img.copy(b2,
             0, 0,
             block_width, block_height,
             start.x2, start.y2,
             block_width, block_height);
    img.copy(b1,
             0, 0,
             block_width, block_height,
             start.x1, start.y1,
             block_width, block_height);
  }

  var end = {
    alpha: 0
  };

  tween = new TWEEN.Tween(start);
  tween.to(end, tween_rate)
       .onUpdate(function() {
         fill(r, g, b, this.alpha);

         rect(this.x2, this.y2, block_width, block_height);
         rect(this.x1, this.y1, block_width, block_height);

       })
       .onComplete(function() {
         setTimeout(nextTween, 1);
       });
  tween.start();

  last_x = last_x + 1;
}

function draw() {
  image(img, 0, 0);
  TWEEN.update();
}

<commit_msg>Add notes, some tweaks<commit_after>// load any incoming URL parameters. you could just use the
// URLSearchParams object directly to manage these variables, but
// having them in a hash is a little easier sometimes.
var tmpParams = new URLSearchParams(document.location.search);
window.urlParams = {};

for(let k of tmpParams.keys() ) {
  window.urlParams[k] = tmpParams.get(k);
}

var r, g, b;

var block_width_count;
var block_height_count;

var block_width;
var block_height;

var last_x = 0;
var last_y = 0;

var img;
var tweenCount = 3;
var tween_rate = 250;

function preload() {
  var imgUrl = unescape(decodeURIComponent(window.urlParams.screenshot));
  img = loadImage(imgUrl);
}

function getFactors(integer){
  var factors = [],
      quotient = 0;

  for(var i = 1; i <= integer; i++){
    quotient = integer/i;

    if(quotient === Math.floor(quotient)){
      factors.push(i);
    }
  }
  return factors;
}

function setup() {
  r = random(255);
  g = random(255);
  b = random(255);

  // figure out the screen dimensions
  if ( typeof(window.urlParams) !== "undefined" ) {
    display_width = window.urlParams.width;
    display_height = window.urlParams.height;
  }
  else {
    display_width = screen.width;
    display_height = screen.height;
  }

  // note -- if you don't do this, width/height will be strings!
  display_width = parseInt(display_width, 10);
  display_height = parseInt(display_height, 10);

  var widths = getFactors(display_width);
  var heights = getFactors(display_height);

  // pick random block counts from the collection of widths/heights
  // this ensures that the math is always dividing evenly
  block_width_count = random(widths);
  block_height_count = random(heights);

  block_width = (display_width / block_width_count);
  block_height = (display_height / block_height_count);

  // place sketch on screen
  var c = createCanvas(display_width, display_height);
  c.parent("wrapper");

  frameRate(15);
  noStroke();

  // start animations!
  for ( var i = 0; i < tweenCount; i++ ) {
    nextTween();
  }

}

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

function avg(i) {
  var sum = 0;
  var count = 0;

  i.loadPixels();
  for ( var j = 0; j < i.pixels.length; j++ ) {
    // every four elements in the array is RGBA
    // let's skip the alpha value
    if ( j % 4 !== 0 ) {
      count = count + 1;
      sum += i.pixels[j];
    }
  }
  i.updatePixels();

  return sum / count;
}

function getBlock(bx, by) {
  var x = block_width * bx;
  var y = block_height * by;

  return img.get(x, y, block_width, block_height);
}

function nextTween() {
  var tween;

  var x = getRandomInt(0, block_width_count);
  var y = getRandomInt(0, block_height_count);

  if ( last_x >= block_width_count ) {
    last_x = 0;
    last_y = last_y + 1;

    if ( last_y >= block_height_count ) {
      last_y = 0;
    }
  }

  var b1 = getBlock(last_x, last_y);
  var b2 = getBlock(x, y);

  var start = {
    alpha: 255,
    x1: last_x * block_width,
    y1: last_y * block_height,
    x2: x * block_width,
    y2: y * block_height,
    b1: b1,
    b2: b2,
  };

  var flip = avg(b1) > avg(b2);

  if ( flip ) {
    img.copy(b1,
             0, 0,
             block_width, block_height,
             start.x2, start.y2,
             block_width, block_height);
    img.copy(b2,
             0, 0,
             block_width, block_height,
             start.x1, start.y1,
             block_width, block_height);
  }
  else {
    img.copy(b2,
             0, 0,
             block_width, block_height,
             start.x2, start.y2,
             block_width, block_height);
    img.copy(b1,
             0, 0,
             block_width, block_height,
             start.x1, start.y1,
             block_width, block_height);
  }

  var end = {
    alpha: 0
  };

  tween = new TWEEN.Tween(start);
  tween.to(end, tween_rate)
       .onUpdate(function() {
         fill(r, g, b, this.alpha);

         rect(this.x2, this.y2, block_width, block_height);
         rect(this.x1, this.y1, block_width, block_height);

       })
       .onComplete(function() {
         setTimeout(nextTween, 1);
       });
  tween.start();

  last_x = last_x + 1;
}

function draw() {
  image(img, 0, 0);
  TWEEN.update();
}

<|endoftext|>


<commit_before>/**
 * Asynchronously loads data sources from vellum.opts().core.dataSources
 * Currently only supports fixtures
 *
 * Format in opts:
 * dataSources: [
 *     {
 *          key: string : data source name (fixture, case, products...)
 *          endpoint: function or string (URL)
 *     }
 * ]
 *
 * The endpoint function (or URL) should return the following format:
 * [
 *      {
 *          sourceUri: string (used in the instance definition)
 *          defaultId: string (used in instance definition)
 *          intialQuery: string (used in nodeset)
 *          name: string (text in the dropdown)
 *          structure: nested dictionary of elements and attributes
 *          {
 *              element: {
 *                  structure: {
 *                      inner-element: { }
 *                  }
 *                  name: "Element" (the text used in dropdown for this element)
 *              },
 *              @attribute: { }
 *          }
 *      }
 * ]
 *
 * elements can be nested indefinitely with structure keys describing inner
 *     elements and attributes
 *
 * The result of that would be (if used in an itemset):
 *     <instance src=sourceUri id=defaultId>
 *     ...
 *     <itemset nodeset=initialQuery />
 *
 *
 * The dropdown would have options:
 *     name (would have output as above)
 *     name - Element (would change nodeset to initialQuery/element)
 */
define([
    'jquery',
    'underscore',
    'vellum/widgets',
    'tpl!vellum/templates/data_source_editor',
    'tpl!vellum/templates/select_data_source'
], function (
    $,
    _,
    widgets,
    edit_source,
    select_source
) {
    var BLANK_FIXTURE = {
        sourceUri: "",
        defaultId: "No Lookup Table Found",
        initialQuery: "",
        name: '',
        structure: {}
    };

    var vellum, dataSources, cachedDataSources;

    function init(instance) {
        vellum = instance;
        dataSources = vellum.opts().core.dataSources || [];
        cachedDataSources = {
            fixture: {}
        };
    }

    function cacheFixtures(data) {
        if (data.length === 0) {
            cachedDataSources.fixture[BLANK_FIXTURE.sourceUri] = BLANK_FIXTURE;
        }
        _.each(data, function(fixture) {
            cachedDataSources.fixture[fixture.sourceUri] = fixture;
        });
    }

    function getPossibleFixtures() {
        function generateFixtureDefinitions(structure, baseFixture) {
            return _.map(structure, function(value, key) {
                var ret = [],
                    newBaseFixture = {
                        src: baseFixture.src,
                        id: baseFixture.id,
                        query: baseFixture.query + "/" + key
                    };
                newBaseFixture.name = baseFixture.name + " - " + (value.name || key);

                if (!value.no_option) {
                    ret = [newBaseFixture];
                }
                return ret.concat(generateFixtureDefinitions(value.structure, newBaseFixture));
            });
        }

        return _.flatten(_.map(cachedDataSources.fixture, function(fixture) {
            var baseFixture = {
                src: fixture.sourceUri,
                id: fixture.defaultId,
                query: fixture.initialQuery,
                name: fixture.name || fixture.defaultId
            };

            return [baseFixture].concat(generateFixtureDefinitions(fixture.structure, baseFixture));
        }));
    }

    function generateFixtureOptions() {
        return _.map(getPossibleFixtures(), function(fixture) {
            return {
                value: JSON.stringify(_.omit(fixture, 'name')),
                text: fixture.name
            };
        });
    }

    function generateFixtureColumns(fixture) {
        function generateColumns(structure) {
            return _.map(structure, function(value, key) {
                return [key].concat(_.map(generateColumns(value.structure), function(value) {
                    return key + '/' + value;
                }));
            });
        }

        if (fixture) {
            return _.flatten(generateColumns(fixture.structure));
        }
        return [];
    }

    function autocompleteChoices(fixture_uri) {
        return generateFixtureColumns(cachedDataSources.fixture[fixture_uri]);
    }

    function getDataSources(type, callback) {
        if (!_.isEmpty(cachedDataSources[type])) {
            return;
        }

        var source = _.find(dataSources, function (src) {
            return src.key === type;
        });

        if (source) {
            if (_.isString(source.endpoint)) {
                $.ajax({
                    type: 'GET',
                    url: source.endpoint,
                    dataType: 'json',
                    success: function (data) { callback(data); },
                    // TODO error handling
                    data: {},
                    async: false
                });
            } else {
                callback(source.endpoint());
            }
        } else {
            callback([]);
        }
    }

    /**
     * Load data source editor
     *
     * @param $div - jQuery object in which editor will be created.
     * @param options - Object containing editor options:
     *      {
     *          source: {
     *              id: "<instance id>",
     *              src: "<instance src>",
     *              query: "<query expression>"
     *          },
     *          change: callback,   // called when the editor content changes
     *          done: callback      // called with no arguments on cancel
     *      }
     */
    function loadDataSourceEditor($div, options) {
        var $ui = $(edit_source()),
            $instanceId = $ui.find("[name=instance-id]"),
            $instanceSrc = $ui.find("[name=instance-src]"),
            $query = $ui.find("[name=query]");
        $div.empty().append($ui);

        if (options.source) {
            $instanceId.val(options.source.id || "");
            $instanceSrc.val(options.source.src || "");
            $query.val(options.source.query || "");
        }

        function getDataSource() {
            return {
                id: $instanceId.val(),
                src: $instanceSrc.val(),
                query: $query.val()
            };
        }

        if (options.change) {
            $instanceId.on('change keyup', function () {
                options.change(getDataSource());
            });

            $instanceSrc.on('change keyup', function () {
                options.change(getDataSource());
            });

            $query.on('change keyup', function () {
                options.change(getDataSource());
            });
        }

        var done = function (val) {
            $div.find('.fd-data-source-editor').hide();
            options.done(val);
        };

        $ui.find('.fd-data-source-save-button').click(function () {
            done(getDataSource());
        });

        $ui.find('.fd-data-source-cancel-button').click(function () {
            done();
        });
    }

    function advancedDataSourceWidget(mug, options, labelText) {
        var widget = widgets.text(mug, options),
            getUIElement = widgets.util.getUIElement,
            getUIElementWithEditButton = widgets.util.getUIElementWithEditButton,
            super_getValue = widget.getValue,
            super_setValue = widget.setValue,
            currentValue = null;

        widget.getUIElement = function () {
            var query = getUIElementWithEditButton(
                    getUIElement(widget.input, labelText),
                    function () {
                        vellum.displaySecondaryEditor({
                            source: local_getValue(),
                            headerText: labelText,
                            loadEditor: loadDataSourceEditor,
                            done: function (source) {
                                if (!_.isUndefined(source)) {
                                    local_setValue(source);
                                    widget.handleChange();
                                }
                            }
                        });
                    }
                );
            return $("

").append(query);
        };

        function local_getValue() {
            currentValue.query = super_getValue();
            return currentValue;
        }

        function local_setValue(val) {
            currentValue = val;
            super_setValue(val.query || "");
        }

        widget.getValue = local_getValue;
        widget.setValue = local_setValue;

        return widget;
    }

    /**
     * @param options - Optionally pass in:
     *      hasAdvancedEditor - enable advanced editor if true
     *      getSource(mug) - Initializes the source for the advanced editor
     *      setSource(source, mug) - Saves the source from the advanced editor
     */
    function fixtureWidget(mug, options, labelText) {
        getDataSources('fixture', cacheFixtures);

        function local_getValue() {
            currentValue = JSON.parse(super_getValue());
            return currentValue;
        }

        function local_setValue(val) {
            currentValue = val;
            var jsonVal = val ? JSON.stringify(val) : '',
                val2 = widget.equivalentOption(jsonVal);
            if (!val2 && !_.isEqual(val, {id: "", src: "", query: undefined})) {
                widget.addOption(jsonVal, customXML);
            }

            super_setValue(jsonVal);
        }

        var widget = widgets.dropdown(mug, options),
            super_getValue = widget.getValue,
            super_setValue = widget.setValue,
            currentValue = null,
            customXML = "Lookup table was not found in the project",
            getSource = options.getSource ? options.getSource : local_getValue,
            setSource = options.setSource ? options.setSource : local_setValue;

        if (options.hasAdvancedEditor) {
            widget.getUIElement = function () {
                var query = widgets.util.getUIElementWithEditButton(
                        widgets.util.getUIElement(widget.input, labelText),
                        function () {
                            vellum.displaySecondaryEditor({
                                source: getSource(mug),
                                headerText: labelText,
                                loadEditor: loadDataSourceEditor,
                                done: function (source) {
                                    if (!_.isUndefined(source)) {
                                        setSource(source, mug);
                                        widget.handleChange();
                                    }
                                }
                            });
                        }
                    );
                query.find(".fd-edit-button").text("...");
                query.find('.controls').css('margin-right', '48px');
                return $("

").append(query);
            };
        }

        widget.addOptions(generateFixtureOptions());

        widget.getValue = local_getValue;
        widget.setValue = local_setValue;

        return widget;
    }

    return {
        init: init,
        advancedDataSourceWidget: advancedDataSourceWidget,
        fixtureWidget: fixtureWidget,
        autocompleteChoices:autocompleteChoices,
        getPossibleFixtures: getPossibleFixtures
    };
});
<commit_msg>Async/generic data source loading<commit_after>/**
 * Asynchronously loads data sources from vellum.opts().core.dataSources
 * Currently only supports fixtures
 *
 * Format in opts:
 * dataSources: [
 *     {
 *          key: string : data source name (fixture, case, products...)
 *          endpoint: function or string (URL)
 *     }
 * ]
 *
 * The endpoint function (or URL) should return the following format:
 * [
 *      {
 *          sourceUri: string (used in the instance definition)
 *          defaultId: string (used in instance definition)
 *          intialQuery: string (used in nodeset)
 *          name: string (text in the dropdown)
 *          structure: nested dictionary of elements and attributes
 *          {
 *              element: {
 *                  structure: {
 *                      inner-element: { }
 *                  }
 *                  name: "Element" (the text used in dropdown for this element)
 *              },
 *              @attribute: { }
 *          }
 *      }
 * ]
 *
 * elements can be nested indefinitely with structure keys describing inner
 *     elements and attributes
 *
 * The result of that would be (if used in an itemset):
 *     <instance src=sourceUri id=defaultId>
 *     ...
 *     <itemset nodeset=initialQuery />
 *
 *
 * The dropdown would have options:
 *     name (would have output as above)
 *     name - Element (would change nodeset to initialQuery/element)
 */
define([
    'jquery',
    'underscore',
    'vellum/widgets',
    'tpl!vellum/templates/data_source_editor',
    'tpl!vellum/templates/select_data_source'
], function (
    $,
    _,
    widgets,
    edit_source,
    select_source
) {
    var BLANKS = {
        fixture: {
            sourceUri: "",
            defaultId: "No Lookup Table Found",
            initialQuery: "",
            name: '',
            structure: {}
        }
    };

    var vellum, dataSources, dataCache = {};

    function init(instance) {
        vellum = instance;
        dataSources = vellum.opts().core.dataSources || [];
    }

    function cacheData(data, type) {
        if (data.length === 0) {
            var blank = BLANKS[type] || {};
            dataCache[type][blank.sourceUri || ""] = blank;
        }
        _.each(data, function(item) {
            dataCache[type][item.sourceUri] = item;
        });
    }

    function getPossibleFixtures() {
        function generateFixtureDefinitions(structure, baseFixture) {
            return _.map(structure, function(value, key) {
                var ret = [],
                    newBaseFixture = {
                        src: baseFixture.src,
                        id: baseFixture.id,
                        query: baseFixture.query + "/" + key
                    };
                newBaseFixture.name = baseFixture.name + " - " + (value.name || key);

                if (!value.no_option) {
                    ret = [newBaseFixture];
                }
                return ret.concat(generateFixtureDefinitions(value.structure, newBaseFixture));
            });
        }

        return _.flatten(_.map(dataCache.fixture, function(fixture) {
            var baseFixture = {
                src: fixture.sourceUri,
                id: fixture.defaultId,
                query: fixture.initialQuery,
                name: fixture.name || fixture.defaultId
            };

            return [baseFixture].concat(generateFixtureDefinitions(fixture.structure, baseFixture));
        }));
    }

    function generateFixtureOptions() {
        return _.map(getPossibleFixtures(), function(fixture) {
            return {
                value: JSON.stringify(_.omit(fixture, 'name')),
                text: fixture.name
            };
        });
    }

    function generateFixtureColumns(fixture) {
        function generateColumns(structure) {
            return _.map(structure, function(value, key) {
                return [key].concat(_.map(generateColumns(value.structure), function(value) {
                    return key + '/' + value;
                }));
            });
        }

        if (fixture) {
            return _.flatten(generateColumns(fixture.structure));
        }
        return [];
    }

    function autocompleteChoices(fixture_uri) {
        return generateFixtureColumns(dataCache.fixture[fixture_uri]);
    }

    function getDataSources(type, callback) {
        if (!_.isEmpty(dataCache[type])) {
            return;
        }

        var source = _.find(dataSources, function (src) {
            return src.key === type;
        });

        if (source) {
            if (_.isString(source.endpoint)) {
                $.ajax({
                    type: 'GET',
                    url: source.endpoint,
                    dataType: 'json',
                    success: function (data) { callback(data, type); },
                    // TODO error handling
                    data: {},
                    async: false
                });
            } else {
                callback(source.endpoint());
            }
        } else {
            callback([]);
        }
    }

    /**
     * Load data source editor
     *
     * @param $div - jQuery object in which editor will be created.
     * @param options - Object containing editor options:
     *      {
     *          source: {
     *              id: "<instance id>",
     *              src: "<instance src>",
     *              query: "<query expression>"
     *          },
     *          change: callback,   // called when the editor content changes
     *          done: callback      // called with no arguments on cancel
     *      }
     */
    function loadDataSourceEditor($div, options) {
        var $ui = $(edit_source()),
            $instanceId = $ui.find("[name=instance-id]"),
            $instanceSrc = $ui.find("[name=instance-src]"),
            $query = $ui.find("[name=query]");
        $div.empty().append($ui);

        if (options.source) {
            $instanceId.val(options.source.id || "");
            $instanceSrc.val(options.source.src || "");
            $query.val(options.source.query || "");
        }

        function getDataSource() {
            return {
                id: $instanceId.val(),
                src: $instanceSrc.val(),
                query: $query.val()
            };
        }

        if (options.change) {
            $instanceId.on('change keyup', function () {
                options.change(getDataSource());
            });

            $instanceSrc.on('change keyup', function () {
                options.change(getDataSource());
            });

            $query.on('change keyup', function () {
                options.change(getDataSource());
            });
        }

        var done = function (val) {
            $div.find('.fd-data-source-editor').hide();
            options.done(val);
        };

        $ui.find('.fd-data-source-save-button').click(function () {
            done(getDataSource());
        });

        $ui.find('.fd-data-source-cancel-button').click(function () {
            done();
        });
    }

    function advancedDataSourceWidget(mug, options, labelText) {
        var widget = widgets.text(mug, options),
            getUIElement = widgets.util.getUIElement,
            getUIElementWithEditButton = widgets.util.getUIElementWithEditButton,
            super_getValue = widget.getValue,
            super_setValue = widget.setValue,
            currentValue = null;

        widget.getUIElement = function () {
            var query = getUIElementWithEditButton(
                    getUIElement(widget.input, labelText),
                    function () {
                        vellum.displaySecondaryEditor({
                            source: local_getValue(),
                            headerText: labelText,
                            loadEditor: loadDataSourceEditor,
                            done: function (source) {
                                if (!_.isUndefined(source)) {
                                    local_setValue(source);
                                    widget.handleChange();
                                }
                            }
                        });
                    }
                );
            return $("

").append(query);
        };

        function local_getValue() {
            currentValue.query = super_getValue();
            return currentValue;
        }

        function local_setValue(val) {
            currentValue = val;
            super_setValue(val.query || "");
        }

        widget.getValue = local_getValue;
        widget.setValue = local_setValue;

        return widget;
    }

    /**
     * @param options - Optionally pass in:
     *      hasAdvancedEditor - enable advanced editor if true
     *      getSource(mug) - Initializes the source for the advanced editor
     *      setSource(source, mug) - Saves the source from the advanced editor
     */
    function fixtureWidget(mug, options, labelText) {
        getDataSources('fixture', cacheData);

        function local_getValue() {
            currentValue = JSON.parse(super_getValue());
            return currentValue;
        }

        function local_setValue(val) {
            currentValue = val;
            var jsonVal = val ? JSON.stringify(val) : '',
                val2 = widget.equivalentOption(jsonVal);
            if (!val2 && !_.isEqual(val, {id: "", src: "", query: undefined})) {
                widget.addOption(jsonVal, customXML);
            }

            super_setValue(jsonVal);
        }

        var widget = widgets.dropdown(mug, options),
            super_getValue = widget.getValue,
            super_setValue = widget.setValue,
            currentValue = null,
            customXML = "Lookup table was not found in the project",
            getSource = options.getSource ? options.getSource : local_getValue,
            setSource = options.setSource ? options.setSource : local_setValue;

        if (options.hasAdvancedEditor) {
            widget.getUIElement = function () {
                var query = widgets.util.getUIElementWithEditButton(
                        widgets.util.getUIElement(widget.input, labelText),
                        function () {
                            vellum.displaySecondaryEditor({
                                source: getSource(mug),
                                headerText: labelText,
                                loadEditor: loadDataSourceEditor,
                                done: function (source) {
                                    if (!_.isUndefined(source)) {
                                        setSource(source, mug);
                                        widget.handleChange();
                                    }
                                }
                            });
                        }
                    );
                query.find(".fd-edit-button").text("...");
                query.find('.controls').css('margin-right', '48px');
                return $("

").append(query);
            };
        }

        widget.addOptions(generateFixtureOptions());

        widget.getValue = local_getValue;
        widget.setValue = local_setValue;

        return widget;
    }

    return {
        init: init,
        advancedDataSourceWidget: advancedDataSourceWidget,
        fixtureWidget: fixtureWidget,
        autocompleteChoices: autocompleteChoices,
        getPossibleFixtures: getPossibleFixtures
    };
});
<|endoftext|>


<commit_before>var J = J || {};
//-----------------------------------
//
// J.Viewer - test webGL overlay atop OpenSeaDragon
//
//-----------------------------------

J.Viewer = function() {
}

J.Viewer.prototype.init = function() {

    // Open a seaDragon with two layers
    var openSD = OpenSeadragon({
        tileSources: '../../images/babel/babel.dzi',
        id: this.container || 'viaWebGL',
        prefixUrl: '../../images/icons/'
    });

    // Make a link to webGL
    var seaGL = new SeaDragonGL();
    seaGL.vShader = '../../shaders/vertex/square.glsl';
    seaGL.fShader = '../../shaders/fragment/none.glsl';
    seaGL.tileSize = 512;

    var load = function(callback, e) {
        // via webGL
        callback(e);
    }

    var draw = function(callback, e) {

        if (e.tile.loaded !==1) {
            e.tile.loaded = 1;
            callback(e);
        }
    }

    //seaGL['tile-drawing'] = draw;
    seaGL['tile-loaded'] = load;
    seaGL.init(openSD);
}<commit_msg>sobel<commit_after>var J = J || {};
//-----------------------------------
//
// J.Viewer - test webGL overlay atop OpenSeaDragon
//
//-----------------------------------

J.Viewer = function() {
}

J.Viewer.prototype.init = function() {

    // Open a seaDragon with two layers
    var openSD = OpenSeadragon({
        tileSources: '../../images/babel/babel.dzi',
        id: this.container || 'viaWebGL',
        prefixUrl: '../../images/icons/'
    });

    // Make a link to webGL
    var seaGL = new SeaDragonGL();
    seaGL.vShader = '../../shaders/vertex/square.glsl';
    seaGL.fShader = '../../shaders/fragment/sobel.glsl';
    seaGL.tileSize = 512;

    var load = function(callback, e) {
        // via webGL
        callback(e);
    }

    var draw = function(callback, e) {

        if (e.tile.loaded !==1) {
            e.tile.loaded = 1;
            callback(e);
        }
    }

    //seaGL['tile-drawing'] = draw;
    seaGL['tile-loaded'] = load;
    seaGL.init(openSD);
}<|endoftext|>


<commit_before>define([
    'jquery',
    'underscore',
    'vellum/widgets',
    'tpl!vellum/templates/data_source_editor',
    'tpl!vellum/templates/select_data_source'
], function (
    $,
    _,
    widgets,
    edit_source,
    select_source
) {
    var vellum, dataSources, cachedDataSources;

    function init(instance) {
        vellum = instance;
        dataSources = vellum.opts().core.dataSources || [];
        cachedDataSources = {
            fixtures: {}
        };
        getDataSources('fixture', cacheFixtures);
    }

    function cacheFixtures(data) {
        _.map(data, function(fixture) {
            cachedDataSources.fixtures[fixture.sourceUri] = fixture;
        });
    }

    function getPossibleFixtures() {
        function generateFixtureDefinitions(structure, baseFixture) {
            return _.map(structure, function(value, key) {
                var ret = [],
                    newBaseFixture = {
                        src: baseFixture.src,
                        id: baseFixture.id,
                        query: baseFixture.query + "/" + key
                    };
                newBaseFixture.name = baseFixture.name + " - " + (value.name || key);

                if (!value.no_option) {
                    ret = [newBaseFixture];
                }
                return ret.concat(generateFixtureDefinitions(value.structure, newBaseFixture));
            });
        }

        return _.flatten(_.map(cachedDataSources.fixtures, function(fixture) {
            var baseFixture = {
                src: fixture.sourceUri,
                id: fixture.defaultId,
                query: fixture.initialQuery,
                name: fixture.name || fixture.defaultId
            };

            return [baseFixture].concat(generateFixtureDefinitions(fixture.structure, baseFixture));
        }));
    }

    function generateFixtureOptions() {
        return _.map(getPossibleFixtures(), function(fixture) {
            return {
                value: JSON.stringify(_.omit(fixture, 'name')),
                text: fixture.name
            };
        });
    }

    function generateFixtureColumns(fixture) {
        function generateColumns(structure) {
            return _.map(structure, function(value, key) {
                return [key].concat(_.map(generateColumns(value.structure), function(value) {
                    return key + '/' + value;
                }));
            });
        }

        if (fixture) {
            return _.flatten(generateColumns(fixture.structure));
        }
        return "";
    }

    function autocompleteChoices(fixture_uri) {
        return generateFixtureColumns(cachedDataSources.fixtures[fixture_uri]);
    }

    function getDataSources(type, callback) {
        var source = _.find(dataSources, function (src) {
            return src.key === type;
        });

        if (source) {
            if (_.isString(source.endpoint)) {
                $.ajax({
                    type: 'GET',
                    url: source.endpoint,
                    dataType: 'json',
                    success: function (data) { callback(data); },
                    // TODO error handling
                    data: {}
                });
            } else {
                callback(source.endpoint());
            }
        } else {
            callback([]);
        }
    }

    /**
     * Load data source editor
     *
     * @param $div - jQuery object in which editor will be created.
     * @param options - Object containing editor options:
     *      {
     *          source: {
     *              id: "<instance id>",
     *              src: "<instance src>",
     *              query: "<query expression>"
     *          },
     *          change: callback,   // called when the editor content changes
     *          done: callback      // called with no arguments on cancel
     *      }
     */
    function loadDataSourceEditor($div, options) {
        var $ui = $(edit_source()),
            $instanceId = $ui.find("[name=instance-id]"),
            $instanceSrc = $ui.find("[name=instance-src]"),
            $query = $ui.find("[name=query]");
        $div.empty().append($ui);

        if (options.source) {
            $instanceId.val(options.source.id || "");
            $instanceSrc.val(options.source.src || "");
            $query.val(options.source.query || "");
        }

        function getDataSource() {
            return {
                id: $instanceId.val(),
                src: $instanceSrc.val(),
                query: $query.val()
            };
        }

        if (options.change) {
            $instanceId.on('change keyup', function () {
                options.change(getDataSource());
            });

            $instanceSrc.on('change keyup', function () {
                options.change(getDataSource());
            });

            $query.on('change keyup', function () {
                options.change(getDataSource());
            });
        }

        var done = function (val) {
            $div.find('.fd-data-source-editor').hide();
            options.done(val);
        };

        $ui.find('.fd-data-source-save-button').click(function () {
            done(getDataSource());
        });

        $ui.find('.fd-data-source-cancel-button').click(function () {
            done();
        });
    }

    function dataSourceWidget(mug, options, labelText) {
        var widget = widgets.text(mug, options),
            getUIElement = widgets.util.getUIElement,
            getUIElementWithEditButton = widgets.util.getUIElementWithEditButton,
            super_getValue = widget.getValue,
            super_setValue = widget.setValue,
            currentValue = null;

        widget.getUIElement = function () {
            var query = getUIElementWithEditButton(
                    getUIElement(widget.input, labelText),
                    function () {
                        vellum.displaySecondaryEditor({
                            source: local_getValue(),
                            headerText: labelText,
                            loadEditor: loadDataSourceEditor,
                            done: function (source) {
                                if (!_.isUndefined(source)) {
                                    local_setValue(source);
                                    widget.handleChange();
                                }
                            }
                        });
                    }
                );
            return $("

").append(query);
        };

        function local_getValue() {
            currentValue.query = super_getValue();
            return currentValue;
        }

        function local_setValue(val) {
            currentValue = val;
            super_setValue(val.query || "");
        }

        widget.getValue = local_getValue;
        widget.setValue = local_setValue;

        return widget;
    }

    function fixtureWidget(mug, options, labelText) {
        var widget = widgets.dropdown(mug, options),
            getUIElement = widgets.util.getUIElement,
            getUIElementWithEditButton = widgets.util.getUIElementWithEditButton,
            super_getValue = widget.getValue,
            super_setValue = widget.setValue,
            currentValue = null;

        widget.addOptions(generateFixtureOptions());

        widget.getUIElement = function () {
            var query = getUIElementWithEditButton(
                    getUIElement(widget.input, labelText),
                    function () {
                        vellum.displaySecondaryEditor({
                            source: local_getValue(),
                            headerText: labelText,
                            loadEditor: loadDataSourceEditor,
                            done: function (source) {
                                if (!_.isUndefined(source)) {
                                    local_setValue(source);
                                    widget.handleChange();
                                }
                            }
                        });
                    },
                    false
                );
            return $("

").append(query);
        };

        function local_getValue() {
            currentValue = JSON.parse(super_getValue());
            return currentValue;
        }

        function local_setValue(val) {
            currentValue = val;
            super_setValue(val ? JSON.stringify(val) : '', val.query);
        }

        widget.getValue = local_getValue;
        widget.setValue = local_setValue;

        return widget;
    }

    return {
        init: init,
        dataSourceWidget: dataSourceWidget,
        fixtureWidget: fixtureWidget,
        autocompleteChoices:autocompleteChoices
    };
});
<commit_msg>Fetch fixtures on demand<commit_after>define([
    'jquery',
    'underscore',
    'vellum/widgets',
    'tpl!vellum/templates/data_source_editor',
    'tpl!vellum/templates/select_data_source'
], function (
    $,
    _,
    widgets,
    edit_source,
    select_source
) {
    var vellum, dataSources, cachedDataSources;

    function init(instance) {
        vellum = instance;
        dataSources = vellum.opts().core.dataSources || [];
        cachedDataSources = {
            fixture: {}
        };
    }

    function cacheFixtures(data) {
        _.map(data, function(fixture) {
            cachedDataSources.fixture[fixture.sourceUri] = fixture;
        });
    }

    function getPossibleFixtures() {
        function generateFixtureDefinitions(structure, baseFixture) {
            return _.map(structure, function(value, key) {
                var ret = [],
                    newBaseFixture = {
                        src: baseFixture.src,
                        id: baseFixture.id,
                        query: baseFixture.query + "/" + key
                    };
                newBaseFixture.name = baseFixture.name + " - " + (value.name || key);

                if (!value.no_option) {
                    ret = [newBaseFixture];
                }
                return ret.concat(generateFixtureDefinitions(value.structure, newBaseFixture));
            });
        }

        return _.flatten(_.map(cachedDataSources.fixture, function(fixture) {
            var baseFixture = {
                src: fixture.sourceUri,
                id: fixture.defaultId,
                query: fixture.initialQuery,
                name: fixture.name || fixture.defaultId
            };

            return [baseFixture].concat(generateFixtureDefinitions(fixture.structure, baseFixture));
        }));
    }

    function generateFixtureOptions() {
        return _.map(getPossibleFixtures(), function(fixture) {
            return {
                value: JSON.stringify(_.omit(fixture, 'name')),
                text: fixture.name
            };
        });
    }

    function generateFixtureColumns(fixture) {
        function generateColumns(structure) {
            return _.map(structure, function(value, key) {
                return [key].concat(_.map(generateColumns(value.structure), function(value) {
                    return key + '/' + value;
                }));
            });
        }

        if (fixture) {
            return _.flatten(generateColumns(fixture.structure));
        }
        return "";
    }

    function autocompleteChoices(fixture_uri) {
        return generateFixtureColumns(cachedDataSources.fixture[fixture_uri]);
    }

    function getDataSources(type, callback) {
        if (!_.isEmpty(cachedDataSources[type])) {
            return;
        }

        var source = _.find(dataSources, function (src) {
            return src.key === type;
        });

        if (source) {
            if (_.isString(source.endpoint)) {
                $.ajax({
                    type: 'GET',
                    url: source.endpoint,
                    dataType: 'json',
                    success: function (data) { callback(data); },
                    // TODO error handling
                    data: {},
                    async: false
                });
            } else {
                callback(source.endpoint());
            }
        } else {
            callback([]);
        }
    }

    /**
     * Load data source editor
     *
     * @param $div - jQuery object in which editor will be created.
     * @param options - Object containing editor options:
     *      {
     *          source: {
     *              id: "<instance id>",
     *              src: "<instance src>",
     *              query: "<query expression>"
     *          },
     *          change: callback,   // called when the editor content changes
     *          done: callback      // called with no arguments on cancel
     *      }
     */
    function loadDataSourceEditor($div, options) {
        var $ui = $(edit_source()),
            $instanceId = $ui.find("[name=instance-id]"),
            $instanceSrc = $ui.find("[name=instance-src]"),
            $query = $ui.find("[name=query]");
        $div.empty().append($ui);

        if (options.source) {
            $instanceId.val(options.source.id || "");
            $instanceSrc.val(options.source.src || "");
            $query.val(options.source.query || "");
        }

        function getDataSource() {
            return {
                id: $instanceId.val(),
                src: $instanceSrc.val(),
                query: $query.val()
            };
        }

        if (options.change) {
            $instanceId.on('change keyup', function () {
                options.change(getDataSource());
            });

            $instanceSrc.on('change keyup', function () {
                options.change(getDataSource());
            });

            $query.on('change keyup', function () {
                options.change(getDataSource());
            });
        }

        var done = function (val) {
            $div.find('.fd-data-source-editor').hide();
            options.done(val);
        };

        $ui.find('.fd-data-source-save-button').click(function () {
            done(getDataSource());
        });

        $ui.find('.fd-data-source-cancel-button').click(function () {
            done();
        });
    }

    function dataSourceWidget(mug, options, labelText) {
        var widget = widgets.text(mug, options),
            getUIElement = widgets.util.getUIElement,
            getUIElementWithEditButton = widgets.util.getUIElementWithEditButton,
            super_getValue = widget.getValue,
            super_setValue = widget.setValue,
            currentValue = null;

        widget.getUIElement = function () {
            var query = getUIElementWithEditButton(
                    getUIElement(widget.input, labelText),
                    function () {
                        vellum.displaySecondaryEditor({
                            source: local_getValue(),
                            headerText: labelText,
                            loadEditor: loadDataSourceEditor,
                            done: function (source) {
                                if (!_.isUndefined(source)) {
                                    local_setValue(source);
                                    widget.handleChange();
                                }
                            }
                        });
                    }
                );
            return $("

").append(query);
        };

        function local_getValue() {
            currentValue.query = super_getValue();
            return currentValue;
        }

        function local_setValue(val) {
            currentValue = val;
            super_setValue(val.query || "");
        }

        widget.getValue = local_getValue;
        widget.setValue = local_setValue;

        return widget;
    }

    function fixtureWidget(mug, options, labelText) {
        getDataSources('fixture', cacheFixtures);

        var widget = widgets.dropdown(mug, options),
            getUIElement = widgets.util.getUIElement,
            getUIElementWithEditButton = widgets.util.getUIElementWithEditButton,
            super_getValue = widget.getValue,
            super_setValue = widget.setValue,
            currentValue = null;

        widget.addOptions(generateFixtureOptions());

        widget.getUIElement = function () {
            var query = getUIElementWithEditButton(
                    getUIElement(widget.input, labelText),
                    function () {
                        vellum.displaySecondaryEditor({
                            source: local_getValue(),
                            headerText: labelText,
                            loadEditor: loadDataSourceEditor,
                            done: function (source) {
                                if (!_.isUndefined(source)) {
                                    local_setValue(source);
                                    widget.handleChange();
                                }
                            }
                        });
                    },
                    false
                );
            return $("

").append(query);
        };

        function local_getValue() {
            currentValue = JSON.parse(super_getValue());
            return currentValue;
        }

        function local_setValue(val) {
            currentValue = val;
            super_setValue(val ? JSON.stringify(val) : '', val.query);
        }

        widget.getValue = local_getValue;
        widget.setValue = local_setValue;

        return widget;
    }

    return {
        init: init,
        dataSourceWidget: dataSourceWidget,
        fixtureWidget: fixtureWidget,
        autocompleteChoices:autocompleteChoices
    };
});
<|endoftext|>


<commit_before>var code_window = null;
function pp_model() {
  function spaces(number) {
    var sp = "";
    for (var i = 0; i < number; i++) {
      sp = sp + " ";
    }
    return sp;
  }
  function recurse_obj(obj, depth) {
    var ret = spaces(depth) + "{";

    depth += 2;
    var number_of_keys = 0;
    for (key in obj) { number_of_keys++; }

    var i = 0;
    for (key in obj) {
      ret += "\n" + spaces(depth) + key + " : ";
      ret += (typeof obj[key] == "object") ?
        recurse_obj(obj[key], depth) : obj[key];
      i++; if (i < number_of_keys) { ret += ","; }
    }

    depth -= 2
    ret += "\n" + spaces(depth) + "}";
    return ret;
  }

  return recurse_obj(todo_model, 0);
}
function spawn_code_window() {
  var content = $("#code").html();
  code_window = open('', 'Mmvp.js Source', 'height=720,width=720');
  $("body", code_window.document).html("");
  code_window.document.write(content);
  $("body", code_window.document).attr("id", "code-window");
  $("h3", code_window.document).on("click", function(ev) {
    if ($(ev.target).text() == "Todo.js") {
      activate_code_window("todo");
    } else {
      activate_code_window("mmvp");
    }
  });
}
function activate_code_window(mmvp_or_todo) {
  spawn_code_window();
  if (mmvp_or_todo === 'todo') {
    $("body", code_window.document).addClass("todo").removeClass("mmvp");
  } else if (mmvp_or_todo === 'mmvp') {
    $("body", code_window.document).addClass("mmvp").removeClass("todo");
  }
}
$(function() {
  (function code_window_callbacks() {
    $("a#todo-src").on("click", function() { activate_code_window('todo'); return false; });
    $("a#mmvp-src").on("click", function() { activate_code_window('mmvp'); return false; });
  })();
  (function syntax_highlighter() { SyntaxHighlighter.all(); })();
  (function tab_switcher_callbacks() {
    $("section#demo h3").on("click", function(ev) {
      if (!$(ev.target).hasClass('active')) {

        $("section#demo h3.active").removeClass('active');
        $("section#demo section#switcher section.active").removeClass('active');

        var new_tab = $(ev.target).attr('class');
        if (new_tab == 'model') {
          $("section.model").html("
" + pp_model() + "
");
          SyntaxHighlighter.highlight();
        }

        $("section#demo h3." + new_tab).addClass('active');
        $("section#demo section#switcher section." + new_tab).addClass('active');
      }
    });
  })();
});
<commit_msg>autofocus input on demopage on load<commit_after>var code_window = null;
function pp_model() {
  function spaces(number) {
    var sp = "";
    for (var i = 0; i < number; i++) {
      sp = sp + " ";
    }
    return sp;
  }
  function recurse_obj(obj, depth) {
    var ret = spaces(depth) + "{";

    depth += 2;
    var number_of_keys = 0;
    for (key in obj) { number_of_keys++; }

    var i = 0;
    for (key in obj) {
      ret += "\n" + spaces(depth) + key + " : ";
      ret += (typeof obj[key] == "object") ?
        recurse_obj(obj[key], depth) : obj[key];
      i++; if (i < number_of_keys) { ret += ","; }
    }

    depth -= 2
    ret += "\n" + spaces(depth) + "}";
    return ret;
  }

  return recurse_obj(todo_model, 0);
}
function spawn_code_window() {
  var content = $("#code").html();
  code_window = open('', 'Mmvp.js Source', 'height=720,width=720');
  $("body", code_window.document).html("");
  code_window.document.write(content);
  $("body", code_window.document).attr("id", "code-window");
  $("h3", code_window.document).on("click", function(ev) {
    if ($(ev.target).text() == "Todo.js") {
      activate_code_window("todo");
    } else {
      activate_code_window("mmvp");
    }
  });
}
function activate_code_window(mmvp_or_todo) {
  spawn_code_window();
  if (mmvp_or_todo === 'todo') {
    $("body", code_window.document).addClass("todo").removeClass("mmvp");
  } else if (mmvp_or_todo === 'mmvp') {
    $("body", code_window.document).addClass("mmvp").removeClass("todo");
  }
}
$(function() {
  $("input[type='text']").focus();
  $(document).on("click", function() { $("input[type='text']").focus(); });
  (function code_window_callbacks() {
    $("a#todo-src").on("click", function() { activate_code_window('todo'); return false; });
    $("a#mmvp-src").on("click", function() { activate_code_window('mmvp'); return false; });
  })();
  (function syntax_highlighter() { SyntaxHighlighter.all(); })();
  (function tab_switcher_callbacks() {
    $("section#demo h3").on("click", function(ev) {
      if (!$(ev.target).hasClass('active')) {

        $("section#demo h3.active").removeClass('active');
        $("section#demo section#switcher section.active").removeClass('active');

        var new_tab = $(ev.target).attr('class');
        if (new_tab == 'model') {
          $("section.model").html("
" + pp_model() + "
");
          SyntaxHighlighter.highlight();
        }

        $("section#demo h3." + new_tab).addClass('active');
        $("section#demo section#switcher section." + new_tab).addClass('active');
      }
    });
  })();
});
<|endoftext|>


<commit_before>var Comet = {
    props: {
        speed: 1.7,
        x: 0,
        y: 0,
        origX: 0,
        origY: 0,
        radius: 5,
        rotation: 200,
        startTime: null,
        color: '#FFFFFF',
        particleAge: 200,
        particleSize: 3
    },
    particles: [],
    draw: function (canvas, context) {
        if (this.props.startTime == null) {
            this.props.startTime = new Date().getTime();
        }

        this.reposition(canvas);

        this.drawSquare(context);

        this.drawParticles(context);

        for (var i = 0; i < 10; i++) {
            this.particles.push({
                x: this.props.x + this.props.radius / 2 - this.props.particleSize / 2,
                y: this.props.y + this.props.radius / 2 - this.props.particleSize / 2,
                age: this.props.particleAge,
            });

        }
    },
    reposition: function (canvas) {
        var time = (new Date().getTime() - this.props.startTime) / 1000 * this.props.speed;
        this.props.x = this.props.origX + this.props.rotation * Math.sin(time);
        this.props.y = this.props.origY + this.props.rotation * Math.cos(time);
        if (this.props.x >= canvas.width) {
            this.props.x = 0;
        }
        //this.props.y = this.props.y + Math.sin(this.props.startTime)*10;

    },
    drawSquare: function (context) {
        context.beginPath();
        context.rect(this.props.x, this.props.y, this.props.radius, this.props.radius);
        context.fillStyle = this.props.color;
        context.fill();
    },
    drawParticles: function (context) {
        var i = this.particles.length - 1;
        while (i >= 0) {
            if (this.particles[i].age > 0) {
                this.drawSingleParticle(context, this.particles[i]);
            }
            else {
                this.particles.splice(i, 1);
            }
            i -= 1;
        }
    },
    drawSingleParticle: function (context, particle) {
        context.beginPath();
        context.rect(particle.x, particle.y, this.props.particleSize, this.props.particleSize);
        context.fillStyle = 'rgba(255,' + Math.floor((particle.age / this.props.particleAge) * 255) + ',0,'+particle.age / this.props.particleAge+')';
        context.fill();
        particle.age -= 1;
        particle.y += (Math.random() - 0.5) * 2;
        particle.x += (Math.random() - 0.5) * 2;
    },
    hex2rgb: function (hex) {
        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }
}<commit_msg>changed particle age<commit_after>var Comet = {
    props: {
        speed: 1.7,
        x: 0,
        y: 0,
        origX: 0,
        origY: 0,
        radius: 5,
        rotation: 200,
        startTime: null,
        color: '#FFFFFF',
        particleAge: 100,
        particleSize: 3
    },
    particles: [],
    draw: function (canvas, context) {
        if (this.props.startTime == null) {
            this.props.startTime = new Date().getTime();
        }

        this.reposition(canvas);

        this.drawSquare(context);

        this.drawParticles(context);

        for (var i = 0; i < 10; i++) {
            this.particles.push({
                x: this.props.x + this.props.radius / 2 - this.props.particleSize / 2,
                y: this.props.y + this.props.radius / 2 - this.props.particleSize / 2,
                age: this.props.particleAge,
            });

        }
    },
    reposition: function (canvas) {
        var time = (new Date().getTime() - this.props.startTime) / 1000 * this.props.speed;
        this.props.x = this.props.origX + this.props.rotation * Math.sin(time);
        this.props.y = this.props.origY + this.props.rotation * Math.cos(time);
        if (this.props.x >= canvas.width) {
            this.props.x = 0;
        }
        //this.props.y = this.props.y + Math.sin(this.props.startTime)*10;

    },
    drawSquare: function (context) {
        context.beginPath();
        context.rect(this.props.x, this.props.y, this.props.radius, this.props.radius);
        context.fillStyle = this.props.color;
        context.fill();
    },
    drawParticles: function (context) {
        var i = this.particles.length - 1;
        while (i >= 0) {
            if (this.particles[i].age > 0) {
                this.drawSingleParticle(context, this.particles[i]);
            }
            else {
                this.particles.splice(i, 1);
            }
            i -= 1;
        }
    },
    drawSingleParticle: function (context, particle) {
        context.beginPath();
        context.rect(particle.x, particle.y, this.props.particleSize, this.props.particleSize);
        context.fillStyle = 'rgba(255,' + Math.floor((particle.age / this.props.particleAge) * 255) + ',0,'+particle.age / this.props.particleAge+')';
        context.fill();
        particle.age -= 1;
        particle.y += (Math.random() - 0.5) * 2;
        particle.x += (Math.random() - 0.5) * 2;
    },
    hex2rgb: function (hex) {
        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }
}<|endoftext|>


<commit_before>var ecpup_queue = [];
var ecpup_ready=false;
var ecpup_CSSlines = false;
var ecpup_JSlines = false;
var ecpup_console;
var ecpup_cssStart = false;
var ecpup_jsStart = false;
var ecpup_jsEnd = false;
var ecpup_adjustJS = 2; // skip doctype and html start tag
var ecpup_callback = false;
var ecpup_autopopup = true;
var ecpup_silencePromiseRejections = true;

function ecpup_count(o) {
  switch (typeof o) {
    case 'string':
      return o.split(/\r\n|\r|\n/).length;
      break;
    case 'object':
      return o.innerHTML.split(/\r\n|\r|\n/).length;
      break;
  }
}
function ecpup_newSpan(c, t) {
  var spann = document.createElement("span");
  spann.class = c;
  spann.text = t;
  return spann;
}

function ecpup_insertConsole() {
  var doc = window.document;

  var divv = doc.createElement("div");

  divv.setAttribute("class", "ecpupScroll");
    var pree = doc.createElement("pre");
    var spann = doc.createElement("span");
    spann.setAttribute("class", "ecpupg");
    spann.innerHTML="Line:Col ";
    pree.appendChild(spann);
    var spann = doc.createElement("span");
    spann.setAttribute("class", "ecpupc");
    spann.innerHTML="Section";
    pree.appendChild(spann);
    var txtEl=doc.createTextNode("   Message  ");
    pree.appendChild(txtEl);
    spann = doc.createElement("span");
    spann.setAttribute("class", "ecpupb");
    spann.innerHTML = "(document)";
    pree.appendChild(spann);
  divv.appendChild(pree);

    spann = doc.createElement("span");
    spann.setAttribute("id", "ecpup_console");
    spann.innerHTML="";
  divv.appendChild(spann);

    aa = doc.createElement("a");
    aa.setAttribute("class", "ecpupclose");
    aa.href = "#stub";
    aa.text = ""; // set by ::before
  divv.appendChild(aa); // change class and it unhides

  var divvv = doc.createElement("div");
  divvv.setAttribute("class", "ecpupbox");
  var divvvv = doc.createElement("div");
  divvvv.setAttribute("class", "ecpup");
  divvvv.setAttribute("id", "ecpup1");
  divvv.appendChild(divv);
  divvvv.appendChild(divvv);

  try {
    doc.body.appendChild(divvvv);
  } catch(e) {
    ecpup_altcomms("appendChild failed: " + e.message);
  }
}

function ecpup_altcomms(msg) {
  // TODO: Anyone care?
  //  Choose between console.error or alerts()
  alert("Error Console: " + msg);
}

function ecpup_getLineAndSection(line) {
  var calcline, errloc;
  if(line < ecpup_jsStart) {
    calcline = line;
    errloc = "<head>";
  } else if(line <= ecpup_jsEnd) {
    calcline = line - ecpup_jsStart + 1; // offset in [JS] tab.
    errloc = "[JS]";
  } else {
    calcline = line - ecpup_JSlines - ecpup_CSSlines + ecpup_adjustJS; // accommodate injections
    errloc = "<body>";
  }

  return {ln:calcline, loc:errloc};
}

function ecpup_waitready() {
  var s,j;
  var timeout_count=0;
  s=document.getElementById("style-from-editor");
  j=document.getElementById("script-from-editor");

  if(s) ecpup_CSSlines = ecpup_count(s);
  if(j) ecpup_JSlines = ecpup_count(j);
  if(!(s && j)) {
    timeout_count += 1;
    if(timeout_count == 12) {
      ecpup_altcomms("Unable to connect to document after 3 seconds; console will disconnect after 10 seconds.");
    }
    if(timeout_count > 40) {
      ecpup_altcomms("ErrorConsole: Unable to connect to document after 10 seconds. Disconnecting.");
    } else {
      setTimeout(ecpup_ready, 250); // count-dependency
      return false;
    }
  }
  // document is ready enough to adjust event line numbers and identify locations

  ecpup_insertConsole();
  ecpup_console = document.getElementById('ecpup_console');
  var c = ecpup_console;

  var hd = document.getElementsByTagName("html")[0].innerHTML; // Assume <doctype>, and no intervening code before .
  var hd = hd.split('<'+'/head>'); // drop the end of the document

  if(hd.length < 2) {
    ecpup_altcomms("At least one  section is expected");
  }
  if(hd.length > 2) {
    ecpup_altcomms("More than one <'+'/head> endtag; assuming first one found is correct.");
  }
  hd=hd[0];

  var hdbits = hd.split('<'+'/style>


<commit_before>/**
 * Created by Mihail on 10/2/2016.
 */

'use strict';

import { Utils } from '../utils/utils';

class Ball {
	constructor(num) {
		this.number = num;
		this.color = Utils.getColorByNumber(num);
		this.borderColor = Utils.getBorderColorByNumber(num);
	}

	draw(parentElement, visibleBallNum) {
		const elBall = document.createElement('div');
		const elNumber = document.createElement('span');
		elNumber.innerText = this.number;
		elBall.style.backgroundImage = this.color;
		elBall.style.borderColor = this.borderColor;
		elBall.appendChild(elNumber);
		parentElement.appendChild(elBall);

		setTimeout(() => {
			this.move(elBall, Ball.bounce, Ball.quad, 1000, visibleBallNum);
		}, 200);
	}

	move(element, delta1, delta2, duration = 1000, visibleBallNum) {
		const posUp = 5;
		const startPos = 61;
		const endPosBall2 = 49;
		const endPosBall3 = 37;
		const endPosBall4 = 25;
		const endPosBall5 = 13;

		this.animate({
			delay: 10,
			duration: duration,
			delta: delta1,
			step: function (delta) {
				element.style.top = (-posUp * delta) + 5.5 + "%";
			}
		});

		setTimeout(() => {
				this.animate({
				delay: 10,
				duration: 1000,
				delta: delta2,
				step: function (delta) {
					switch (visibleBallNum) {
						case 1:
							element.style.left = (-(startPos * delta) + startPos) + "%";
							break;
						case 2:
							element.style.left = (-(endPosBall2 * delta) + startPos) + "%";
							break;
						case 3:
							element.style.left = (-(endPosBall3 * delta) + startPos) + "%";
							break;
						case 4:
							element.style.left = (-(endPosBall4 * delta) + startPos) + "%";
							break;
						case 5:
							element.style.left = (-(endPosBall5 * delta) + startPos) + "%";
							break;
					}
				}
			});
		}, 1000);
	}

	animate(opts) {
		const start = new Date;

		let id = setInterval(function () {
			let timePassed = new Date - start;
			let progress = timePassed / opts.duration;

			if (progress > 1)
				progress = 1;

			let delta = opts.delta(progress);
			opts.step(delta);

			if (progress == 1) {
				clearInterval(id)
			}
		}, opts.delay || 10);
	}

	static bounce(progress) {
		for (var a = 0, b = 1; 1; a += b, b /= 2) {
			if (progress >= (7 - 4 * a) / 11) {
				return -Math.pow((11 - 6 * a - 11 * progress) / 4, 2) + Math.pow(b, 2)
			}
		}
	}

	static linear(progress) {
		return progress
	}

	static quad(progress) {
		return Math.pow(progress, 2)
	}

}

export default Ball;<commit_msg>Removed linear function as it's not used anymore.<commit_after>/**
 * Created by Mihail on 10/2/2016.
 */

'use strict';

import { Utils } from '../utils/utils';

class Ball {
	constructor(num) {
		this.number = num;
		this.color = Utils.getColorByNumber(num);
		this.borderColor = Utils.getBorderColorByNumber(num);
	}

	draw(parentElement, visibleBallNum) {
		const elBall = document.createElement('div');
		const elNumber = document.createElement('span');
		elNumber.innerText = this.number;
		elBall.style.backgroundImage = this.color;
		elBall.style.borderColor = this.borderColor;
		elBall.appendChild(elNumber);
		parentElement.appendChild(elBall);

		setTimeout(() => {
			this.move(elBall, Ball.bounce, Ball.quad, 1000, visibleBallNum);
		}, 200);
	}

	move(element, delta1, delta2, duration = 1000, visibleBallNum) {
		const posUp = 5;
		const startPos = 61;
		const endPosBall2 = 49;
		const endPosBall3 = 37;
		const endPosBall4 = 25;
		const endPosBall5 = 13;

		this.animate({
			delay: 10,
			duration: duration,
			delta: delta1,
			step: function (delta) {
				element.style.top = (-posUp * delta) + 5.5 + "%";
			}
		});

		setTimeout(() => {
				this.animate({
				delay: 10,
				duration: 1000,
				delta: delta2,
				step: function (delta) {
					switch (visibleBallNum) {
						case 1:
							element.style.left = (-(startPos * delta) + startPos) + "%";
							break;
						case 2:
							element.style.left = (-(endPosBall2 * delta) + startPos) + "%";
							break;
						case 3:
							element.style.left = (-(endPosBall3 * delta) + startPos) + "%";
							break;
						case 4:
							element.style.left = (-(endPosBall4 * delta) + startPos) + "%";
							break;
						case 5:
							element.style.left = (-(endPosBall5 * delta) + startPos) + "%";
							break;
					}
				}
			});
		}, 1000);
	}

	animate(opts) {
		const start = new Date;

		let id = setInterval(function () {
			let timePassed = new Date - start;
			let progress = timePassed / opts.duration;

			if (progress > 1)
				progress = 1;

			let delta = opts.delta(progress);
			opts.step(delta);

			if (progress == 1) {
				clearInterval(id)
			}
		}, opts.delay || 10);
	}

	static bounce(progress) {
		for (var a = 0, b = 1; 1; a += b, b /= 2) {
			if (progress >= (7 - 4 * a) / 11) {
				return -Math.pow((11 - 6 * a - 11 * progress) / 4, 2) + Math.pow(b, 2)
			}
		}
	}

	static quad(progress) {
		return Math.pow(progress, 2)
	}

}

export default Ball;<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/firebug",
    "firebug/lib/trace",
    "firebug/lib/object",
    "firebug/lib/dom",
    "firebug/lib/xml",
    "firebug/lib/locale",
    "firebug/lib/events",
    "firebug/lib/options",
    "firebug/chrome/menu",
    "firebug/chrome/module",
],
function(Firebug, FBTrace, Obj, Dom, Xml, Locale, Events, Options, Menu, Module) {

"use strict";

// ********************************************************************************************* //
// Constants

// Tracing
var Trace = FBTrace.to("DBG_PANELSELECTOR");
var TraceError = FBTrace.to("DBG_ERRORS");

// The option has been renamed in Firebug 2.0 to force all panels to be displayed.
// This is because the panel selector menu has been moved into Firebug menu and
// some users could be confused by that change (not being able to get back hidden panels).
// (see also issue 7046).
var hiddenPanels = "hiddenPanels2";

// ********************************************************************************************* //
// Implementation

/**
 * @module This object implements 'Panel Selector' feature that allows to show/hide individual
 * Firebug panels. This feature used to be available on the main Firebug toolbar and has
 * been moved into Firebug menu in 2.0
 */
var PanelSelector = Obj.extend(Module,
/** @lends PanelSelector */
{
    dispatchName: "PanelSelector",

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Module

    initialize: function()
    {
        Module.initialize.apply(this, arguments);

        Firebug.registerUIListener(this);
    },

    shutdown: function()
    {
        Module.shutdown.apply(this, arguments);

        Firebug.unregisterUIListener(this);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Firebug Menu

    onMenuShowing: function(popup)
    {
        var items = [];
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");
        var tab = panelBar.panelTabs.firstChild;

        // Create an menu-option-item for every existing panel tab.
        while (tab)
        {
            var panelType = tab.panelType;
            var panelName = panelType.prototype.name;

            items.push(
            {
                label: Firebug.getPanelTitle(panelType),
                tooltiptext: Firebug.getPanelTooltip(panelType),
                type: "checkbox",
                checked: Xml.isVisible(tab),
                command: this.onTogglePanel.bind(this, popup, panelName),
            });

            tab = tab.nextSibling;
        }

        // Create separator
        items.push("-");

        // The last menu item is for opening all panels.
        items.push(
        {
            label: Locale.$STR("firebug.Show_All_Panels"),
            tooltiptext: Firebug.getPanelTooltip(panelType),
            command: this.onShowAllPanels.bind(this)
        });

        Menu.createMenuItems(popup, items);

        this.updateMenuItems(popup);

        return true;
    },

    onMenuHiding: function(popup)
    {
        Dom.eraseNode(popup);
    },

    updateMenuItems: function(popup)
    {
        var visibleTabs = [];
        var menuItem = popup.firstChild;
        while (menuItem)
        {
            var checked = menuItem.getAttribute("checked") == "true";
            if (checked)
                visibleTabs.push(menuItem);

            menuItem.removeAttribute("disabled");
            menuItem = menuItem.nextSibling;
        }

        // If there is only one panel visible don't allow to close it.
        if (visibleTabs.length == 1)
            visibleTabs[0].setAttribute("disabled", true);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Commands

    onTogglePanel: function(popup, panelName, event)
    {
        Events.cancelEvent(event);

        var menuItem = event.target;
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        // The last visible panel can't be hidden.
        if (menuItem.getAttribute("disabled") == "true")
            return;

        // Toggle panel visibility
        menuItem.checked = !menuItem.checked;
        this.togglePanel(panelName, !menuItem.checked);

        Trace.sysout("panelSelector.onTogglePanel; " + panelName + ", visible now: " +
            menuItem.checked, event);

        // If there is only one visible panel now, make sure it's disabled.
        // (the user can't hide all panels).
        this.updateMenuItems(popup);
    },

    onShowAllPanels: function(event)
    {
        Events.cancelEvent(event);

        Trace.sysout("panelSelector.onShowAllPanels;", event);

        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        var tab = panelBar.panelTabs.firstChild;
        while (tab)
        {
            if (!Xml.isVisible(tab))
                Dom.collapse(tab, false);

            tab = tab.nextSibling;
        }

        Options.set(hiddenPanels, "");
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Implementation

    closePanel: function(panelName)
    {
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        var tab = panelBar.getTab(panelName);
        Dom.collapse(tab, true);

        this.storeHiddenPanels();

        if (panelBar.selectedTab != tab)
            return;

        // If the selected panel has been closed, select the first one that is visible.
        tab = panelBar.panelTabs.firstChild;
        while (tab)
        {
            if (FBL.isVisible(tab))
            {
                panelBar.selectTab(tab);
                break;
            }
            tab = tab.nextSibling;
        }
    },

    openPanel: function(panelName)
    {
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        var tab = panelBar.getTab(panelName);
        Dom.collapse(tab, false);

        this.storeHiddenPanels();
    },

    togglePanel: function(panelName, forceOpen)
    {
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        var tab = panelBar.getTab(panelName);
        if (!tab)
            return;

        var open = Xml.isVisible(tab);
        if (open && forceOpen)
            return;

        if (open)
            this.closePanel(panelName);
        else
            this.openPanel(panelName);
    },

    storeHiddenPanels: function()
    {
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        var closedPanels = [];
        var tab = panelBar.panelTabs.firstChild;
        while (tab)
        {
            if (!Xml.isVisible(tab))
                closedPanels.push(tab.panelType.prototype.name);

            tab = tab.nextSibling;
        }

        Options.set(hiddenPanels, closedPanels.join(" "));
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // UI Listener

    /**
     * Sent by the framework (bindings.xml) when panel tabs are updated.
     */
    updatePanels: function(panelTypes)
    {
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        // Make sure hidden panels are collapsed.
        var value = Options.get(hiddenPanels);
        if (!value || !value.length)
            return;

        var closedPanels = value.split(" ");
        for (var i = 0; i < closedPanels.length; i++)
        {
            var tab = panelBar.tabMap[closedPanels[i]];
            if (tab)
                Dom.collapse(tab, true);
        }
    }
});

// ********************************************************************************************* //
// Registration

Firebug.registerModule(PanelSelector);

// Expose for browserOverlay.js
Firebug.PanelSelector = PanelSelector;

return PanelSelector;

// ********************************************************************************************* //
});
<commit_msg>Use proper module<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/firebug",
    "firebug/lib/trace",
    "firebug/lib/object",
    "firebug/lib/dom",
    "firebug/lib/xml",
    "firebug/lib/locale",
    "firebug/lib/events",
    "firebug/lib/options",
    "firebug/chrome/menu",
    "firebug/chrome/module",
],
function(Firebug, FBTrace, Obj, Dom, Xml, Locale, Events, Options, Menu, Module) {

"use strict";

// ********************************************************************************************* //
// Constants

// Tracing
var Trace = FBTrace.to("DBG_PANELSELECTOR");
var TraceError = FBTrace.to("DBG_ERRORS");

// The option has been renamed in Firebug 2.0 to force all panels to be displayed.
// This is because the panel selector menu has been moved into Firebug menu and
// some users could be confused by that change (not being able to get back hidden panels).
// (see also issue 7046).
var hiddenPanels = "hiddenPanels2";

// ********************************************************************************************* //
// Implementation

/**
 * @module This object implements 'Panel Selector' feature that allows to show/hide individual
 * Firebug panels. This feature used to be available on the main Firebug toolbar and has
 * been moved into Firebug menu in 2.0
 */
var PanelSelector = Obj.extend(Module,
/** @lends PanelSelector */
{
    dispatchName: "PanelSelector",

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Module

    initialize: function()
    {
        Module.initialize.apply(this, arguments);

        Firebug.registerUIListener(this);
    },

    shutdown: function()
    {
        Module.shutdown.apply(this, arguments);

        Firebug.unregisterUIListener(this);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Firebug Menu

    onMenuShowing: function(popup)
    {
        var items = [];
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");
        var tab = panelBar.panelTabs.firstChild;

        // Create an menu-option-item for every existing panel tab.
        while (tab)
        {
            var panelType = tab.panelType;
            var panelName = panelType.prototype.name;

            items.push(
            {
                label: Firebug.getPanelTitle(panelType),
                tooltiptext: Firebug.getPanelTooltip(panelType),
                type: "checkbox",
                checked: Xml.isVisible(tab),
                command: this.onTogglePanel.bind(this, popup, panelName),
            });

            tab = tab.nextSibling;
        }

        // Create separator
        items.push("-");

        // The last menu item is for opening all panels.
        items.push(
        {
            label: Locale.$STR("firebug.Show_All_Panels"),
            tooltiptext: Firebug.getPanelTooltip(panelType),
            command: this.onShowAllPanels.bind(this)
        });

        Menu.createMenuItems(popup, items);

        this.updateMenuItems(popup);

        return true;
    },

    onMenuHiding: function(popup)
    {
        Dom.eraseNode(popup);
    },

    updateMenuItems: function(popup)
    {
        var visibleTabs = [];
        var menuItem = popup.firstChild;
        while (menuItem)
        {
            var checked = menuItem.getAttribute("checked") == "true";
            if (checked)
                visibleTabs.push(menuItem);

            menuItem.removeAttribute("disabled");
            menuItem = menuItem.nextSibling;
        }

        // If there is only one panel visible don't allow to close it.
        if (visibleTabs.length == 1)
            visibleTabs[0].setAttribute("disabled", true);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Commands

    onTogglePanel: function(popup, panelName, event)
    {
        Events.cancelEvent(event);

        var menuItem = event.target;
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        // The last visible panel can't be hidden.
        if (menuItem.getAttribute("disabled") == "true")
            return;

        // Toggle panel visibility
        menuItem.checked = !menuItem.checked;
        this.togglePanel(panelName, !menuItem.checked);

        Trace.sysout("panelSelector.onTogglePanel; " + panelName + ", visible now: " +
            menuItem.checked, event);

        // If there is only one visible panel now, make sure it's disabled.
        // (the user can't hide all panels).
        this.updateMenuItems(popup);
    },

    onShowAllPanels: function(event)
    {
        Events.cancelEvent(event);

        Trace.sysout("panelSelector.onShowAllPanels;", event);

        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        var tab = panelBar.panelTabs.firstChild;
        while (tab)
        {
            if (!Xml.isVisible(tab))
                Dom.collapse(tab, false);

            tab = tab.nextSibling;
        }

        Options.set(hiddenPanels, "");
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Implementation

    closePanel: function(panelName)
    {
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        var tab = panelBar.getTab(panelName);
        Dom.collapse(tab, true);

        this.storeHiddenPanels();

        if (panelBar.selectedTab != tab)
            return;

        // If the selected panel has been closed, select the first one that is visible.
        tab = panelBar.panelTabs.firstChild;
        while (tab)
        {
            if (Xml.isVisible(tab))
            {
                panelBar.selectTab(tab);
                break;
            }
            tab = tab.nextSibling;
        }
    },

    openPanel: function(panelName)
    {
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        var tab = panelBar.getTab(panelName);
        Dom.collapse(tab, false);

        this.storeHiddenPanels();
    },

    togglePanel: function(panelName, forceOpen)
    {
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        var tab = panelBar.getTab(panelName);
        if (!tab)
            return;

        var open = Xml.isVisible(tab);
        if (open && forceOpen)
            return;

        if (open)
            this.closePanel(panelName);
        else
            this.openPanel(panelName);
    },

    storeHiddenPanels: function()
    {
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        var closedPanels = [];
        var tab = panelBar.panelTabs.firstChild;
        while (tab)
        {
            if (!Xml.isVisible(tab))
                closedPanels.push(tab.panelType.prototype.name);

            tab = tab.nextSibling;
        }

        Options.set(hiddenPanels, closedPanels.join(" "));
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // UI Listener

    /**
     * Sent by the framework (bindings.xml) when panel tabs are updated.
     */
    updatePanels: function(panelTypes)
    {
        var panelBar = Firebug.chrome.getElementById("fbPanelBar1");

        // Make sure hidden panels are collapsed.
        var value = Options.get(hiddenPanels);
        if (!value || !value.length)
            return;

        var closedPanels = value.split(" ");
        for (var i = 0; i < closedPanels.length; i++)
        {
            var tab = panelBar.tabMap[closedPanels[i]];
            if (tab)
                Dom.collapse(tab, true);
        }
    }
});

// ********************************************************************************************* //
// Registration

Firebug.registerModule(PanelSelector);

// Expose for browserOverlay.js
Firebug.PanelSelector = PanelSelector;

return PanelSelector;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>module.exports = function(root) {
    var glob = require('glob'),
        _ = require('lodash'),
        PATH = require('path'),
        definitionsFiles = glob.sync('./src/definitions/**/*.js', {
            root: root
        });

    _.forEach(definitionsFiles, function(defFile) {
        var def = require(PATH.resolve(root, defFile));
        if (_.isArray(def)) {
            compiledDefs = _.union(compiledDefs, def);
        }
    })

    return compiledDefs;

};<commit_msg>0.0.8<commit_after>module.exports = function(root){
  var glob = require('glob'),
      _ = require('lodash'),
      PATH = require('path'),
      definitionsFiles = glob.sync('./src/definitions/**/*.js', {root: root});

  var compiledDefs = [];

  _.forEach(definitionsFiles, function(defFile){
    var def = require(PATH.resolve(root, defFile));
    if(_.isArray(def)){
      compiledDefs = _.union(compiledDefs, def);
    }
  })

  return compiledDefs;

};
<|endoftext|>