<commit_before>var Utils = require("./utils")

var QueryGenerator = module.exports = {
  /*
    Returns a query for creating a table.
    Attributes should have the format: {attributeName: type, attr2: type2} --> {title: 'VARCHAR(255)'}
  */
  createTableQuery: function(tableName, attributes, options) {
    options = options || {}

    var query   = "CREATE TABLE IF NOT EXISTS `<%= table %>` (<%= attributes%>);"
      , attrStr = Utils._.map(attributes, function(dataType, attr) { return Utils.addTicks(attr) + " " + dataType}).join(", ")
      , values  = {table: tableName, attributes: attrStr}

    return  Utils._.template(query)(values)
  },

  dropTableQuery: function(tableName, options) {
    options = options || {}

    var query = "DROP TABLE IF EXISTS `<%= table %>`;"

    return Utils._.template(query)({table: tableName})
  },

  selectQuery: function(tableName, options) {
    options = options || {}
    options.table = tableName
    options.attributes = options.attributes || '*'

    var query = "SELECT <%= attributes %> FROM `<%= table %>`"

    if(options.where) {
      if(Utils.isHash(options.where))
        options.where = QueryGenerator.hashToWhereConditions(values.where)
      else if(typeof options.where == 'number')
        options.where = Utils.addTicks('id') + "=" + options.where
      query += " WHERE <%= where %>"
    }
    if(options.order) query += " ORDER BY <%= order %>"
    if(options.group) query += " GROUP BY <%= group %>"
    if(options.limit) {
      if(options.offset) query += " LIMIT <%= offset %>, <%= limit %>"
      else query += " LIMIT <%= limit %>"
    }

    query += ";"

    return Utils._.template(query)(options)
  },

  // TODO
  insertQuery: function(tableName, attributes, values) {
    // query = "INSERT INTO `%{table}` (%{fields}) VALUES (%{values})"
  },

  // TODO
  updateQuery: function(tableName, values, where) {
    // if(Sequelize.Helper.Hash.isHash(values.values))
    //   values.values = Sequelize.Helper.SQL.hashToWhereConditions(values.values)
    //
    // query = "UPDATE `%{table}` SET %{values} WHERE `id`=%{id}"
  },

  // TODO
  deleteQuery: function(tableName, where) {
    // if(Sequelize.Helper.Hash.isHash(values.where))
    //   values.where = Sequelize.Helper.SQL.hashToWhereConditions(values.where)
    //
    // query = "DELETE FROM `%{table}` WHERE %{where}"
    // if(typeof values.limit == 'undefined') query += " LIMIT 1"
    // else if(values.limit != null) query += " LIMIT " + values.limit
  },

  /*
    Takes a hash and transforms it into a mysql where condition: {key: value, key2: value2} ==> key=value AND key2=value2
    The values are transformed by the relevant datatype.
  */
  hashToWhereConditions: function(hash) {
    return Utils._.map(hash, function(value, key) {
      var dataType = Utils.getDataTypeForValue(value)
        , _value   = Utils.transformValueByDataType(value, dataType)
        , _key     = Utils.addTicks(key)

      return (_value == 'NULL') ? _key + " IS NULL" : [_key, _value].join("=")
    }).join(" AND ")
  }
}<commit_msg>added insertQuery<commit_after>var Utils = require("./utils")

var QueryGenerator = module.exports = {
  /*
    Returns a query for creating a table.
    Attributes should have the format: {attributeName: type, attr2: type2} --> {title: 'VARCHAR(255)'}
  */
  createTableQuery: function(tableName, attributes, options) {
    options = options || {}

    var query   = "CREATE TABLE IF NOT EXISTS `<%= table %>` (<%= attributes%>);"
      , attrStr = Utils._.map(attributes, function(dataType, attr) { return Utils.addTicks(attr) + " " + dataType}).join(", ")
      , values  = {table: tableName, attributes: attrStr}

    return  Utils._.template(query)(values)
  },

  dropTableQuery: function(tableName, options) {
    options = options || {}

    var query = "DROP TABLE IF EXISTS `<%= table %>`;"

    return Utils._.template(query)({table: tableName})
  },

  selectQuery: function(tableName, options) {
    options = options || {}
    options.table = tableName
    options.attributes = options.attributes || '*'

    var query = "SELECT <%= attributes %> FROM `<%= table %>`"

    if(options.where) {
      if(Utils.isHash(options.where))
        options.where = QueryGenerator.hashToWhereConditions(values.where)
      else if(typeof options.where == 'number')
        options.where = Utils.addTicks('id') + "=" + options.where
      query += " WHERE <%= where %>"
    }
    if(options.order) query += " ORDER BY <%= order %>"
    if(options.group) query += " GROUP BY <%= group %>"
    if(options.limit) {
      if(options.offset) query += " LIMIT <%= offset %>, <%= limit %>"
      else query += " LIMIT <%= limit %>"
    }

    query += ";"

    return Utils._.template(query)(options)
  },

  /*
    Returns an insert into command. Parameters: table name + hash of attribute-value-pairs.
  */
  insertQuery: function(tableName, attrValueHash) {
    var query = "INSERT INTO `<%= table %>` (<%= attributes %>) VALUES (<%= values %>)"
    var replacements  = {
      table: tableName,
      attributes: Utils._.keys(attrValueHash).map(function(attr){return Utils.addTicks(attr)}).join(","),
      values: Utils._.values(attrValueHash).map(function(value){
        return Utils.transformValueByDataType(value, Utils.getDataTypeForValue(value))
      }).join(",")
    }

    return Utils._.template(query)(replacements)
  },

  // TODO
  updateQuery: function(tableName, values, where) {
    // if(Sequelize.Helper.Hash.isHash(values.values))
    //   values.values = Sequelize.Helper.SQL.hashToWhereConditions(values.values)
    //
    // query = "UPDATE `%{table}` SET %{values} WHERE `id`=%{id}"
  },

  // TODO
  deleteQuery: function(tableName, where) {
    // if(Sequelize.Helper.Hash.isHash(values.where))
    //   values.where = Sequelize.Helper.SQL.hashToWhereConditions(values.where)
    //
    // query = "DELETE FROM `%{table}` WHERE %{where}"
    // if(typeof values.limit == 'undefined') query += " LIMIT 1"
    // else if(values.limit != null) query += " LIMIT " + values.limit
  },

  /*
    Takes a hash and transforms it into a mysql where condition: {key: value, key2: value2} ==> key=value AND key2=value2
    The values are transformed by the relevant datatype.
  */
  hashToWhereConditions: function(hash) {
    return Utils._.map(hash, function(value, key) {
      var dataType = Utils.getDataTypeForValue(value)
        , _value   = Utils.transformValueByDataType(value, dataType)
        , _key     = Utils.addTicks(key)

      return (_value == 'NULL') ? _key + " IS NULL" : [_key, _value].join("=")
    }).join(" AND ")
  }
}<|endoftext|>


<commit_before>// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.views.calendar");

frappe.views.GanttFactory = frappe.views.Factory.extend({
	make: function(route) {
		var me = this;
		frappe.model.with_doctype(route[1], function() {
			var page = me.make_page();
			$(page).on("show", function() {
				page.ganttview.set_filters_from_route_options();
			});

			var options = {
				doctype: route[1],
				page: page
			};
			$.extend(options, frappe.views.calendar[route[1]] || {});

			page.ganttview = new frappe.views.Gantt(options);
		});
	}
});

frappe.views.Gantt = Class.extend({
	init: function(opts) {
		$.extend(this, opts);

		frappe.require('assets/frappe/js/lib/jQuery.Gantt/css/style.css');
		frappe.require('assets/frappe/js/lib/jQuery.Gantt/js/jquery.fn.gantt.js');

		this.make_page();
		frappe.route_options ?
			this.set_filters_from_route_options() :
			this.refresh();
	},
	make_page: function() {
		var module = locals.DocType[this.doctype].module,
			me = this;

		this.appframe = this.page.appframe;
		this.appframe.set_title(__("Gantt Chart") + " - " + __(this.doctype));
		this.appframe.add_module_icon(module)
		this.appframe.set_views_for(this.doctype, "gantt");

		this.appframe.set_title_right(__("Refresh"),
			function() { me.refresh(); }, "icon-refresh")

		this.appframe.add_field({fieldtype:"Date", label:"From",
			fieldname:"start", "default": frappe.datetime.month_start(), input_css: {"z-index": 3}});

		this.appframe.add_field({fieldtype:"Date", label:"To",
			fieldname:"end", "default": frappe.datetime.month_end(), input_css: {"z-index": 3}});

		if(this.filters) {
			$.each(this.filters, function(i, df) {
				me.appframe.add_field(df);
				return false;
			});
		}
	},
	refresh: function() {
		var parent = $(this.page)
			.find(".layout-main")
			.empty()
			.css('min-height', '300px')
			.html('
Loading...
');

		var me = this;
		return frappe.call({
			method: this.get_events_method,
			type: "GET",
			args: {
				doctype: this.doctype,
				start: this.appframe.fields_dict.start.get_parsed_value(),
				end: this.appframe.fields_dict.end.get_parsed_value(),
				filters: this.get_filters()
			},
			callback: function(r) {
				$(parent).empty();
				if(!r.message || !r.message.length) {
					$(parent).html('
' + __('Nothing to show for this selection') + '
');
				} else {
					var gantt_area = $('
').appendTo(parent);
					gantt_area.gantt({
						source: me.get_source(r),
						navigate: "scroll",
						scale: "days",
						minScale: "hours",
						maxScale: "months",
						onItemClick: function(data) {
							frappe.set_route('Form', me.doctype, data.name);
						},
						onAddClick: function(dt, rowId) {
							newdoc(me.doctype);
						}
					});
				}
			}
		})

	},
	set_filter: function(doctype, value) {
		var me = this;
		if(this.filters) {
			$.each(this.filters, function(i, df) {
				if(df.options===value)
					me.appframe.fields_dict[df.fieldname].set_input(value);
					return false;
			});
		}
	},
	get_filters: function() {
		var filter_vals = {},
			me = this;
		if(this.filters) {
			$.each(this.filters, function(i, df) {
				filter_vals[df.fieldname || df.label] =
					me.appframe.fields_dict[df.fieldname || df.label].get_parsed_value();
			});
		}
		return filter_vals;
	},
	get_source: function(r) {
		var source = [],
			me = this;
		// projects
		$.each(r.message, function(i,v) {

			// standardize values
			$.each(me.field_map, function(target, source) {
				v[target] = v[source];
			});

			if(v.start && !v.end) {
				v.end = new Date(v.start)
				v.end.setHours(v.end.getHours() + 1);
			}

			if(v.start && v.end) {
				source.push({
					name: v.title,
					desc: v.status,
					values: [{
						name: v.title,
						desc: v.title + "
" + (v.status || ""),
						from: '/Date('+moment(v.start).format("X")+'000)/',
						to: '/Date('+moment(v.end).format("X")+'000)/',
						customClass: {
							'danger':'ganttRed',
							'warning':'ganttOrange',
							'info':'ganttBlue',
							'success':'ganttGreen',
							'':'ganttGray'
						}[me.style_map ?
							me.style_map[v.status] :
							frappe.utils.guess_style(v.status, "standard")],
						dataObj: v
					}]
				})
			}
		});
		return source
	},
	set_filters_from_route_options: function() {
		var me = this;
		if(frappe.route_options) {
			$.each(frappe.route_options, function(k, value) {
				if(me.appframe.fields_dict[k]) {
					me.appframe.fields_dict[k].set_input(value);
				};
			})
			frappe.route_options = null;
			me.refresh();
			return false;
		}
	}
});
<commit_msg>gantt-view fix<commit_after>// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.views.calendar");

frappe.views.GanttFactory = frappe.views.Factory.extend({
	make: function(route) {
		var me = this;
		frappe.model.with_doctype(route[1], function() {
			var page = me.make_page();
			$(page).on("show", function() {
				page.ganttview.set_filters_from_route_options();
			});

			var options = {
				doctype: route[1],
				page: page
			};
			$.extend(options, frappe.views.calendar[route[1]] || {});

			page.ganttview = new frappe.views.Gantt(options);
		});
	}
});

frappe.views.Gantt = Class.extend({
	init: function(opts) {
		$.extend(this, opts);

		frappe.require('assets/frappe/js/lib/jQuery.Gantt/css/style.css');
		frappe.require('assets/frappe/js/lib/jQuery.Gantt/js/jquery.fn.gantt.js');

		this.make_page();
		frappe.route_options ?
			this.set_filters_from_route_options() :
			this.refresh();
	},
	make_page: function() {
		var module = locals.DocType[this.doctype].module,
			me = this;

		this.appframe = this.page.appframe;
		this.appframe.set_title(__("Gantt Chart") + " - " + __(this.doctype));
		this.appframe.add_module_icon(module)
		this.appframe.set_views_for(this.doctype, "gantt");

		this.appframe.set_title_right(__("Refresh"),
			function() { me.refresh(); }, "icon-refresh")

		this.appframe.add_field({fieldtype:"Date", label:"From",
			fieldname:"start", "default": frappe.datetime.month_start(), input_css: {"z-index": 3}});

		this.appframe.add_field({fieldtype:"Date", label:"To",
			fieldname:"end", "default": frappe.datetime.month_end(), input_css: {"z-index": 3}});

		if(this.filters) {
			$.each(this.filters, function(i, df) {
				me.appframe.add_field(df);
			});
		}
	},
	refresh: function() {
		var parent = $(this.page)
			.find(".layout-main")
			.empty()
			.css('min-height', '300px')
			.html('
Loading...
');

		var me = this;
		return frappe.call({
			method: this.get_events_method,
			type: "GET",
			args: {
				doctype: this.doctype,
				start: this.appframe.fields_dict.start.get_parsed_value(),
				end: this.appframe.fields_dict.end.get_parsed_value(),
				filters: this.get_filters()
			},
			callback: function(r) {
				$(parent).empty();
				if(!r.message || !r.message.length) {
					$(parent).html('
' + __('Nothing to show for this selection') + '
');
				} else {
					var gantt_area = $('
').appendTo(parent);
					gantt_area.gantt({
						source: me.get_source(r),
						navigate: "scroll",
						scale: "days",
						minScale: "hours",
						maxScale: "months",
						onItemClick: function(data) {
							frappe.set_route('Form', me.doctype, data.name);
						},
						onAddClick: function(dt, rowId) {
							newdoc(me.doctype);
						}
					});
				}
			}
		})

	},
	set_filter: function(doctype, value) {
		var me = this;
		if(this.filters) {
			$.each(this.filters, function(i, df) {
				if(df.options===value)
					me.appframe.fields_dict[df.fieldname].set_input(value);
					return false;
			});
		}
	},
	get_filters: function() {
		var filter_vals = {},
			me = this;
		if(this.filters) {
			$.each(this.filters, function(i, df) {
				filter_vals[df.fieldname || df.label] =
					me.appframe.fields_dict[df.fieldname || df.label].get_parsed_value();
			});
		}
		return filter_vals;
	},
	get_source: function(r) {
		var source = [],
			me = this;
		// projects
		$.each(r.message, function(i,v) {

			// standardize values
			$.each(me.field_map, function(target, source) {
				v[target] = v[source];
			});

			if(v.start && !v.end) {
				v.end = new Date(v.start)
				v.end.setHours(v.end.getHours() + 1);
			}

			if(v.start && v.end) {
				source.push({
					name: v.title,
					desc: v.status,
					values: [{
						name: v.title,
						desc: v.title + "
" + (v.status || ""),
						from: '/Date('+moment(v.start).format("X")+'000)/',
						to: '/Date('+moment(v.end).format("X")+'000)/',
						customClass: {
							'danger':'ganttRed',
							'warning':'ganttOrange',
							'info':'ganttBlue',
							'success':'ganttGreen',
							'':'ganttGray'
						}[me.style_map ?
							me.style_map[v.status] :
							frappe.utils.guess_style(v.status, "standard")],
						dataObj: v
					}]
				})
			}
		});
		return source
	},
	set_filters_from_route_options: function() {
		var me = this;
		if(frappe.route_options) {
			$.each(frappe.route_options, function(k, value) {
				if(me.appframe.fields_dict[k]) {
					me.appframe.fields_dict[k].set_input(value);
				};
			})
			frappe.route_options = null;
			me.refresh();
			return false;
		}
	}
});
<|endoftext|>


<commit_before>define([
    'jsiso/canvas/Control',
    'jsiso/canvas/Input',
    'jsiso/img/load',
    'jsiso/json/load',
    'jsiso/tile/Field',
    'jsiso/pathfind/pathfind',
    '../../player',
    '../../action'
  ],
  (CanvasControl, CanvasInput, imgLoader, jsonLoader, TileField, pathfind, Player, ActionExecutor) => {

  let requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame  ||
    window.mozRequestAnimationFrame     ||
    window.oRequestAnimationFrame       ||
    window.msRequestAnimationFrame      ||
    function(callback, element) {
      window.setTimeout(callback, 1000 / 60);
    };
  })();

  const ELEMENT_NAMES = {
    containerName: 'container',
    frameName: 'text-frame',
    messageName: 'text-message',
    indicatorName: 'text-indicator'
  };

  let appendHtml = (el, str) => {
    let div = document.createElement('div');
    div.innerHTML = str;
    while (div.children.length > 0) {
      el.appendChild(div.children[0]);
    }
  }

  let createElements = (container, names) => {
    let elements = '\

\

\
        \
        ▼\

\
    ';
    appendHtml(container, elements);
  }

  return function TileEngine(x, y, xrange, yrange, parent=document.body, overrides) {
    let self = this;
    overrides = Object.assign({}, overrides);

    let elementNames = Object.assign(ELEMENT_NAMES, overrides.elementNames);
    createElements(parent, elementNames);
    const container = document.getElementById(elementNames.containerName);

    let textMessages = [];
    const textMessageFrame = document.getElementById(elementNames.frameName);
    const textMessage = document.getElementById(elementNames.messageName);
    const textIndicator = document.getElementById(elementNames.indicatorName)

    const controlWidth = container.clientWidth;
    const controlHeight = container.clientHeight;
    const context = CanvasControl.create("canvas", controlWidth, controlHeight, {}, elementNames.containerName, true);

    let backgroundLayers = [];
    let foregroundLayers = [];

    let paused = false;
    let mapLayers = [];
    let players = [];

    let actionExecutor = new ActionExecutor();
    actionExecutor.registerAction('toggleTile', (options, engine, player) => {
      let layers = mapLayers.filter((layer) => layer.zIndex === player.properties.zIndex);
      layers.forEach((layer) => {
        let currentTile = layer.getTile(options.target.x, options.target.y);
        let currentIndex = options.tiles.indexOf(currentTile);
        layer.setTile(options.target.x, options.target.y, options.tiles[(currentIndex + 1) % options.tiles.length]);
      })
    });

    //CanvasControl.fullScreen();
    const input = new CanvasInput(document, CanvasControl());

    input.mouse_action(function(coords) {
      if (paused) {
        drawMessages()
      } else {
        let player = players[0];
        let layer = player.properties.layer;
        let t = layer.applyMouseFocus(coords.x, coords.y);
        player.goTo(t.x, t.y);
        if (Math.abs(t.x - player.getTile().x) + Math.abs(t.y - player.getTile().y) === 1) {
          interact(player, t);
        }
      }
    });

    textMessageFrame.onclick = () => {
      if (paused) {
        drawMessages();
      }
    };

    input.keyboard(function(pressed, status) {
      let player = players[0];
      if (status) {
        if (paused) {
          if ([13, 32].indexOf(pressed) >= 0) {
            drawMessages();
          }
        } else {
          switch (pressed) {
            case 37: player.moveTo(player.getTile().x - 1, player.getTile().y); break;
            case 38: player.moveTo(player.getTile().x, player.getTile().y - 1); break;
            case 39: player.moveTo(player.getTile().x + 1, player.getTile().y); break;
            case 40: player.moveTo(player.getTile().x, player.getTile().y + 1); break;
            case 13: case 32: interact(player, player.getLookedAtTile()); break;
          }
        }
      }
    });

    let getActions = (player=null) => {
      let layers = mapLayers;
      if (player !== null) {
        layers = layers.filter((layer) => layer.zIndex === player.properties.zIndex);
      }
      let actions = [];
      layers.forEach((layer) => actions = actions.concat(layer.actions || []));
      return actions;
    }

    let interact = (player, tile) => {
      if (!player.isMoving()) {
        getActions(player)
          .filter((action) => action.type !== actionExecutor.TYPE_POSITIONAL)
          .filter((action) => action.x === tile.x && action.y == tile.y)
          .forEach((action) => actionExecutor.execute(action, self, player));
      }
    };

    let pause = () => {
      paused = true;
    }

    let unpause = () => {
      if (paused) {
        paused = false;
        draw();
      }
    }

    let clearText = () => {
      textMessages = [];
      textMessageFrame.classList.remove("in");
      textMessage.innerHTML = "";
      textIndicator.classList.remove("in");
      if (paused) {
        unpause();
      }
    }

    this.displayText = (text) => {
      textMessages = textMessages.concat(text);
    }

    let drawMessages = () => {
      if (textMessages.length > 0) {
        pause();
        let text = textMessages.splice(0, 1)[0];
        textMessage.innerHTML = text;
        if (!("in" in textMessageFrame.classList)) {
          textMessageFrame.classList.add("in");
        }
        if (textMessages.length >= 1) {
          textIndicator.classList.add("in");
        } else {
          textIndicator.classList.remove("in");
        }
      } else {
        clearText();
      }
    }

    let drawLayers = (layers) => {
      for (let i = y; i < yrange; i++) {
        for (let j = x; j < xrange; j++) {
          layers.forEach((layer) => layer.draw(i, j));
        }
      }
    }

    let setPlayerLighting = (tile) => {
      mapLayers.forEach((layer) => layer.setLight(tile.x, tile.y));
    }

    let previousTime = 0;
    let timeToDraw = (time) => !overrides.lockedFrameRate || (time - previousTime) >= 1000 / overrides.lockedFrameRate;

    let draw = (time) => {
      if (!timeToDraw(time)) {
        requestAnimationFrame(draw);
      } else {
        previousTime = time;
        context.clearRect(0, 0, controlWidth, controlHeight);
        drawLayers(backgroundLayers);
        for (let player of players) {
          player.draw();
          player.move();
          setPlayerLighting(player.getTile());
        }
        drawLayers(foregroundLayers);
        drawMessages();
        if (!paused) {
          requestAnimationFrame(draw);
        }
      }
    }

    let initLayer = (layer) => {
      let mapLayer = new TileField(context, controlWidth, controlHeight);
      mapLayer.setup(layer);
      mapLayer.flip("horizontal");
      mapLayer.rotate("left");
      mapLayer.setLightmap(layer.lightmap);
      mapLayer = Object.assign(mapLayer, layer);
      return mapLayer;
    }

    this.init = (map) => {
      let playerOptions = map.characters["player"];
      imgLoader([{
        graphics: [playerOptions.sprites],
        spritesheet: {
          width: playerOptions.width,
          height: playerOptions.height
        }
      }]).then((playerImages) => {
        mapLayers = map.layers.sort((a, b) => a.zIndex > b.zIndex).map(initLayer);
        backgroundLayers = mapLayers.filter((layer) => layer.zIndex < playerOptions.zIndex && layer.visible);
        foregroundLayers = mapLayers.filter((layer) => layer.zIndex >= playerOptions.zIndex && layer.visible);

        playerOptions.files = playerImages[0].files;
        playerOptions.layer = mapLayers[0];
        playerOptions.pathfindingLayer = mapLayers[playerOptions.pathfindingLayer];
        playerOptions.tileWidth = map.tileWidth;
        playerOptions.tileHeight = map.tileHeight;

        let player = new Player(context, playerOptions, playerOptions.x, playerOptions.y, pathfind);
        player.on("changeTile", (p, tile) => {
          getActions().filter((action) => action.type === actionExecutor.TYPE_POSITIONAL).forEach((action) => {
            if (action.x === tile.x && action.y === tile.y) {
              actionExecutor.execute(action, self, p);
            }
          })
        });

        players.push(player);

        draw();
      });
    }
  }
});<commit_msg>Make more parts of engine interface public<commit_after>define([
    'jsiso/canvas/Control',
    'jsiso/canvas/Input',
    'jsiso/img/load',
    'jsiso/json/load',
    'jsiso/tile/Field',
    'jsiso/pathfind/pathfind',
    '../../player',
    '../../action'
  ],
  (CanvasControl, CanvasInput, imgLoader, jsonLoader, TileField, pathfind, Player, ActionExecutor) => {

  let requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame  ||
    window.mozRequestAnimationFrame     ||
    window.oRequestAnimationFrame       ||
    window.msRequestAnimationFrame      ||
    function(callback, element) {
      window.setTimeout(callback, 1000 / 60);
    };
  })();

  const ELEMENT_NAMES = {
    containerName: 'container',
    frameName: 'text-frame',
    messageName: 'text-message',
    indicatorName: 'text-indicator'
  };

  let appendHtml = (el, str) => {
    let div = document.createElement('div');
    div.innerHTML = str;
    while (div.children.length > 0) {
      el.appendChild(div.children[0]);
    }
  }

  let createElements = (container, names) => {
    let elements = '\

\

\
        \
        ▼\

\
    ';
    appendHtml(container, elements);
  }

  return function TileEngine(x, y, xrange, yrange, parent=document.body, overrides) {
    let self = this;
    overrides = Object.assign({}, overrides);

    let elementNames = Object.assign(ELEMENT_NAMES, overrides.elementNames);
    createElements(parent, elementNames);
    const container = document.getElementById(elementNames.containerName);

    let textMessages = [];
    const textMessageFrame = document.getElementById(elementNames.frameName);
    const textMessage = document.getElementById(elementNames.messageName);
    const textIndicator = document.getElementById(elementNames.indicatorName)

    const controlWidth = container.clientWidth;
    const controlHeight = container.clientHeight;
    const context = CanvasControl.create("canvas", controlWidth, controlHeight, {}, elementNames.containerName, true);

    let backgroundLayers = [];
    let foregroundLayers = [];

    let paused = false;
    let mapLayers = [];
    let players = [];

    let actionExecutor = new ActionExecutor();
    actionExecutor.registerAction('toggleTile', (options, engine, player) => {
      let layers = mapLayers.filter((layer) => layer.zIndex === player.properties.zIndex);
      layers.forEach((layer) => {
        let currentTile = layer.getTile(options.target.x, options.target.y);
        let currentIndex = options.tiles.indexOf(currentTile);
        layer.setTile(options.target.x, options.target.y, options.tiles[(currentIndex + 1) % options.tiles.length]);
      })
    });

    //CanvasControl.fullScreen();
    const input = new CanvasInput(document, CanvasControl());

    input.mouse_action(function(coords) {
      if (paused) {
        drawMessages()
      } else {
        let player = players[0];
        let layer = player.properties.layer;
        let t = layer.applyMouseFocus(coords.x, coords.y);
        player.goTo(t.x, t.y);
        if (Math.abs(t.x - player.getTile().x) + Math.abs(t.y - player.getTile().y) === 1) {
          interact(player, t);
        }
      }
    });

    textMessageFrame.onclick = () => {
      if (paused) {
        drawMessages();
      }
    };

    input.keyboard(function(pressed, status) {
      let player = players[0];
      if (status) {
        if (paused) {
          if ([13, 32].indexOf(pressed) >= 0) {
            drawMessages();
          }
        } else {
          switch (pressed) {
            case 37: player.moveTo(player.getTile().x - 1, player.getTile().y); break;
            case 38: player.moveTo(player.getTile().x, player.getTile().y - 1); break;
            case 39: player.moveTo(player.getTile().x + 1, player.getTile().y); break;
            case 40: player.moveTo(player.getTile().x, player.getTile().y + 1); break;
            case 13: case 32: interact(player, player.getLookedAtTile()); break;
          }
        }
      }
    });

    let getActions = (player=null) => {
      let layers = mapLayers;
      if (player !== null) {
        layers = layers.filter((layer) => layer.zIndex === player.properties.zIndex);
      }
      let actions = [];
      layers.forEach((layer) => actions = actions.concat(layer.actions || []));
      return actions;
    }

    let interact = (player, tile) => {
      if (!player.isMoving()) {
        getActions(player)
          .filter((action) => action.type !== actionExecutor.TYPE_POSITIONAL)
          .filter((action) => action.x === tile.x && action.y == tile.y)
          .forEach((action) => actionExecutor.execute(action, self, player));
      }
    };

    let pause = () => {
      paused = true;
    }

    let unpause = () => {
      if (paused) {
        paused = false;
        draw();
      }
    }

    let clearText = () => {
      textMessages = [];
      textMessageFrame.classList.remove("in");
      textMessage.innerHTML = "";
      textIndicator.classList.remove("in");
      if (paused) {
        unpause();
      }
    }

    let displayText = (text) => {
      textMessages = textMessages.concat(text);
    }

    let drawMessages = () => {
      if (textMessages.length > 0) {
        pause();
        let text = textMessages.splice(0, 1)[0];
        textMessage.innerHTML = text;
        if (!("in" in textMessageFrame.classList)) {
          textMessageFrame.classList.add("in");
        }
        if (textMessages.length >= 1) {
          textIndicator.classList.add("in");
        } else {
          textIndicator.classList.remove("in");
        }
      } else {
        clearText();
      }
    }

    let drawLayers = (layers) => {
      for (let i = y; i < yrange; i++) {
        for (let j = x; j < xrange; j++) {
          layers.forEach((layer) => layer.draw(i, j));
        }
      }
    }

    let setPlayerLighting = (tile) => {
      mapLayers.forEach((layer) => layer.setLight(tile.x, tile.y));
    }

    let previousTime = 0;
    let timeToDraw = (time) => !overrides.lockedFrameRate || (time - previousTime) >= 1000 / overrides.lockedFrameRate;

    let draw = (time) => {
      if (!timeToDraw(time)) {
        requestAnimationFrame(draw);
      } else {
        previousTime = time;
        context.clearRect(0, 0, controlWidth, controlHeight);
        drawLayers(backgroundLayers);
        for (let player of players) {
          player.draw();
          player.move();
          setPlayerLighting(player.getTile());
        }
        drawLayers(foregroundLayers);
        drawMessages();
        if (!paused) {
          requestAnimationFrame(draw);
        }
      }
    }

    let initLayer = (layer) => {
      let mapLayer = new TileField(context, controlWidth, controlHeight);
      mapLayer.setup(layer);
      mapLayer.flip("horizontal");
      mapLayer.rotate("left");
      mapLayer.setLightmap(layer.lightmap);
      mapLayer = Object.assign(mapLayer, layer);
      return mapLayer;
    }

    let init = (map) => {
      let playerOptions = map.characters["player"];
      imgLoader([{
        graphics: [playerOptions.sprites],
        spritesheet: {
          width: playerOptions.width,
          height: playerOptions.height
        }
      }]).then((playerImages) => {
        mapLayers = map.layers.sort((a, b) => a.zIndex > b.zIndex).map(initLayer);
        backgroundLayers = mapLayers.filter((layer) => layer.zIndex < playerOptions.zIndex && layer.visible);
        foregroundLayers = mapLayers.filter((layer) => layer.zIndex >= playerOptions.zIndex && layer.visible);

        playerOptions.files = playerImages[0].files;
        playerOptions.layer = mapLayers[0];
        playerOptions.pathfindingLayer = mapLayers[playerOptions.pathfindingLayer];
        playerOptions.tileWidth = map.tileWidth;
        playerOptions.tileHeight = map.tileHeight;

        let player = new Player(context, playerOptions, playerOptions.x, playerOptions.y, pathfind);
        player.on("changeTile", (p, tile) => {
          getActions().filter((action) => action.type === actionExecutor.TYPE_POSITIONAL).forEach((action) => {
            if (action.x === tile.x && action.y === tile.y) {
              actionExecutor.execute(action, self, p);
            }
          })
        });

        players.push(player);

        draw();
      });
    }

    this.init = init;
    this.displayText = displayText;
    this.pause = pause;
    this.unpause = unpause;

    this.actionExecutor = actionExecutor;
  }
});<|endoftext|>


<commit_before>'use strict';

(function (angular, window) {
    angular
        .module('peoplePluginWidget')
        .controller('WidgetHomeCtrl', ['$scope', 'Buildfire', 'TAG_NAMES', 'COLLECTIONS', 'ERROR_CODE', "Location", '$sce', '$rootScope', 'DB',
            function ($scope, Buildfire, TAG_NAMES, COLLECTIONS, ERROR_CODE, Location, $sce, $rootScope, DB) {
                var MANUALLY = 'Manually',
                    OLDEST_TO_NEWEST = 'Oldest to Newest',
                    NEWEST_TO_OLDEST = 'Newest to Oldest',
                    FIRST_NAME_A_TO_Z = 'First Name A-Z',
                    FIRST_NAME_Z_TO_A = 'First Name Z-A',
                    LAST_NAME_A_TO_Z = 'Last Name A-Z',
                    LAST_NAME_Z_TO_A = 'Last Name Z-A',
                    _limit = 15,
                    searchOptions = {
                        filter: {"$json.fName": {"$regex": '/*'}},
                        skip: 0,
                        limit: _limit + 1 // the plus one is to check if there are any more
                    },
                    DEFAULT_LIST_LAYOUT = 'list-layout-1',
                    DEFAULT_ITEM_LAYOUT = 'item-layout-1';
                var PeopleInfo = new DB(TAG_NAMES.PEOPLE_INFO);
                var WidgetHome = this;
                WidgetHome.data = {};
                WidgetHome.busy = false;
                WidgetHome.sortingOptions = [
                    MANUALLY,
                    OLDEST_TO_NEWEST,
                    NEWEST_TO_OLDEST,
                    FIRST_NAME_A_TO_Z,
                    FIRST_NAME_Z_TO_A,
                    LAST_NAME_A_TO_Z,
                    LAST_NAME_Z_TO_A
                ];
                WidgetHome.defaults = {
                    DEFAULT_LIST_LAYOUT: 'list-layout-1',
                    DEFAULT_ITEM_LAYOUT: 'item-layout-1',
                    DEFAULT_SORT_OPTION: WidgetHome.sortingOptions[0]
                };
                //create new instance of buildfire carousel viewer
                var view = null;
                var currentItemLayout,
                    currentListLayout, currentSortOrder, currentBackgroundImage;
                WidgetHome.data = {};

                $rootScope.showHome = true;
                var getSearchOptions = function (value) {
                    switch (value) {
                        case OLDEST_TO_NEWEST:
                            searchOptions.sort = {"dateCreated": 1};
                            break;
                        case NEWEST_TO_OLDEST:
                            searchOptions.sort = {"dateCreated": -1};
                            break;
                        case FIRST_NAME_A_TO_Z:
                            searchOptions.sort = {"fName": 1};
                            break;
                        case FIRST_NAME_Z_TO_A:
                            searchOptions.sort = {"fName": -1};
                            break;
                        case LAST_NAME_A_TO_Z:
                            searchOptions.sort = {"lName": 1};
                            break;
                        case LAST_NAME_Z_TO_A:
                            searchOptions.sort = {"lName": -1};
                            break;
                        default :
                            searchOptions.sort = {"rank": 1};
                            break;
                    }
                    return searchOptions;
                };

                /*declare the device width heights*/
                $rootScope.deviceHeight = window.innerHeight;
                $rootScope.deviceWidth = window.innerWidth;
                $rootScope.backgroundImage = "";

                /*initialize the device width heights*/
                var initDeviceSize = function (callback) {
                    $rootScope.deviceHeight = window.innerHeight;
                    $rootScope.deviceWidth = window.innerWidth;
                    if (callback) {
                        if (WidgetHome.deviceWidth == 0 || WidgetHome.deviceHeight == 0) {
                            setTimeout(function () {
                                initDeviceSize(callback);
                            }, 500);
                        } else {
                            callback();
                            if (!$scope.$$phase && !$scope.$root.$$phase) {
                                $scope.$apply();
                            }
                        }
                    }
                };

                /* Get People details*/
                WidgetHome.getPeopleDetails = function (peopleId) {
                    Location.goTo("#/people/" + peopleId);
                };
                /*crop image on the basis of width heights*/
                WidgetHome.cropImage = function (url, settings) {
                    var options = {};
                    if (!url) {
                        return "";
                    }
                    else {
                        if (settings.height) {
                            options.height = settings.height;
                        }
                        if (settings.width) {
                            options.width = settings.width;
                        }
                        return Buildfire.imageLib.cropImage(url, options);
                    }
                };

                var init = function () {
                    var success = function (result) {
                            WidgetHome.data = result.data;
                            WidgetHome.data.design = WidgetHome.data.design || {};
                            if (WidgetHome.data.design) {
                                currentBackgroundImage = WidgetHome.data.design.backgroundImage;
                                currentItemLayout = WidgetHome.data.design.itemLayout;
                                currentListLayout = WidgetHome.data.design.listLayout;
                            }
                            if (WidgetHome.data.content) {
                                currentSortOrder = WidgetHome.data.content.sortBy;
                            }
                            $rootScope.backgroundImage = WidgetHome.data.design.backgroundImage ? WidgetHome.data.design.backgroundImage : "";
                        }
                        , error = function (err) {
                            if (err) {
                                console.error('Error while getting data', err);
                            }
                        };
                    PeopleInfo.get(TAG_NAMES.PEOPLE_INFO).then(success, error);
                };

                init();
                $scope.isDefined = function (item) {
                    return item.imageUrl !== undefined && item.imageUrl !== '';
                };
                WidgetHome.safeHtml = function (html) {
                    if (html)
                        return $sce.trustAsHtml(html);
                };
                WidgetHome.showDescription = function (description) {
                  var _retVal = false;
                  description = description.trim();
                  if(description && (description !== '

') && (description !== '

')) {
                    _retVal = true;
                  }
                  return _retVal;
                };
                var onUpdateCallback = function (event) {
                    console.log("*******************************************", event);
                    $scope.imagesUpdated = false;
                    $scope.$digest();
                    if (event && event.tag) {
                        if (event.data && WidgetHome.data.design && event.data.design) {
                            WidgetHome.data.design = event.data.design;
                        }
                        if (!WidgetHome.data.content) {
                            WidgetHome.data.content = {
                                sortBy: WidgetHome.defaults.DEFAULT_SORT_OPTION
                            }
                        }
                        if (!WidgetHome.data.design) {
                            WidgetHome.data.design = {
                                itemLayout: WidgetHome.defaults.DEFAULT_ITEM_LAYOUT,
                                listLayout: WidgetHome.defaults.DEFAULT_LIST_LAYOUT
                            };
                            currentItemLayout = WidgetHome.data.design.itemLayout;
                            currentListLayout = WidgetHome.data.design.listLayout;
                        }
                        switch (event.tag) {
                            case TAG_NAMES.PEOPLE:
                                var skip = searchOptions.skip || 0;
                                WidgetHome.busy = false;
                                WidgetHome.items = [];
                                if (searchOptions.skip && searchOptions.skip >= _limit) {
                                    searchOptions.limit = _limit + 1;
                                    var times = Math.floor(searchOptions.skip / _limit);
                                    searchOptions.skip = 0;
                                    WidgetHome.loadMore(true, Math.min(times - 1, 0));
                                } else {
                                    searchOptions.limit = _limit + 1;
                                    searchOptions.skip = 0;
                                    WidgetHome.loadMore();
                                }

                                break;
                            case TAG_NAMES.PEOPLE_INFO:
                                if (event.data) {
                                    if (event.data.design && event.data.design.itemLayout && currentItemLayout != event.data.design.itemLayout) {
                                        if (WidgetHome.items && WidgetHome.items.length) {
                                            var id = WidgetHome.items[0].id;
                                            $rootScope.showFeed = true;
                                            Location.goTo("#/people/" + id);
                                        }
                                    }
                                    else if (event.data.design && event.data.design.listLayout && currentListLayout != event.data.design.listLayout) {
                                        currentListLayout = event.data.design.listLayout;
                                        WidgetHome.data.design.listLayout = event.data.design.listLayout;
                                    }
                                    if (!WidgetHome.data.design)
                                        WidgetHome.data.design = {};
                                    currentItemLayout = WidgetHome.data.design.itemLayout || DEFAULT_ITEM_LAYOUT;

                                    if (event.data.content) {
                                        if (!WidgetHome.data)
                                            WidgetHome.data = {};
                                        WidgetHome.data.content = event.data.content;
                                        $scope.imagesUpdated = true;
                                    } else {
                                        $scope.imagesUpdated = false;
                                    }
                                    if (!event.data.design.backgroundImage) {
                                        $rootScope.backgroundImage = ""
                                    } else {
                                        $rootScope.backgroundImage = event.data.design.backgroundImage;
                                    }

                                    if (currentListLayout != WidgetHome.data.design.listLayout && view && WidgetHome.data.content.images) {
                                        view._destroySlider();
                                        view = null;
                                    }
                                    else {
                                        if (view) {
                                            view.loadItems(WidgetHome.data.content.images);
                                        }
                                    }
                                    if (event.data.content.sortBy && currentSortOrder != event.data.content.sortBy) {
                                        WidgetHome.data.content.sortBy = event.data.content.sortBy;
                                        WidgetHome.items = [];
                                        searchOptions.skip = 0;
                                        WidgetHome.busy = false;
                                        WidgetHome.loadMore();
                                    }
                                }
                                break;
                        }
                        $scope.$digest();
                        $rootScope.$apply();
                    }
                };
                Buildfire.datastore.onUpdate(onUpdateCallback);
                WidgetHome.noMore = false;
                WidgetHome.loadMore = function (multi, times) {
                    Buildfire.spinner.show();
                    console.log("loadMore");
                    if (WidgetHome.busy) {
                        return;
                    }
                    WidgetHome.busy = true;
                    if (WidgetHome.data && WidgetHome.data.content.sortBy) {
                        searchOptions = getSearchOptions(WidgetHome.data.content.sortBy);
                    }
                    Buildfire.datastore.search(searchOptions, TAG_NAMES.PEOPLE, function (err, result) {
                        console.log('-----------WidgetHome.loadMore-------------');
                        if (err) {
                            Buildfire.spinner.hide();
                            return console.error('-----------err in getting list-------------', err);
                        }
                        if (result.length <= _limit) {// to indicate there are more
                            WidgetHome.noMore = true;
                            Buildfire.spinner.hide();
                        } else {
                            result.pop();
                            searchOptions.skip = searchOptions.skip + _limit;
                            WidgetHome.noMore = false;
                        }
                        WidgetHome.items = WidgetHome.items ? WidgetHome.items.concat(result) : result;
                        WidgetHome.busy = false;
                        if (multi && !WidgetHome.noMore && times) {
                            times = times - 1;
                            WidgetHome.loadMore(multi, times);
                        }
                        Buildfire.spinner.hide();
                        $scope.$digest();
                    });
                };
                /**
                 * WidgetHome.resizeImage method to resize
                 * @param url
                 * @param width
                 * @param height
                 * @returns {null}
                 */
                WidgetHome.resizeImage = function (url, width, height) {
                    return Buildfire.imageLib.resizeImage(url, {
                        width: width,
                        height: height
                    });
                };
                $rootScope.$on("ROUTE_CHANGED", function (e, listLayout, itemLayout, background, data) {
                    WidgetHome.data = data
                    if (!WidgetHome.data.design)
                        WidgetHome.data.design = {};
                    if (!WidgetHome.data.content)
                        WidgetHome.data.content = {};
                    if (!view) {
                        view = new Buildfire.components.carousel.view("#carousel", []);
                    }
                    if (view && WidgetHome.data.content.images) {
                        view.loadItems(WidgetHome.data.content.images);
                    }
                    Buildfire.datastore.onUpdate(onUpdateCallback);
                });
                $scope.$on("$destroy", function () {
                    WidgetHome.onUpdateFn.clear();
                });
                $rootScope.$on("Carousel:LOADED", function () {
                    view = null;
                    if (!view) {
                        view = new Buildfire.components.carousel.view("#carousel", []);
                    }
                    if (WidgetHome.data.content && WidgetHome.data.content.images) {
                        view.loadItems(WidgetHome.data.content.images);
                    } else {
                        view.loadItems([]);
                    }
                });
            }]);
})(window.angular, window);
<commit_msg>Made required changes for pivotal issue: #115494479<commit_after>'use strict';

(function (angular, window) {
    angular
        .module('peoplePluginWidget')
        .controller('WidgetHomeCtrl', ['$scope', 'Buildfire', 'TAG_NAMES', 'COLLECTIONS', 'ERROR_CODE', "Location", '$sce', '$rootScope', 'DB',
            function ($scope, Buildfire, TAG_NAMES, COLLECTIONS, ERROR_CODE, Location, $sce, $rootScope, DB) {
                var MANUALLY = 'Manually',
                    OLDEST_TO_NEWEST = 'Oldest to Newest',
                    NEWEST_TO_OLDEST = 'Newest to Oldest',
                    FIRST_NAME_A_TO_Z = 'First Name A-Z',
                    FIRST_NAME_Z_TO_A = 'First Name Z-A',
                    LAST_NAME_A_TO_Z = 'Last Name A-Z',
                    LAST_NAME_Z_TO_A = 'Last Name Z-A',
                    _limit = 15,
                    searchOptions = {
                        filter: {"$json.fName": {"$regex": '/*'}},
                        skip: 0,
                        limit: _limit + 1 // the plus one is to check if there are any more
                    },
                    DEFAULT_LIST_LAYOUT = 'list-layout-1',
                    DEFAULT_ITEM_LAYOUT = 'item-layout-1';
                var PeopleInfo = new DB(TAG_NAMES.PEOPLE_INFO);
                var WidgetHome = this;
                WidgetHome.data = {};
                WidgetHome.busy = false;
                WidgetHome.sortingOptions = [
                    MANUALLY,
                    OLDEST_TO_NEWEST,
                    NEWEST_TO_OLDEST,
                    FIRST_NAME_A_TO_Z,
                    FIRST_NAME_Z_TO_A,
                    LAST_NAME_A_TO_Z,
                    LAST_NAME_Z_TO_A
                ];
                WidgetHome.defaults = {
                    DEFAULT_LIST_LAYOUT: 'list-layout-1',
                    DEFAULT_ITEM_LAYOUT: 'item-layout-1',
                    DEFAULT_SORT_OPTION: WidgetHome.sortingOptions[0]
                };
                //create new instance of buildfire carousel viewer
                var view = null;
                var currentItemLayout,
                    currentListLayout, currentSortOrder, currentBackgroundImage;
                WidgetHome.data = {};

                $rootScope.showHome = true;
                var getSearchOptions = function (value) {
                    switch (value) {
                        case OLDEST_TO_NEWEST:
                            searchOptions.sort = {"dateCreated": 1};
                            break;
                        case NEWEST_TO_OLDEST:
                            searchOptions.sort = {"dateCreated": -1};
                            break;
                        case FIRST_NAME_A_TO_Z:
                            searchOptions.sort = {"fName": 1};
                            break;
                        case FIRST_NAME_Z_TO_A:
                            searchOptions.sort = {"fName": -1};
                            break;
                        case LAST_NAME_A_TO_Z:
                            searchOptions.sort = {"lName": 1};
                            break;
                        case LAST_NAME_Z_TO_A:
                            searchOptions.sort = {"lName": -1};
                            break;
                        default :
                            searchOptions.sort = {"rank": 1};
                            break;
                    }
                    return searchOptions;
                };

                /*declare the device width heights*/
                $rootScope.deviceHeight = window.innerHeight;
                $rootScope.deviceWidth = window.innerWidth;
                $rootScope.backgroundImage = "";

                /*initialize the device width heights*/
                var initDeviceSize = function (callback) {
                    $rootScope.deviceHeight = window.innerHeight;
                    $rootScope.deviceWidth = window.innerWidth;
                    if (callback) {
                        if (WidgetHome.deviceWidth == 0 || WidgetHome.deviceHeight == 0) {
                            setTimeout(function () {
                                initDeviceSize(callback);
                            }, 500);
                        } else {
                            callback();
                            if (!$scope.$$phase && !$scope.$root.$$phase) {
                                $scope.$apply();
                            }
                        }
                    }
                };

                /* Get People details*/
                WidgetHome.getPeopleDetails = function (peopleId) {
                    Location.goTo("#/people/" + peopleId);
                };
                /*crop image on the basis of width heights*/
                WidgetHome.cropImage = function (url, settings) {
                    var options = {};
                    if (!url) {
                        return "";
                    }
                    else {
                        if (settings.height) {
                            options.height = settings.height;
                        }
                        if (settings.width) {
                            options.width = settings.width;
                        }
                        return Buildfire.imageLib.cropImage(url, options);
                    }
                };

                var init = function () {
                    var success = function (result) {
                            WidgetHome.data = result.data;
                            WidgetHome.data.design = WidgetHome.data.design || {};
                            if (WidgetHome.data.design) {
                                currentBackgroundImage = WidgetHome.data.design.backgroundImage;
                                currentItemLayout = WidgetHome.data.design.itemLayout;
                                currentListLayout = WidgetHome.data.design.listLayout;
                            }
                            if (WidgetHome.data.content) {
                                currentSortOrder = WidgetHome.data.content.sortBy;
                            }
                            $rootScope.backgroundImage = WidgetHome.data.design.backgroundImage ? WidgetHome.data.design.backgroundImage : "";
                        }
                        , error = function (err) {
                            if (err) {
                                console.error('Error while getting data', err);
                            }
                        };
                    PeopleInfo.get(TAG_NAMES.PEOPLE_INFO).then(success, error);
                };

                init();
                $scope.isDefined = function (item) {
                    return item.imageUrl !== undefined && item.imageUrl !== '';
                };
                WidgetHome.safeHtml = function (html) {
                    if (html) {
                        var $html = $('
', {html: html});
                        $html.find('iframe').each(function (index, element) {
                            var src = element.src;
                            console.log('element is: ', src, src.indexOf('http'));
                            src = src && src.indexOf('file://') != -1 ? src.replace('file://', 'http://') : src;
                            element.src = src && src.indexOf('http') != -1 ? src : 'http:' + src;
                        });
                        return $sce.trustAsHtml($html.html());
                    }
                };
                WidgetHome.showDescription = function (description) {
                  var _retVal = false;
                  description = description.trim();
                  if(description && (description !== '

') && (description !== '

')) {
                    _retVal = true;
                  }
                  return _retVal;
                };
                var onUpdateCallback = function (event) {
                    console.log("*******************************************", event);
                    $scope.imagesUpdated = false;
                    $scope.$digest();
                    if (event && event.tag) {
                        if (event.data && WidgetHome.data.design && event.data.design) {
                            WidgetHome.data.design = event.data.design;
                        }
                        if (!WidgetHome.data.content) {
                            WidgetHome.data.content = {
                                sortBy: WidgetHome.defaults.DEFAULT_SORT_OPTION
                            }
                        }
                        if (!WidgetHome.data.design) {
                            WidgetHome.data.design = {
                                itemLayout: WidgetHome.defaults.DEFAULT_ITEM_LAYOUT,
                                listLayout: WidgetHome.defaults.DEFAULT_LIST_LAYOUT
                            };
                            currentItemLayout = WidgetHome.data.design.itemLayout;
                            currentListLayout = WidgetHome.data.design.listLayout;
                        }
                        switch (event.tag) {
                            case TAG_NAMES.PEOPLE:
                                var skip = searchOptions.skip || 0;
                                WidgetHome.busy = false;
                                WidgetHome.items = [];
                                if (searchOptions.skip && searchOptions.skip >= _limit) {
                                    searchOptions.limit = _limit + 1;
                                    var times = Math.floor(searchOptions.skip / _limit);
                                    searchOptions.skip = 0;
                                    WidgetHome.loadMore(true, Math.min(times - 1, 0));
                                } else {
                                    searchOptions.limit = _limit + 1;
                                    searchOptions.skip = 0;
                                    WidgetHome.loadMore();
                                }

                                break;
                            case TAG_NAMES.PEOPLE_INFO:
                                if (event.data) {
                                    if (event.data.design && event.data.design.itemLayout && currentItemLayout != event.data.design.itemLayout) {
                                        if (WidgetHome.items && WidgetHome.items.length) {
                                            var id = WidgetHome.items[0].id;
                                            $rootScope.showFeed = true;
                                            Location.goTo("#/people/" + id);
                                        }
                                    }
                                    else if (event.data.design && event.data.design.listLayout && currentListLayout != event.data.design.listLayout) {
                                        currentListLayout = event.data.design.listLayout;
                                        WidgetHome.data.design.listLayout = event.data.design.listLayout;
                                    }
                                    if (!WidgetHome.data.design)
                                        WidgetHome.data.design = {};
                                    currentItemLayout = WidgetHome.data.design.itemLayout || DEFAULT_ITEM_LAYOUT;

                                    if (event.data.content) {
                                        if (!WidgetHome.data)
                                            WidgetHome.data = {};
                                        WidgetHome.data.content = event.data.content;
                                        $scope.imagesUpdated = true;
                                    } else {
                                        $scope.imagesUpdated = false;
                                    }
                                    if (!event.data.design.backgroundImage) {
                                        $rootScope.backgroundImage = ""
                                    } else {
                                        $rootScope.backgroundImage = event.data.design.backgroundImage;
                                    }

                                    if (currentListLayout != WidgetHome.data.design.listLayout && view && WidgetHome.data.content.images) {
                                        view._destroySlider();
                                        view = null;
                                    }
                                    else {
                                        if (view) {
                                            view.loadItems(WidgetHome.data.content.images);
                                        }
                                    }
                                    if (event.data.content.sortBy && currentSortOrder != event.data.content.sortBy) {
                                        WidgetHome.data.content.sortBy = event.data.content.sortBy;
                                        WidgetHome.items = [];
                                        searchOptions.skip = 0;
                                        WidgetHome.busy = false;
                                        WidgetHome.loadMore();
                                    }
                                }
                                break;
                        }
                        $scope.$digest();
                        $rootScope.$apply();
                    }
                };
                Buildfire.datastore.onUpdate(onUpdateCallback);
                WidgetHome.noMore = false;
                WidgetHome.loadMore = function (multi, times) {
                    Buildfire.spinner.show();
                    console.log("loadMore");
                    if (WidgetHome.busy) {
                        return;
                    }
                    WidgetHome.busy = true;
                    if (WidgetHome.data && WidgetHome.data.content.sortBy) {
                        searchOptions = getSearchOptions(WidgetHome.data.content.sortBy);
                    }
                    Buildfire.datastore.search(searchOptions, TAG_NAMES.PEOPLE, function (err, result) {
                        console.log('-----------WidgetHome.loadMore-------------');
                        if (err) {
                            Buildfire.spinner.hide();
                            return console.error('-----------err in getting list-------------', err);
                        }
                        if (result.length <= _limit) {// to indicate there are more
                            WidgetHome.noMore = true;
                            Buildfire.spinner.hide();
                        } else {
                            result.pop();
                            searchOptions.skip = searchOptions.skip + _limit;
                            WidgetHome.noMore = false;
                        }
                        WidgetHome.items = WidgetHome.items ? WidgetHome.items.concat(result) : result;
                        WidgetHome.busy = false;
                        if (multi && !WidgetHome.noMore && times) {
                            times = times - 1;
                            WidgetHome.loadMore(multi, times);
                        }
                        Buildfire.spinner.hide();
                        $scope.$digest();
                    });
                };
                /**
                 * WidgetHome.resizeImage method to resize
                 * @param url
                 * @param width
                 * @param height
                 * @returns {null}
                 */
                WidgetHome.resizeImage = function (url, width, height) {
                    return Buildfire.imageLib.resizeImage(url, {
                        width: width,
                        height: height
                    });
                };
                $rootScope.$on("ROUTE_CHANGED", function (e, listLayout, itemLayout, background, data) {
                    WidgetHome.data = data
                    if (!WidgetHome.data.design)
                        WidgetHome.data.design = {};
                    if (!WidgetHome.data.content)
                        WidgetHome.data.content = {};
                    if (!view) {
                        view = new Buildfire.components.carousel.view("#carousel", []);
                    }
                    if (view && WidgetHome.data.content.images) {
                        view.loadItems(WidgetHome.data.content.images);
                    }
                    Buildfire.datastore.onUpdate(onUpdateCallback);
                });
                $scope.$on("$destroy", function () {
                    WidgetHome.onUpdateFn.clear();
                });
                $rootScope.$on("Carousel:LOADED", function () {
                    view = null;
                    if (!view) {
                        view = new Buildfire.components.carousel.view("#carousel", []);
                    }
                    if (WidgetHome.data.content && WidgetHome.data.content.images) {
                        view.loadItems(WidgetHome.data.content.images);
                    } else {
                        view.loadItems([]);
                    }
                });
            }]);
})(window.angular, window);
<|endoftext|>


<commit_before>
var chai = require("chai");
var expect = chai.expect;

var RG = require("../battles.js");

var World = require("../src/world.js");

describe('World.Branch', function() {
    it('Contains a number of connected levels', function() {
        var nlevels = 4;
        var levels = [];
        var branch = new World.Branch();
        for (var i = 0; i < nlevels; i++) {
            levels.push(RG.FACT.createLevel("arena", 20, 20));
            branch.addLevel(levels[i]);
            expect(branch.hasLevel(levels[i])).to.equal(true);
        }

        branch.connectLevels();

        var stairs = levels[0].getStairs(levels[1]);
        expect(stairs === null).to.equal(false);
        stairs = levels[0].getStairs(levels[2]);
        expect(stairs === null).to.equal(true);
        var entrance = branch.getEntrance();
        expect(entrance === null).to.equal(false);

    });
});

var addLevelsToBranch = function(br, nLevels) {
    for (var i = 0; i < nLevels; i++) {
        var level = RG.FACT.createLevel("arena", 20, 20);
        br.addLevel(level);
    }
    br.connectLevels();
};

describe('World.Dungeon', function() {
    it('Contains a number of connected branches', function() {
        var dungeon = new World.Dungeon("DarkDungeon");

        var branches = [];
        for (var i = 0; i < 4; i++) {
            var branch = new World.Branch("branch" + i);
            addLevelsToBranch(branch, i+2);
            dungeon.addBranch(branch);
            branches.push(branch);
        }
        expect(branches[0].getDungeon()).to.equal(dungeon);

        dungeon.connectBranches(branches[0], branches[1], 1, 2);

    });
});

describe('World.AreaTile', function() {
    it('Contains a level and connects from sides to other tiles', function() {
        var testArea = new World.Area("TestArea", 1, 1);
        var areaTile = new World.AreaTile(0, 0, testArea);
        var tileLevel = RG.FACT.createLevel("arena", 20, 20);
        areaTile.setLevel(tileLevel);
        expect(areaTile.isNorthEdge()).to.equal(true);
        expect(areaTile.isSouthEdge()).to.equal(true);
        expect(areaTile.isEastEdge()).to.equal(true);
        expect(areaTile.isWestEdge()).to.equal(true);
        expect(areaTile.cols).to.equal(20);

        testArea = new World.Area("TestArea", 3, 3);
        var t1_1 = new World.AreaTile(1, 1, testArea);
        var l1_1 = RG.FACT.createLevel("arena", 20, 20);
        t1_1.setLevel(l1_1);
        expect(t1_1.isNorthEdge()).to.equal(false);
        expect(t1_1.isSouthEdge()).to.equal(false);
        expect(t1_1.isWestEdge()).to.equal(false);
        expect(t1_1.isEastEdge()).to.equal(false);

        // Create 2 more tiles, and test connect()
        var t2_1 = new World.AreaTile(2, 1, testArea);
        var l2_1 = RG.FACT.createLevel("arena", 20, 20);
        t2_1.setLevel(l2_1);
        var t1_2 = new World.AreaTile(1, 2, testArea);
        var l1_2 = RG.FACT.createLevel("arena", 20, 20);
        t1_2.setLevel(l1_2);
        t1_1.connect(t2_1, t1_2);
        var levels = [l1_1, l1_2, l2_1];
        for (var i = 0; i < levels.length; i++) {
            expect(levels[i].getStairs() === null).to.equal(false);
        }
    });
});

describe('World.Area', function() {
    it('Contains a number of connected tiles', function() {
        var area = new World.Area();
    });
});

describe('World.World', function() {
    it('Contains a number of dungeon and areas', function() {
        var conf = {
            nAreas: 2,
            nDungeons: 3,
        };
        var world = new World.World(conf);
    });
});
<commit_msg>Added check to unit test to see that stairs are created properly.<commit_after>
var chai = require("chai");
var expect = chai.expect;

var RG = require("../battles.js");

var World = require("../src/world.js");

describe('World.Branch', function() {
    it('Contains a number of connected levels', function() {
        var nlevels = 4;
        var levels = [];
        var branch = new World.Branch();
        for (var i = 0; i < nlevels; i++) {
            levels.push(RG.FACT.createLevel("arena", 20, 20));
            branch.addLevel(levels[i]);
            expect(branch.hasLevel(levels[i])).to.equal(true);
        }

        branch.connectLevels();

        var stairs = levels[0].getStairs(levels[1]);
        expect(stairs === null).to.equal(false);
        stairs = levels[0].getStairs(levels[2]);
        expect(stairs === null).to.equal(true);
        var entrance = branch.getEntrance();
        expect(entrance === null).to.equal(false);

    });
});

var addLevelsToBranch = function(br, nLevels) {
    for (var i = 0; i < nLevels; i++) {
        var level = RG.FACT.createLevel("arena", 20, 20);
        br.addLevel(level);
    }
    br.connectLevels();
};

describe('World.Dungeon', function() {
    it('Contains a number of connected branches', function() {
        var dungeon = new World.Dungeon("DarkDungeon");

        var branches = [];
        for (var i = 0; i < 4; i++) {
            var branch = new World.Branch("branch" + i);
            addLevelsToBranch(branch, i+2);
            dungeon.addBranch(branch);
            branches.push(branch);
        }
        expect(branches[0].getDungeon()).to.equal(dungeon);

        dungeon.connectBranches(branches[0], branches[1], 1, 2);

    });
});

describe('World.AreaTile', function() {
    it('Contains a level and connects from sides to other tiles', function() {
        var cols = 20;
        var rows = 20;

        var testArea = new World.Area("TestArea", 1, 1);
        var areaTile = new World.AreaTile(0, 0, testArea);
        var tileLevel = RG.FACT.createLevel("ruins", cols, rows);
        areaTile.setLevel(tileLevel);
        expect(areaTile.isNorthEdge()).to.equal(true);
        expect(areaTile.isSouthEdge()).to.equal(true);
        expect(areaTile.isEastEdge()).to.equal(true);
        expect(areaTile.isWestEdge()).to.equal(true);
        expect(areaTile.cols).to.equal(cols);

        testArea = new World.Area("TestArea", 3, 3);
        var t1_1 = new World.AreaTile(1, 1, testArea);
        var l1_1 = RG.FACT.createLevel("ruins", cols, rows);
        t1_1.setLevel(l1_1);
        expect(t1_1.isNorthEdge()).to.equal(false);
        expect(t1_1.isSouthEdge()).to.equal(false);
        expect(t1_1.isWestEdge()).to.equal(false);
        expect(t1_1.isEastEdge()).to.equal(false);

        // Create 2 more tiles, and test connect()
        var t2_1 = new World.AreaTile(2, 1, testArea);
        var l2_1 = RG.FACT.createLevel("ruins", cols, rows);
        t2_1.setLevel(l2_1);
        var t1_2 = new World.AreaTile(1, 2, testArea);
        var l1_2 = RG.FACT.createLevel("ruins", cols, rows);
        t1_2.setLevel(l1_2);
        t1_1.connect(t2_1, t1_2);

        expect(l2_1.getStairs(l1_1) === null).to.equal(false);
        expect(l1_1.getStairs(l2_1) === null).to.equal(false);
        expect(l1_2.getStairs(l1_1) === null).to.equal(false);
    });
});

describe('World.Area', function() {
    it('Contains a number of connected tiles', function() {
        var area = new World.Area("SwampArea");
    });
});

describe('World.World', function() {
    it('Contains a number of dungeon and areas', function() {
        var conf = {
            nAreas: 2,
            nDungeons: 3,
        };
        var world = new World.World(conf);
    });
});
<|endoftext|>


<commit_before>import {Router} from 'express'
import React from 'react'
import {renderToString} from 'react-dom/server'

import RepositoryView from '../../share/Repository'
import {renderFullPage} from '../utils'
import {getCommits} from '../service/repository'

export default new Router()
  .get('/dummy_user/:repoName', (req, res) => {
    const config = req.app.get('config')
    const repoName = req.params.repoName
    getCommits(config, repoName)
      .then(commits => {
        const props = {name: repoName, commits}
        const repositoryHTML = renderToString(React.createElement(RepositoryView, props))
        const fullHTML = renderFullPage(repositoryHTML, props, 'repository')
        res.end(fullHTML)
      })
      .catch(err => {
        console.log(err)
        res.status(503).end('503')
      })
  })
<commit_msg>Fix import filepath<commit_after>import {Router} from 'express'
import React from 'react'
import {renderToString} from 'react-dom/server'

import RepositoryView from '../../share/repository'
import {renderFullPage} from '../utils'
import {getCommits} from '../service/repository'

export default new Router()
  .get('/dummy_user/:repoName', (req, res) => {
    const config = req.app.get('config')
    const repoName = req.params.repoName
    getCommits(config, repoName)
      .then(commits => {
        const props = {name: repoName, commits}
        const repositoryHTML = renderToString(React.createElement(RepositoryView, props))
        const fullHTML = renderFullPage(repositoryHTML, props, 'repository')
        res.end(fullHTML)
      })
      .catch(err => {
        console.log(err)
        res.status(503).end('503')
      })
  })
<|endoftext|>


<commit_before>PykCharts.multiD.simple2x2 = function (options) {
    var that = this;
    var theme = new PykCharts.Configuration.Theme({});
    this.execute = function () {
    	that = new PykCharts.validation.processInputs(that, options, 'multiDimensionalCharts');
        PykCharts.scaleFunction(that);
        if(that.stop) {
            return;
        }

        if(that.mode === "default") {
            that.k.loading();
        }

        var multiDimensionalCharts = theme.multiDimensionalCharts,
            stylesheet = theme.stylesheet,
            optional = options.optional;
        that.axis_x_enable = "yes";
        that.axis_x_data_format = "string";
        that.axis_x_pointer_length = 0;
        that.axis_x_pointer_position = "bottom";
        that.axis_y_enable = "yes";
        that.axis_y_data_format = "string";
        that.axis_y_pointer_length = 0;

        that.data_sort_enable = "yes";
        that.data_sort_type = "numerically";

        that.chart_width = (that.chart_width < that.chart_height) ? that.chart_width : that.chart_height;
        that.chart_height = that.chart_width;
        that.reducedWidth = that.chart_width - that.chart_margin_left - that.chart_margin_right;
        that.reducedHeight = that.chart_height - that.chart_margin_top - that.chart_margin_bottom;
        that.axis_x_pointer_padding = (that.reducedHeight/2) + 10;
        that.axis_x_title_padding = that.axis_x_pointer_padding;
        that.axis_y_pointer_padding = (that.reducedWidth/2) + 10;
        that.axis_y_title_padding = that.axis_y_pointer_padding;

        that.executeData = function (data) {
            var validate = that.k.validator().validatingJSON(data),
                id = that.selector.substring(1,that.selector.length);
            if(that.stop || validate === false) {
                that.k.remove_loading_bar(id);
                return;
            }
            that.data = that.k.__proto__._groupBy("simple2x2",data);
            that.compare_data = that.k.__proto__._groupBy("simple2x2",data);
            that.k.remove_loading_bar(id);

            that.dataTransformation();
            that.render();
        }

        that.k.dataSourceFormatIdentification(options.data,that,"executeData");
    };

    this.dataTransformation = function () {
    	that.data = that.k.__proto__._sortData(that.data, "group", null, that);
    };

    this.render = function () {
        var id = that.selector.substring(1,that.selector.length),
            container_id = id + "_svg";

		if (that.mode === "default") {
			that.k.title()
                .backgroundColor(that)
                .export(that,"#"+that.container_id,"simple2x2")
                .emptyDiv()
                .subtitle();

            that.optionalFeatures()
                .svgContainer(container_id)
                .createChart()
                .axisContainer()
                .label();

            that.k/*.liveData(that)*/
                .tooltip()
                .createFooter()
                .lastUpdatedAt()
                .credits()
                .dataSource();

		}
        else {
            that.k.backgroundColor(that)
                .export(that,"#"+that.container_id,"simple2x2")
                .emptyDiv();

            that.optionalFeatures()
                .svgContainer(container_id)
                .createChart()
                .axisContainer()
                .labels();

            that.k.createFooter()
                .credits()
                .dataSource();

        }

        that.optionalFeatures().axisShift();

        that.k.exportSVG(that,"#"+container_id,"simple2x2Chart");

        var resize = that.k.resize(that.svgContainer);
        that.k.__proto__._ready(resize);
        window.addEventListener('resize', function(event){
            return that.k.resize(that.svgContainer);
        });
    };

    // this.refresh = function () {

    // };

    this.optionalFeatures = function () {
        var id = that.selector.substring(1,that.selector.length);
        var optional = {
            svgContainer: function (container_id) {
                document.getElementById(id).className = "PykCharts-twoD";
                that.svgContainer = d3.select(that.selector)
                    .append("svg:svg")
                    .attr({
                        "width": that.chart_width,
                        "height": that.chart_height,
                        "id": container_id,
                        "class": "svgcontainer",
                        "preserveAspectRatio": "xMinYMin",
                        "viewBox": "0 0 " + that.chart_width + " " + that.chart_height
                    });

                that.group = that.svgContainer.append("g")
                    .attr("id","simple2x2-group");
                return this;
            },
            axisContainer: function () {
                if(PykCharts['boolean'](that.axis_x_enable) || options.axis_x_title){
                    that.xGroup = that.group.append("g")
                            .attr({
                                "id": "xaxis",
                                "class": "x axis"
                            });
                }
                if(PykCharts['boolean'](that.axis_y_enable) || options.axis_y_title){
                    that.yGroup = that.group.append("g")
                        .attr({
                            "id": "yaxis",
                            "class": "y axis"
                        });
                }
                return this;
            },
            createChart: function () {
                var x_data=[], y_data=[],
                    y_range, x_range;
                that.x_tick_values = that.k.processXAxisTickValues(); //--- NOT REQD ???
                that.y_tick_values = that.k.processYAxisTickValues(); //--- NOT REQD ???

                if(that.axis_y_data_format === "string") {
                    y_data = ["Low", "High"];
                    y_range = [that.reducedHeight, 0];
                    that.yScale = that.k.scaleIdentification("ordinal",y_data,y_range,0.3);
                    that.extra_top_margin = (that.yScale.rangeBand() / 2);
                }

                if(that.axis_x_data_format === "string") {
                    x_data = y_data;
                    x_range = [0 ,that.reducedWidth];
                    that.xScale = that.k.scaleIdentification("ordinal",x_data,x_range,0.3);
                    that.extra_left_margin = (that.xScale.rangeBand()/2);
                }

                that.x_domain = that.xScale.domain();
                that.y_domain = that.yScale.domain();

                return this;
            },
            axisShift: function () {
                that.k.xAxis(that.svgContainer,that.xGroup,that.xScale,that.extra_left_margin,that.x_domain,that.x_tick_values)
                    .yAxis(that.svgContainer,that.yGroup,that.yScale,that.y_domain,that.y_tick_values)
                    .xAxisTitle(that.xGroup)
                    .yAxisTitle(that.yGroup);

                that.xGroup.attr("transform","translate("+that.chart_margin_left+"," + (that.chart_margin_top + that.reducedHeight/2) + ")");
                that.yGroup.attr("transform","translate(" + (that.chart_margin_left + that.reducedWidth/2) + ","+ that.chart_margin_top +")");

                var x_axis_title_height = d3.select(that.selector+" text.x-axis-title").node().getBBox().height;
                var y_axis_title_height = d3.select(that.selector+" text.y-axis-title").node().getBBox().height;
                d3.select(that.selector+" text.x-axis-title").attr("transform","translate(0,"+((that.reducedHeight/2) - (x_axis_title_height/3))+")");
                d3.select(that.selector+" text.y-axis-title").attr("transform","translate("+(-(that.reducedWidth/2))+",0) rotate(-90)");

                return this;
            },
            label: function () {
                var x_position, y_position=300;
                that.chart_label = that.group.selectAll(".simple2x2-label")
                    .data(that.data);

                that.chart_label.enter()
                    .append("text");

                that.chart_label.attr("class","simple2x2-label")
                    .text("");

                that.chart_label.text(function (d) {
                    return d.tooltip;
                })
                .style("visibility","hidden")
                .attr({
                    "x": function (d) {
                        switch (d.group) {
                            case 1: x_position = that.chart_margin_left + (3*(that.reducedWidth/4)) - (this.getBBox().width/2);
                                    break;
                            case 2: x_position = that.chart_margin_left + (that.reducedWidth/4) - (this.getBBox().width/2);
                                    break;
                            case 3: x_position = that.chart_margin_left + (that.reducedWidth/4) - (this.getBBox().width/2);
                                    break;
                            case 4: x_position = that.chart_margin_left + (3*(that.reducedWidth/4)) - (this.getBBox().width/2);
                                    break;
                        }
                        return x_position;
                    },
                    "y": function (d) {
                        switch (d.group) {
                            case 1: y_position = that.chart_margin_top + (that.reducedHeight/4) + (this.getBBox().height/3);
                                    break;
                            case 2: y_position = that.chart_margin_top + (that.reducedHeight/4) + (this.getBBox().height/3);
                                    break;
                            case 3: y_position = that.chart_margin_top + (3*(that.reducedHeight/4)) + (this.getBBox().height/3);
                                    break;
                            case 4: y_position = that.chart_margin_top + (3*(that.reducedHeight/4)) + (this.getBBox().height/3);
                                    break;
                        }
                        return y_position;
                    },
                    "fill": that.label_color
                })
                .style({
                    "font-weight": that.label_weight,
                    "font-size": that.label_size + "px",
                    "font-family": that.label_family,
                    "visibility": "visible"
                });

                that.chart_label.exit()
                    .remove();

                return this;
            }
        };
        return optional;
    };
};<commit_msg>outer boudary rect added<commit_after>PykCharts.multiD.simple2x2 = function (options) {
    var that = this;
    var theme = new PykCharts.Configuration.Theme({});
    this.execute = function () {
    	that = new PykCharts.validation.processInputs(that, options, 'multiDimensionalCharts');
        PykCharts.scaleFunction(that);
        if(that.stop) {
            return;
        }

        if(that.mode === "default") {
            that.k.loading();
        }

        var multiDimensionalCharts = theme.multiDimensionalCharts,
            stylesheet = theme.stylesheet,
            optional = options.optional;
        that.axis_x_enable = "yes";
        that.axis_x_data_format = "string";
        that.axis_x_pointer_length = 0;
        that.axis_x_pointer_position = "bottom";
        that.axis_y_enable = "yes";
        that.axis_y_data_format = "string";
        that.axis_y_pointer_length = 0;

        that.data_sort_enable = "yes";
        that.data_sort_type = "numerically";

        that.chart_width = (that.chart_width < that.chart_height) ? that.chart_width : that.chart_height;
        that.chart_height = that.chart_width;
        that.reducedWidth = that.chart_width - that.chart_margin_left - that.chart_margin_right;
        that.reducedHeight = that.chart_height - that.chart_margin_top - that.chart_margin_bottom;
        that.axis_x_pointer_padding = (that.reducedHeight/2) + 10;
        that.axis_x_title_padding = that.axis_x_pointer_padding;
        that.axis_y_pointer_padding = (that.reducedWidth/2) + 10;
        that.axis_y_title_padding = that.axis_y_pointer_padding;

        that.border_between_chart_elements_color = options.border_between_chart_elements_color || "#1d1d1d";

        that.executeData = function (data) {
            var validate = that.k.validator().validatingJSON(data),
                id = that.selector.substring(1,that.selector.length);
            if(that.stop || validate === false) {
                that.k.remove_loading_bar(id);
                return;
            }
            that.data = that.k.__proto__._groupBy("simple2x2",data);
            that.compare_data = that.k.__proto__._groupBy("simple2x2",data);
            that.k.remove_loading_bar(id);

            that.dataTransformation();
            that.render();
        }

        that.k.dataSourceFormatIdentification(options.data,that,"executeData");
    };

    this.dataTransformation = function () {
    	that.data = that.k.__proto__._sortData(that.data, "group", null, that);
    };

    this.render = function () {
        var id = that.selector.substring(1,that.selector.length),
            container_id = id + "_svg";

        that.border = new PykCharts.Configuration.border(that);

		if (that.mode === "default") {
			that.k.title()
                .backgroundColor(that)
                .export(that,"#"+that.container_id,"simple2x2")
                .emptyDiv()
                .subtitle();

            that.optionalFeatures()
                .svgContainer(container_id)
                .createChart()
                .axisContainer()
                .label();

            that.k/*.liveData(that)*/
                .tooltip()
                .createFooter()
                .lastUpdatedAt()
                .credits()
                .dataSource();

		}
        else {
            that.k.backgroundColor(that)
                .export(that,"#"+that.container_id,"simple2x2")
                .emptyDiv();

            that.optionalFeatures()
                .svgContainer(container_id)
                .createChart()
                .axisContainer()
                .labels();

            that.k.createFooter()
                .credits()
                .dataSource();

        }

        that.optionalFeatures().axisShift()
            .renderOuterBoundary();

        that.k.exportSVG(that,"#"+container_id,"simple2x2Chart");

        var resize = that.k.resize(that.svgContainer);
        that.k.__proto__._ready(resize);
        window.addEventListener('resize', function(event){
            return that.k.resize(that.svgContainer);
        });
    };

    // this.refresh = function () {

    // };

    this.optionalFeatures = function () {
        var id = that.selector.substring(1,that.selector.length);
        var optional = {
            svgContainer: function (container_id) {
                document.getElementById(id).className = "PykCharts-twoD";
                that.svgContainer = d3.select(that.selector)
                    .append("svg:svg")
                    .attr({
                        "width": that.chart_width,
                        "height": that.chart_height,
                        "id": container_id,
                        "class": "svgcontainer",
                        "preserveAspectRatio": "xMinYMin",
                        "viewBox": "0 0 " + that.chart_width + " " + that.chart_height
                    });

                that.group = that.svgContainer.append("g")
                    .attr("id","simple2x2-group");
                return this;
            },
            axisContainer: function () {
                if(PykCharts['boolean'](that.axis_x_enable) || options.axis_x_title){
                    that.xGroup = that.group.append("g")
                            .attr({
                                "id": "xaxis",
                                "class": "x axis"
                            });
                }
                if(PykCharts['boolean'](that.axis_y_enable) || options.axis_y_title){
                    that.yGroup = that.group.append("g")
                        .attr({
                            "id": "yaxis",
                            "class": "y axis"
                        });
                }
                return this;
            },
            createChart: function () {
                var x_data=[], y_data=[],
                    y_range, x_range;
                that.x_tick_values = that.k.processXAxisTickValues(); //--- NOT REQD ???
                that.y_tick_values = that.k.processYAxisTickValues(); //--- NOT REQD ???

                if(that.axis_y_data_format === "string") {
                    y_data = ["Low", "High"];
                    y_range = [that.reducedHeight, 0];
                    that.yScale = that.k.scaleIdentification("ordinal",y_data,y_range,0.3);
                    that.extra_top_margin = (that.yScale.rangeBand() / 2);
                }

                if(that.axis_x_data_format === "string") {
                    x_data = y_data;
                    x_range = [0 ,that.reducedWidth];
                    that.xScale = that.k.scaleIdentification("ordinal",x_data,x_range,0.3);
                    that.extra_left_margin = (that.xScale.rangeBand()/2);
                }

                that.x_domain = that.xScale.domain();
                that.y_domain = that.yScale.domain();

                return this;
            },
            axisShift: function () {
                that.k.xAxis(that.svgContainer,that.xGroup,that.xScale,that.extra_left_margin,that.x_domain,that.x_tick_values)
                    .yAxis(that.svgContainer,that.yGroup,that.yScale,that.y_domain,that.y_tick_values)
                    .xAxisTitle(that.xGroup)
                    .yAxisTitle(that.yGroup);

                that.xGroup.attr("transform","translate("+that.chart_margin_left+"," + (that.chart_margin_top + that.reducedHeight/2) + ")");
                that.yGroup.attr("transform","translate(" + (that.chart_margin_left + that.reducedWidth/2) + ","+ that.chart_margin_top +")");

                var x_axis_title_height = d3.select(that.selector+" text.x-axis-title").node().getBBox().height;
                var y_axis_title_height = d3.select(that.selector+" text.y-axis-title").node().getBBox().height;
                d3.select(that.selector+" text.x-axis-title").attr("transform","translate(0,"+((that.reducedHeight/2) - (x_axis_title_height/3))+")");
                d3.select(that.selector+" text.y-axis-title").attr("transform","translate("+(-(that.reducedWidth/2))+",0) rotate(-90)");

                return this;
            },
            renderOuterBoundary: function () {
                that.outer_boundary = that.group.append("svg:rect")
                    .attr({
                        "class": "simple2x2-outer-boundary",
                        "x": that.chart_margin_left,
                        "y": that.chart_margin_top,
                        "height": that.reducedHeight,
                        "width": that.reducedWidth,
                        "fill" : "none",
                        "stroke" : that.border.color(),
                        "stroke-width" : that.border.width(),
                        "stroke-dasharray": that.border.style()
                    });

                return this;
            },
            label: function () {
                var x_position, y_position=300;
                that.chart_label = that.group.selectAll(".simple2x2-label")
                    .data(that.data);

                that.chart_label.enter()
                    .append("text");

                that.chart_label.attr("class","simple2x2-label")
                    .text("");

                that.chart_label.text(function (d) {
                    return d.tooltip;
                })
                .style("visibility","hidden")
                .attr({
                    "x": function (d) {
                        switch (d.group) {
                            case 1: x_position = that.chart_margin_left + (3*(that.reducedWidth/4)) - (this.getBBox().width/2);
                                    break;
                            case 2: x_position = that.chart_margin_left + (that.reducedWidth/4) - (this.getBBox().width/2);
                                    break;
                            case 3: x_position = that.chart_margin_left + (that.reducedWidth/4) - (this.getBBox().width/2);
                                    break;
                            case 4: x_position = that.chart_margin_left + (3*(that.reducedWidth/4)) - (this.getBBox().width/2);
                                    break;
                        }
                        return x_position;
                    },
                    "y": function (d) {
                        switch (d.group) {
                            case 1: y_position = that.chart_margin_top + (that.reducedHeight/4) + (this.getBBox().height/3);
                                    break;
                            case 2: y_position = that.chart_margin_top + (that.reducedHeight/4) + (this.getBBox().height/3);
                                    break;
                            case 3: y_position = that.chart_margin_top + (3*(that.reducedHeight/4)) + (this.getBBox().height/3);
                                    break;
                            case 4: y_position = that.chart_margin_top + (3*(that.reducedHeight/4)) + (this.getBBox().height/3);
                                    break;
                        }
                        return y_position;
                    },
                    "fill": that.label_color
                })
                .style({
                    "font-weight": that.label_weight,
                    "font-size": that.label_size + "px",
                    "font-family": that.label_family,
                    "visibility": "visible"
                });

                that.chart_label.exit()
                    .remove();

                return this;
            }
        };
        return optional;
    };
};<|endoftext|>