<commit_before>var vanguard = {

    getTopologies: function(callback) {
        $.get('/vanguard/topologies', function(data) {
            callback(data.topologies || []);
        });
    },

    setTopology: function(name) {
        document.cookie = 'topology=' + name;
    },

    getTopology: function() {
        key = 'topology';

        regex = new RegExp("(?:^|.*;\\s*)" +
            escape('topology').replace(/[\-\.\+\*]/g, "\\$&") +
            "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*");

        return unescape(document.cookie.replace(regex, "$1"));
    },

    selectElement: function(id, values) {
        values.push('All');

        cookie = vanguard.getTopology();
        options = values.map(function(val, i) {
            return '<option' +
                (val == cookie ? ' selected="selected"' : '') +
                ' value="' + val + '">' + val + '</option>'
        }).join('');

        return '
Topology: <select id="' + id + '">' +
            options + '</select>
'
    }

};

$(document).ready(function() {

    vanguard.getTopologies(function(values) {
        id = 'topologies';

        $('#login p').replaceWith(vanguard.selectElement(id, values));

        $('#' + id).change(function() {
            vanguard.setTopology($(this).val());

            window.location.href = '';
        });
    });

});
<commit_msg>Ensuring topology selector is correctly ordered<commit_after>var vanguard = {

    getTopologies: function(callback) {
        $.get('/vanguard/topologies', function(data) {
            callback(data.topologies || []);
        });
    },

    setTopology: function(name) {
        document.cookie = 'topology=' + name;
    },

    getTopology: function() {
        key = 'topology';

        regex = new RegExp("(?:^|.*;\\s*)" +
            escape('topology').replace(/[\-\.\+\*]/g, "\\$&") +
            "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*");

        return unescape(document.cookie.replace(regex, "$1"));
    },

    selectElement: function(id, values) {
        values.push('All');

        cookie = vanguard.getTopology() || 'All';

        options = values.map(function(val, i) {
            return '<option' +
                (val == cookie ? ' selected="selected"' : '') +
                ' value="' + val + '">' + val + '</option>'
        }).reverse().join('');

        return '
Topology: <select id="' + id + '">' +
            options + '</select>
'
    }

};

$(document).ready(function() {

    vanguard.getTopologies(function(values) {
        id = 'topologies';

        $('#login p').replaceWith(vanguard.selectElement(id, values));

        $('#' + id).change(function() {
            vanguard.setTopology($(this).val());

            window.location.href = '';
        });
    });

});
<|endoftext|>


<commit_before>'use strict';
const Hue = require('./../../lib/client/hue');
const hue = new Hue();

const turnBrightnessUp = (hue, id) => {
  let brightness = hue.getGroupLightsBrightnessAsync(id);
  brightness += 25;
  if (brightness > 100) {
    brightness = 100;
  }
  return hue.setGroupLightsBrightness(id, brightness);
};

const turnBrightnessDown = (hue, id) => {
  let brightness = hue.getGroupLightsBrightnessAsync(id);
  brightness -= 25;
  if (brightness < 0) {
    brightness = 0;
  }
  return hue.setGroupLightsBrightness(id, brightness);
};

const turnOn = (hue, id) => {
  return hue.switchGroupLights(id, true);
};

const turnOff = (hue, id) => {
  return hue.switchGroupLights(id, false);
};

const setBrightness = (hue, id, brightness) => {
  return hue.setGroupLightsBrightness(id, parseInt(brightness));
};

module.exports = {run: function(state, config) {
  return new Promise(function(resolve, reject) {
    hue.connectToBridge().then(() => hue.getGroups()).then((groups) => {
      // append a potential "What room?" response
      state.setField('lightsAction',
        state.getField('lightsAction') + ' ' + state.getStatement()
      );
      const statement = state.getField('lightsAction');

      // figure out what zone we are going to talk to
      let currentGroup = undefined;

      // check to see if the zone was said in the statment
      for (let i = 0; i < groups.length; i++) {
        const re = new RegExp(groups[i].name, 'gi');
        if (statement.match(re)) {
          currentGroup = groups[i].id;
        }
      }

      if (!currentGroup) {
        state.setQuery('groupName');
        return resolve(state.setReply('What room?'));
      } else {
        // check for number to switch brightness
        if (statement.match(/\d+/g)) {
          const percent = statement.match(/\d+/g).pop();
          console.log(percent);
          setBrightness(hue, currentGroup, percent).then(() => {
            return resolve(state.setFinal(''));
          });
        }

        // turn off
        if (statement.match(/(off)/i)) {
          turnOff(hue, currentGroup).then(() => {
            return resolve(state.setFinal(''));
          });
        }

        // turn on
        if (statement.match(/(on)/i)) {
          turnOn(hue, currentGroup).then(() => {
            state.setFinal('');
            return resolve(state.setFinal(''));
          });
        }

        // turn down default 25 percent
        if (statement.match(/(down|lower|dim)/i)) {
          turnBrightnessDown(hue, currentGroup).then(() => {
            state.setFinal('');
            return resolve(state.setFinal(''));
          });
        }

        // turn up default 25 percent
        if (statement.match(/(up|higher|raise|brighter)/i)) {
          turnBrightnessUp(hue, currentGroup).then(() => {
            state.setFinal('');
            return resolve(state);
          });
        }
      }
    }).catch((response) => {
      return resolve(state.setFinal(response));
    });
  });
}};
<commit_msg>updated lights to use syncGroups and match on off on bool<commit_after>'use strict';
const Hue = require('./../../lib/client/hue');
const hue = new Hue();

const turnBrightnessUp = (hue, id) => {
  let brightness = hue.getGroupLightsBrightnessAsync(id);
  brightness += 25;
  if (brightness > 100) {
    brightness = 100;
  }
  return hue.setGroupLightsBrightness(id, brightness);
};

const turnBrightnessDown = (hue, id) => {
  let brightness = hue.getGroupLightsBrightnessAsync(id);
  brightness -= 25;
  if (brightness < 0) {
    brightness = 0;
  }
  return hue.setGroupLightsBrightness(id, brightness);
};

const turnOn = (hue, id) => {
  return hue.switchGroupLights(id, true);
};

const turnOff = (hue, id) => {
  return hue.switchGroupLights(id, false);
};

const setBrightness = (hue, id, brightness) => {
  return hue.setGroupLightsBrightness(id, parseInt(brightness));
};

module.exports = {run: function(state, config) {
  return new Promise(function(resolve, reject) {
    hue.connectToBridge().then(() => hue.syncGroups()).then((groups) => {
      // append a potential "What room?" response
      state.setField('lightsAction',
        state.getField('lightsAction') + ' ' + state.getStatement()
      );
      const statement = state.getField('lightsAction');

      // figure out what zone we are going to talk to
      let currentGroup = undefined;

      // check to see if the zone was said in the statment
      for (let i = 0; i < groups.length; i++) {
        const re = new RegExp(groups[i].name, 'gi');
        if (statement.match(re)) {
          currentGroup = groups[i].id;
        }
      }

      if (!currentGroup) {
        state.setQuery('groupName');
        return resolve(state.setReply('What room?'));
      } else {
        // check for number to switch brightness
        if (statement.match(/\d+/g)) {
          const percent = statement.match(/\d+/g).pop();
          console.log(percent);
          setBrightness(hue, currentGroup, percent).then(() => {
            return resolve(state.setFinal(''));
          });
        }

        // turn off
        if (statement.match(/(off|false)/i)) {
          turnOff(hue, currentGroup).then(() => {
            return resolve(state.setFinal(''));
          });
        }

        // turn on
        if (statement.match(/(on|true)/i)) {
          turnOn(hue, currentGroup).then(() => {
            state.setFinal('');
            return resolve(state.setFinal(''));
          });
        }

        // turn down default 25 percent
        if (statement.match(/(down|lower|dim)/i)) {
          turnBrightnessDown(hue, currentGroup).then(() => {
            state.setFinal('');
            return resolve(state.setFinal(''));
          });
        }

        // turn up default 25 percent
        if (statement.match(/(up|higher|raise|brighter)/i)) {
          turnBrightnessUp(hue, currentGroup).then(() => {
            state.setFinal('');
            return resolve(state);
          });
        }
      }
    }).catch((response) => {
      return resolve(state.setFinal(response));
    });
  });
}};
<|endoftext|>


<commit_before>( function() {
	/*
	 * Copyright 2008 WorldWide Conferencing, LLC
	 *
	 * Licensed under the Apache License, Version 2.0 (the "License"); you may
	 * not use this file except in compliance with the License. You may obtain a
	 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless
	 * required by applicable law or agreed to in writing, software distributed
	 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
	 * OR CONDITIONS OF ANY KIND, either express or implied. See the License for
	 * the specific language governing permissions and limitations under the
	 * License.
	 */

	window.lift$ = {
		buildIndex : function(on, indexName) {
			on[indexName] = {};
			var index = on[indexName];
			var x = 0;
			for (x = 2; x < arguments.length; x++) {
				var arg = arguments[x];
				var keyField = arg[1];
				var table = arg[0];
				var ta = on[table];
				var y = 0;
				for (y = 0; y < ta.length; y++) {
					var item = ta[y];
					var id = item[keyField];
					if (id) {
						index[id] = item;
					}
				}
			}
		},

		foreach : function(array, func) {
			var realFunc = func;
			if (func.apply == null) {
				eval("realFunc = function(p1) {return " + func + ";}");
			}

			for ( var x = 0; x < array.length; x++) {
				realFunc(array[x]);
			}
		},

		fold : function(array, initVal, func) {
			var realFunc = func;
			if (func.apply == null) {
				eval("realFunc = function(p1, p2) {return " + func + ";}");
			}
			lift$.foreach(array, function(e) {
				initVal = realFunc(initVal, e);
			});
			return initVal;
		},

		filter : function(array, func) {
			var realFunc = func;
			if (func.apply == null) {
				eval("realFunc = function(p1) {return " + func + ";}");
			}
			var ret = [];
			lift$.foreach(array, function(e) {
				if (realFunc(e)) {
					ret.push(e);
				}
				;
			});
			return ret;
		},

		alt : function(val, func, altVal) {
			if (val == false || val == null) {
				if (altVal.apply)
					return altVal();
				return altVal;
			} else if (lift$.isArray(val)) {
				return lift$.map(val, func);
			} else {
				var realFunc = func;
				if (func.apply == null) {
					eval("realFunc = function(p1) {return " + func + ";}");
				}
				return realFunc(val)
			}
		},

		map : function(array, func) {
			var realFunc = func;
			if (func.apply == null) {
				eval("realFunc = function(p1) {return " + func + ";}");
			}
			var ret = [];
			lift$.foreach(array, function(e) {
				ret.push(realFunc(e));
			});
			return ret;
		},

		flatMap : function(array, func) {
			var realFunc = func;
			if (func.apply == null) {
				eval("realFunc = function(p1) {return " + func + ";}");
			}
			var ret = [];
			lift$.foreach(array, function(e) {
				lift$.foreach(realFunc(e), function(v) {
					ret.push(v);
				});
			});
			return ret;
		},

		sort : function(array) {
			var func = null;
			if (arguments.length > 1) {
				func = arguments[1];
			}
			var realArray = [].concat(array);
			if (func == null) {
				return realArray.sort();
			} else {
				var realFunc = func;
				if (func.apply == null) {
					eval("realFunc = function(p1, p2) {return " + func + ";}");
				}
				return realArray.sort(realFunc);
			}
		},

		take : function(array, num) {
			var ret = [];
			for ( var x = 0; x < array.length && x < num; x++) {
				ret.push(array[x]);
			}

			return ret;
		},

		magicUpdate : function(holder, field, idField, toUpdate) {
			var f = function(array, item) {
				var na = lift$.filter(array, function(i) {
					return i[idField] != item[idField];
				});
				na.push(item);
				return na;
			}

			var ta = holder[field];

			if (lift$.isArray(toUpdate)) {
				lift$.foreach(toUpdate, function(i) {
					ta = f(ta, i);
				});
				holder[field] = ta;
			} else {
				holder[field] = f(ta, toUpdate);
			}

		},

		isArray : function(obj) {
			if (obj.constructor.toString().indexOf("Array") == -1)
				return false;
			else
				return true;
		},

		randomId : function() {
			var ret = "i";

			for ( var x = 0; x < 10; x++) {
				ret = ret + (Math.floor(Math.random() * 1000));
			}

			return ret;
		},

		swappable : function(visible, hidden) {
			if (visible == null) {
				visible = "";
			}

			if (hidden == null) {
				hidden = "";
			}

			if (visible.nodeType == null) {
				visible = document.createTextNode(visible.toString());
			}

			if (visible.nodeType != 1) {
				var tmp = document.createElement("span");
				tmp.appendChild(visible);
				visible = tmp;
			}

			if (hidden.nodeType == null) {
				hidden = document.createTextNode(hidden.toString());
			}

			if (hidden.nodeType != 1) {
				var tmp = document.createElement("span");
				tmp.appendChild(hidden);
				hidden = tmp;
			}

			visible.onclick = function() {
				jQuery(visible).hide();
				jQuery(hidden).show();
				jQuery(hidden).focus();
				jQuery(hidden).children(":input").focus();
				return false;
			};

			hidden.style.display = "none";

			var onblur = function() {
				jQuery(visible).show();
				jQuery(hidden).hide();
			}

			jQuery(hidden).blur(onblur);
			jQuery(hidden).children().blur(onblur);

			var df = document.createDocumentFragment();
			df.appendChild(visible);
			df.appendChild(hidden);
			return df;
		},

		formToJSON : function(formId) {
			qs = jQuery("#" + formId).serializeArray();
            ret = {};

            for (var i in qs) {
              var obj = qs[i];
              ret[obj.name] = obj.value;
            }
			return ret;
		}
	};

})();
<commit_msg>Fixed JSON serialization<commit_after>( function() {
	/*
	 * Copyright 2008 WorldWide Conferencing, LLC
	 *
	 * Licensed under the Apache License, Version 2.0 (the "License"); you may
	 * not use this file except in compliance with the License. You may obtain a
	 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless
	 * required by applicable law or agreed to in writing, software distributed
	 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
	 * OR CONDITIONS OF ANY KIND, either express or implied. See the License for
	 * the specific language governing permissions and limitations under the
	 * License.
	 */

	window.lift$ = {
		buildIndex : function(on, indexName) {
			on[indexName] = {};
			var index = on[indexName];
			var x = 0;
			for (x = 2; x < arguments.length; x++) {
				var arg = arguments[x];
				var keyField = arg[1];
				var table = arg[0];
				var ta = on[table];
				var y = 0;
				for (y = 0; y < ta.length; y++) {
					var item = ta[y];
					var id = item[keyField];
					if (id) {
						index[id] = item;
					}
				}
			}
		},

		foreach : function(array, func) {
			var realFunc = func;
			if (func.apply == null) {
				eval("realFunc = function(p1) {return " + func + ";}");
			}

			for ( var x = 0; x < array.length; x++) {
				realFunc(array[x]);
			}
		},

		fold : function(array, initVal, func) {
			var realFunc = func;
			if (func.apply == null) {
				eval("realFunc = function(p1, p2) {return " + func + ";}");
			}
			lift$.foreach(array, function(e) {
				initVal = realFunc(initVal, e);
			});
			return initVal;
		},

		filter : function(array, func) {
			var realFunc = func;
			if (func.apply == null) {
				eval("realFunc = function(p1) {return " + func + ";}");
			}
			var ret = [];
			lift$.foreach(array, function(e) {
				if (realFunc(e)) {
					ret.push(e);
				}
				;
			});
			return ret;
		},

		alt : function(val, func, altVal) {
			if (val == false || val == null) {
				if (altVal.apply)
					return altVal();
				return altVal;
			} else if (lift$.isArray(val)) {
				return lift$.map(val, func);
			} else {
				var realFunc = func;
				if (func.apply == null) {
					eval("realFunc = function(p1) {return " + func + ";}");
				}
				return realFunc(val)
			}
		},

		map : function(array, func) {
			var realFunc = func;
			if (func.apply == null) {
				eval("realFunc = function(p1) {return " + func + ";}");
			}
			var ret = [];
			lift$.foreach(array, function(e) {
				ret.push(realFunc(e));
			});
			return ret;
		},

		flatMap : function(array, func) {
			var realFunc = func;
			if (func.apply == null) {
				eval("realFunc = function(p1) {return " + func + ";}");
			}
			var ret = [];
			lift$.foreach(array, function(e) {
				lift$.foreach(realFunc(e), function(v) {
					ret.push(v);
				});
			});
			return ret;
		},

		sort : function(array) {
			var func = null;
			if (arguments.length > 1) {
				func = arguments[1];
			}
			var realArray = [].concat(array);
			if (func == null) {
				return realArray.sort();
			} else {
				var realFunc = func;
				if (func.apply == null) {
					eval("realFunc = function(p1, p2) {return " + func + ";}");
				}
				return realArray.sort(realFunc);
			}
		},

		take : function(array, num) {
			var ret = [];
			for ( var x = 0; x < array.length && x < num; x++) {
				ret.push(array[x]);
			}

			return ret;
		},

		magicUpdate : function(holder, field, idField, toUpdate) {
			var f = function(array, item) {
				var na = lift$.filter(array, function(i) {
					return i[idField] != item[idField];
				});
				na.push(item);
				return na;
			}

			var ta = holder[field];

			if (lift$.isArray(toUpdate)) {
				lift$.foreach(toUpdate, function(i) {
					ta = f(ta, i);
				});
				holder[field] = ta;
			} else {
				holder[field] = f(ta, toUpdate);
			}

		},

		isArray : function(obj) {
			if (obj.constructor.toString().indexOf("Array") == -1)
				return false;
			else
				return true;
		},

		randomId : function() {
			var ret = "i";

			for ( var x = 0; x < 10; x++) {
				ret = ret + (Math.floor(Math.random() * 1000));
			}

			return ret;
		},

		swappable : function(visible, hidden) {
			if (visible == null) {
				visible = "";
			}

			if (hidden == null) {
				hidden = "";
			}

			if (visible.nodeType == null) {
				visible = document.createTextNode(visible.toString());
			}

			if (visible.nodeType != 1) {
				var tmp = document.createElement("span");
				tmp.appendChild(visible);
				visible = tmp;
			}

			if (hidden.nodeType == null) {
				hidden = document.createTextNode(hidden.toString());
			}

			if (hidden.nodeType != 1) {
				var tmp = document.createElement("span");
				tmp.appendChild(hidden);
				hidden = tmp;
			}

			visible.onclick = function() {
				jQuery(visible).hide();
				jQuery(hidden).show();
				jQuery(hidden).focus();
				jQuery(hidden).children(":input").focus();
				return false;
			};

			hidden.style.display = "none";

			var onblur = function() {
				jQuery(visible).show();
				jQuery(hidden).hide();
			}

			jQuery(hidden).blur(onblur);
			jQuery(hidden).children().blur(onblur);

			var df = document.createDocumentFragment();
			df.appendChild(visible);
			df.appendChild(hidden);
			return df;
		},

		formToJSON : function(formId) {
			qs = jQuery("#" + formId).serializeArray();
            ret = {};

            for (var i in qs) {
              var obj = qs[i];
              var cur = ret[obj.name];
              if (!cur) {
                ret[obj.name] = obj.value;
              } else if (lift$.isArray(cur)) {
                  cur.push(obj.value);
              } else {
                  ret[obj.name] = [cur, obj.value];
              }
            }
			return ret;
		}
	};

})();
<|endoftext|>


<commit_before>module.exports = {
	before: function (browser) {
		browser.app = browser.page.app();
		browser.signinPage = browser.page.signin();
		browser.listPage = browser.page.list();
		browser.itemPage = browser.page.item();
		browser.initialFormPage = browser.page.initialForm();

		browser.app.navigate();
		browser.app.waitForElementVisible('@signinScreen');

		browser.signinPage.signin();
		browser.app.waitForElementVisible('@homeScreen');
	},
	after: function (browser) {
		browser.app
			.signout();
		browser
			.end();
	},
	'Text field can be created via the initial modal': function (browser) {
		browser.app
			.click('@fieldsMenu')
			.waitForElementVisible('@listScreen')
			.click('@textsFieldsSubmenu')
			.waitForElementVisible('@listScreen');

		browser.listPage
			.click('@createFirstItemButton');

		browser.app
			.waitForElementVisible('@initialFormScreen');

		browser.initialFormPage.section.form.section.textList.section.name
			.fillInput({value: 'Text Field Test 1'});

		browser.initialFormPage.section.form.section.textList.section.name
			.verifyInput({value: 'Text Field Test 1'});

		browser.initialFormPage.section.form.section.textList.section.fieldA
			.fillInput({value: 'Text Field Test Text 1'});

		browser.initialFormPage.section.form
			.click('@createButton');

		browser.app
			.waitForElementVisible('@itemScreen');

		browser.itemPage
			.expect.element('@flashMessage')
			.text.to.equal('New Text Text Field Test 1 created.');

		browser.itemPage.section.form.section.textList.section.name
			.verifyInput({value: 'Text Field Test 1'});
	},
	'Text field can be created via the edit form': function (browser) {
		browser.itemPage.section.form.section.textList.section.name
			.fillInput({value: 'Text Field Test 2'});

		browser.itemPage.section.form.section.textList.section.fieldA
			.fillInput({value: 'Text Field Test Text 2'});

		browser.itemPage.section.form
			.click('@saveButton');

		browser.itemPage
			.waitForElementVisible('@flashMessage');

		browser.itemPage
			.expect.element('@flashMessage').text.to.equal('Your changes have been saved.');

		browser.itemPage.section.form.section.textList.section.name
			.verifyInput({value: 'Text Field Test 2'});

		browser.itemPage.section.form.section.textList.section.fieldA
			.verifyInput({value: 'Text Field Test Text 2'});
	},
};
<commit_msg>testing(e2e): better wording<commit_after>module.exports = {
	before: function (browser) {
		browser.app = browser.page.app();
		browser.signinPage = browser.page.signin();
		browser.listPage = browser.page.list();
		browser.itemPage = browser.page.item();
		browser.initialFormPage = browser.page.initialForm();

		browser.app.navigate();
		browser.app.waitForElementVisible('@signinScreen');

		browser.signinPage.signin();
		browser.app.waitForElementVisible('@homeScreen');
	},
	after: function (browser) {
		browser.app
			.signout();
		browser
			.end();
	},
	'Text field can be filled via the initial modal': function (browser) {
		browser.app
			.click('@fieldsMenu')
			.waitForElementVisible('@listScreen')
			.click('@textsFieldsSubmenu')
			.waitForElementVisible('@listScreen');

		browser.listPage
			.click('@createFirstItemButton');

		browser.app
			.waitForElementVisible('@initialFormScreen');

		browser.initialFormPage.section.form.section.textList.section.name
			.fillInput({value: 'Text Field Test 1'});

		browser.initialFormPage.section.form.section.textList.section.name
			.verifyInput({value: 'Text Field Test 1'});

		browser.initialFormPage.section.form.section.textList.section.fieldA
			.fillInput({value: 'Text Field Test Text 1'});

		browser.initialFormPage.section.form
			.click('@createButton');

		browser.app
			.waitForElementVisible('@itemScreen');

		browser.itemPage
			.expect.element('@flashMessage')
			.text.to.equal('New Text Text Field Test 1 created.');

		browser.itemPage.section.form.section.textList.section.name
			.verifyInput({value: 'Text Field Test 1'});
	},
	'Text field can be filled via the edit form': function (browser) {
		browser.itemPage.section.form.section.textList.section.name
			.fillInput({value: 'Text Field Test 2'});

		browser.itemPage.section.form.section.textList.section.fieldA
			.fillInput({value: 'Text Field Test Text 2'});

		browser.itemPage.section.form
			.click('@saveButton');

		browser.itemPage
			.waitForElementVisible('@flashMessage');

		browser.itemPage
			.expect.element('@flashMessage').text.to.equal('Your changes have been saved.');

		browser.itemPage.section.form.section.textList.section.name
			.verifyInput({value: 'Text Field Test 2'});

		browser.itemPage.section.form.section.textList.section.fieldA
			.verifyInput({value: 'Text Field Test Text 2'});
	},
};
<|endoftext|>


<commit_before>
define([
    'flight/lib/component',
    'data',
    './image/image',
    '../properties',
    '../withTypeContent',
    '../withHighlighting',
    'tpl!./entity',
    'tpl!./relationships',
    'tpl!util/alert',
    'util/vertexList/list',
    'detail/dropdowns/propertyForm/propForm',
    'service/ontology',
    'service/vertex',
    'sf'
], function(defineComponent,
    appData,
    Image,
    Properties,
    withTypeContent,
    withHighlighting,
    template,
    relationshipsTemplate,
    alertTemplate,
    VertexList,
    PropertyForm,
    OntologyService,
    VertexService,
    sf) {
    'use strict';

    var ontologyService = new OntologyService();
    var vertexService = new VertexService();

    return defineComponent(Entity, withTypeContent, withHighlighting);

    function Entity(withDropdown) {

        this.defaultAttrs({
            glyphIconSelector: '.entity-glyphIcon',
            propertiesSelector: '.properties',
            relationshipsSelector: '.relationships',
            titleSelector: '.entity-title'
        });

        this.after('teardown', function() {
            this.$node.off('click.paneClick');
        });

        this.after('initialize', function() {
            var self = this;
            this.$node.on('click.paneClick', this.onPaneClicked.bind(this));

            this.on(document, 'verticesUpdated', this.onVerticesUpdated);
            this.on('infiniteScrollRequest', this.handleReferenceLoadingRequest);

            self.loadEntity();
        });

        this.onVerticesUpdated = function(event, data) {
            var self = this;

            data.vertices.forEach(function(vertex) {
                if (vertex.id === self.attr.data.id) {
                    self.select('titleSelector').html(vertex.properties.title.value);
                }
            });
        };

        this.loadEntity = function() {
            var self = this;

            this.handleCancelling(appData.refresh(this.attr.data))
                .done(function(vertex) {

                    self.$node.html(template({
                        vertex: vertex,
                        fullscreenButton: self.fullscreenButton([vertex.id]),
                        auditsButton: self.auditsButton()
                    }));

                    Image.attachTo(self.select('glyphIconSelector'), {
                        data: vertex,
                        service: vertexService
                    });

                   Properties.attachTo(self.select('propertiesSelector'), {
                       data: vertex
                   });

                   self.updateEntityAndArtifactDraggables();

                    $.when(
                            self.handleCancelling(ontologyService.relationships()),
                            self.handleCancelling(vertexService.getVertexRelationships(vertex.id))
                        )
                        .fail(function() {
                            self.select('relationshipsSelector').html(alertTemplate({
                                error: 'Unable to load relationships'
                            }));
                        })
                        .done(self.loadRelationships.bind(self, vertex));
                });
        };

        this.loadRelationships = function(vertex, ontologyRelationships, vertexRelationships) {
            var self = this,
                totalReferences = vertexRelationships[0].totalReferences,
                allRelationships = vertexRelationships[0].relationships,
                relationships = [];

            // Create source/dest/other properties
            allRelationships.forEach(function(r) {
                if (ontologyRelationships.byTitle[r.relationship.label]) {
                    r.displayLabel = ontologyRelationships.byTitle[r.relationship.label].displayName;
                    var src, dest, other;
                    if (vertex.id == r.relationship.sourceVertexId) {
                        src = vertex;
                        dest = other = r.vertex;
                    } else {
                        src = other = r.vertex;
                        dest = vertex;
                    }

                    r.vertices = {
                        src: src,
                        dest: dest,
                        other: other,
                        classes: {
                            src: self.classesForVertex(src),
                            dest: self.classesForVertex(dest),
                            other: self.classesForVertex(other)
                        }
                    };

                    r.relationshipInfo = {
                        id: r.relationship.id,
                        properties: $.extend({}, r.relationship.properties, {
                            _conceptType: 'relationship',
                            id: r.relationship.id,
                            relationshipType: r.relationship.label,
                            source: r.relationship.sourceVertexId,
                            target: r.relationship.destVertexId
                        })
                    };
                    relationships.push(r);
                }
            });

            var groupedByType = _.groupBy(relationships, function(r) {

                // Has Entity are collected into references (no matter
                // relationship direction
                if (r.relationship.label === 'rawHasEntity') {
                    return 'references';
                }

                return r.displayLabel;
            });
            var sortedKeys = Object.keys(groupedByType);
            sortedKeys.sort(function(a,b) {

                // If in references group sort by the title
                if (a === b && a === 'references') {
                    return defaultSort(a.vertex.properties.title.value, b.vertex.properties.title.value);
                }

                // Specifies the special group sort order
                var groups = { references:1 };
                if (groups[a] && groups[b]) {
                    return defaultSort(groups[a], groups[b]);
                } else if (groups[a]) {
                    return 1;
                } else if (groups[b]) {
                    return -1;
                }

                return defaultSort(a, b);

                function defaultSort(x,y) {
                    return x === y ? 0 : x < y ? -1 : 1;
                }
            });

            var $rels = self.select('relationshipsSelector');
            $rels.html(relationshipsTemplate({
                relationshipsGroupedByType: groupedByType,
                sortedKeys: sortedKeys
            }));

            VertexList.attachTo($rels.find('.references'), {
                vertices: _.map(groupedByType.references, function(r) {
                    return r.vertices.other;
                }),
                infiniteScrolling: (groupedByType.references && groupedByType.references.length) > 0,
                total: totalReferences
            });
        };

        this.handleReferenceLoadingRequest = function(evt, data) {
            var self = this;

            this.handleCancelling(vertexService.getVertexRelationships(this.attr.data.id, data.paging))
                .done(function(response) {
                    var relationships = response.relationships,
                        total = response.totalReferences;

                    self.trigger(
                        self.select('relationshipsSelector').find('.references'),
                        'addInfiniteVertices',
                        {
                            vertices: _.pluck(relationships, 'vertex'),
                            total: total
                        }
                    );

                });
        };

        this.onPaneClicked = function(evt) {
            var $target = $(evt.target);

            if (!$target.is('.add-new-properties') && $target.parents('.underneath').length === 0) {
                PropertyForm.teardownAll();
            }

            if ($target.is('.entity, .artifact')) {
                var id = $target.data('vertexId');
                this.trigger('selectObjects', { vertices:[appData.vertex(id)] });
                evt.stopPropagation();
            } else if ($target.is('.relationship')) {
                var info = $target.data('info');
                this.trigger('selectObjects', { vertices:[info] });
                evt.stopPropagation();
            }
        };

    }
});

<commit_msg>Fix js error when dragging relationship from detail pane and back<commit_after>
define([
    'flight/lib/component',
    'data',
    './image/image',
    '../properties',
    '../withTypeContent',
    '../withHighlighting',
    'tpl!./entity',
    'tpl!./relationships',
    'tpl!util/alert',
    'util/vertexList/list',
    'detail/dropdowns/propertyForm/propForm',
    'service/ontology',
    'service/vertex',
    'sf'
], function(defineComponent,
    appData,
    Image,
    Properties,
    withTypeContent,
    withHighlighting,
    template,
    relationshipsTemplate,
    alertTemplate,
    VertexList,
    PropertyForm,
    OntologyService,
    VertexService,
    sf) {
    'use strict';

    var ontologyService = new OntologyService();
    var vertexService = new VertexService();

    return defineComponent(Entity, withTypeContent, withHighlighting);

    function Entity(withDropdown) {

        this.defaultAttrs({
            glyphIconSelector: '.entity-glyphIcon',
            propertiesSelector: '.properties',
            relationshipsSelector: '.relationships',
            titleSelector: '.entity-title'
        });

        this.after('teardown', function() {
            this.$node.off('click.paneClick');
        });

        this.after('initialize', function() {
            var self = this;
            this.$node.on('click.paneClick', this.onPaneClicked.bind(this));

            this.on(document, 'verticesUpdated', this.onVerticesUpdated);
            this.on('infiniteScrollRequest', this.handleReferenceLoadingRequest);

            self.loadEntity();
        });

        this.onVerticesUpdated = function(event, data) {
            var self = this;

            data.vertices.forEach(function(vertex) {
                if (vertex.id === self.attr.data.id) {
                    self.select('titleSelector').html(vertex.properties.title.value);
                }
            });
        };

        this.loadEntity = function() {
            var self = this;

            this.handleCancelling(appData.refresh(this.attr.data))
                .done(function(vertex) {

                    self.$node.html(template({
                        vertex: vertex,
                        fullscreenButton: self.fullscreenButton([vertex.id]),
                        auditsButton: self.auditsButton()
                    }));

                    Image.attachTo(self.select('glyphIconSelector'), {
                        data: vertex,
                        service: vertexService
                    });

                   Properties.attachTo(self.select('propertiesSelector'), {
                       data: vertex
                   });

                   self.updateEntityAndArtifactDraggables();

                    $.when(
                            self.handleCancelling(ontologyService.relationships()),
                            self.handleCancelling(vertexService.getVertexRelationships(vertex.id))
                        )
                        .fail(function() {
                            self.select('relationshipsSelector').html(alertTemplate({
                                error: 'Unable to load relationships'
                            }));
                        })
                        .done(self.loadRelationships.bind(self, vertex));
                });
        };

        this.loadRelationships = function(vertex, ontologyRelationships, vertexRelationships) {
            var self = this,
                totalReferences = vertexRelationships[0].totalReferences,
                allRelationships = vertexRelationships[0].relationships,
                relationships = [];

            // Create source/dest/other properties
            allRelationships.forEach(function(r) {
                if (ontologyRelationships.byTitle[r.relationship.label]) {
                    r.displayLabel = ontologyRelationships.byTitle[r.relationship.label].displayName;
                    var src, dest, other;
                    if (vertex.id == r.relationship.sourceVertexId) {
                        src = vertex;
                        dest = other = r.vertex;
                    } else {
                        src = other = r.vertex;
                        dest = vertex;
                    }

                    r.vertices = {
                        src: src,
                        dest: dest,
                        other: other,
                        classes: {
                            src: self.classesForVertex(src),
                            dest: self.classesForVertex(dest),
                            other: self.classesForVertex(other)
                        }
                    };

                    r.relationshipInfo = {
                        id: r.relationship.id,
                        properties: $.extend({}, r.relationship.properties, {
                            _conceptType: 'relationship',
                            id: r.relationship.id,
                            relationshipType: r.relationship.label,
                            source: r.relationship.sourceVertexId,
                            target: r.relationship.destVertexId
                        })
                    };
                    relationships.push(r);
                }
            });

            var groupedByType = _.groupBy(relationships, function(r) {

                // Has Entity are collected into references (no matter
                // relationship direction
                if (r.relationship.label === 'rawHasEntity') {
                    return 'references';
                }

                return r.displayLabel;
            });
            var sortedKeys = Object.keys(groupedByType);
            sortedKeys.sort(function(a,b) {

                // If in references group sort by the title
                if (a === b && a === 'references') {
                    return defaultSort(a.vertex.properties.title.value, b.vertex.properties.title.value);
                }

                // Specifies the special group sort order
                var groups = { references:1 };
                if (groups[a] && groups[b]) {
                    return defaultSort(groups[a], groups[b]);
                } else if (groups[a]) {
                    return 1;
                } else if (groups[b]) {
                    return -1;
                }

                return defaultSort(a, b);

                function defaultSort(x,y) {
                    return x === y ? 0 : x < y ? -1 : 1;
                }
            });

            var $rels = self.select('relationshipsSelector');
            $rels.html(relationshipsTemplate({
                relationshipsGroupedByType: groupedByType,
                sortedKeys: sortedKeys
            }));

            VertexList.attachTo($rels.find('.references'), {
                vertices: _.map(groupedByType.references, function(r) {
                    return r.vertices.other;
                }),
                infiniteScrolling: (groupedByType.references && groupedByType.references.length) > 0,
                total: totalReferences
            });
        };

        this.handleReferenceLoadingRequest = function(evt, data) {
            var self = this;

            this.handleCancelling(vertexService.getVertexRelationships(this.attr.data.id, data.paging))
                .done(function(response) {
                    var relationships = response.relationships,
                        total = response.totalReferences;

                    self.trigger(
                        self.select('relationshipsSelector').find('.references'),
                        'addInfiniteVertices',
                        {
                            vertices: _.pluck(relationships, 'vertex'),
                            total: total
                        }
                    );

                });
        };

        this.onPaneClicked = function(evt) {
            var $target = $(evt.target);

            if (!$target.is('.add-new-properties') && $target.parents('.underneath').length === 0) {
                PropertyForm.teardownAll();
            }

            if ($target.is('.entity, .artifact')) {
                var id = $target.data('vertexId');
                this.trigger('selectObjects', { vertices:[appData.vertex(id)] });
                evt.stopPropagation();
            } else if ($target.is('.relationship')) {
                var info = $target.data('info');
                if (info) {
                    this.trigger('selectObjects', { vertices:[info] });
                }
                evt.stopPropagation();
            }
        };

    }
});

<|endoftext|>


<commit_before>
define([
    'flight/lib/component',
    'tpl!./form',
    'tpl!./shareRow',
    'tpl!./permissions',
    'service/user',
    'service/workspace'
], function(
    defineComponent,
    template,
    shareRowTemplate,
    permissionsTemplate,
    UserService,
    WorkspaceService) {
    'use strict';

    return defineComponent(Form);

    function Form() {

        this.userService = new UserService();
        this.workspaceService = new WorkspaceService();

        this.defaultAttrs({
            titleSelector: '.workspace-title',
            shareListSelector: '.share-list',
            shareHeader: '.share-header',
            shareFormSelector: '.share-form',
            userSearchSelector: '.share-form input',
            permissionsSelector: '.permissions',
            permissionsRadioSelector: '.popover input',
            deleteSelector: '.delete',
            copySelector: '.copy',
            removeAccessSelector: '.remove-access'
        });

        this.after('teardown', function() {
            $(document).off('click.permPopover');
        });

        this.after('initialize', function() {
            var self = this;

            this.editable = this.attr.data.isEditable;

            this.$node.html(template({
                workspace: this.attr.data,
                editable: this.editable
            }));
            this.userService.getCurrentUsers().done(this.loadUserPermissionsList.bind(this));
            this.on('click', {
                copySelector: this.onCopy
            });

            if (this.editable) {
                this.setupTypeahead();
                $(document).on('click.permPopover', function(event) {
                    var $target = $(event.target);

                    if ($target.closest('.permissions').length === 0) {
                        self.$node.find('.permissions').popover('hide');
                    }
                });
                this.on('shareWorkspaceWithUser', this.onShareWorkspaceWithUser);
                this.on('click', {
                    deleteSelector: this.onDelete,
                    removeAccessSelector: this.onRevokeAccess
                });
                this.on('change', {
                    permissionsRadioSelector: this.onPermissionsChange
                });
                this.select('titleSelector').on('change keyup paste', this.onChangeTitle.bind(this));
            }
        });

        var timeout;
        this.saveWorkspace = function(immediate, changes) {
            var self = this,
                d = $.Deferred(),
                save = function() {
                    self.trigger(document, 'workspaceSaving', self.attr.data);
                    return self.workspaceService.save(self.attr.data.workspaceId, changes)
                        .fail(function() {
                            d.reject();
                        })
                        .done(function(workspace) {
                            self.trigger(document, 'workspaceSaved', self.attr.data);
                            d.resolve({ workspace: self.attr.data });
                        });
                }

            if (immediate) {
                save();
            } else {
                clearTimeout(timeout);
                timeout = setTimeout(function() {
                    save();
                }, 1000);
            }

            return d;
        };

        this.loadUserPermissionsList = function(response) {
            var self = this,
                workspace = this.attr.data,
                html = $();

            this.currentUsers = response.users;

            (workspace.users || (workspace.users = [])).forEach(function(userPermission) {
                if (userPermission.userId != window.currentUser.id) {
                    var data = self.shareRowDataForPermission(userPermission);
                    if (data) {
                        html = html.add(shareRowTemplate(data));
                    }
                }
            });
            this.select('shareHeader').after(html).find('.loading').remove();
            if (this.editable) {
                this.select('shareFormSelector').show();
                this.updatePopovers();
            }
        };

        this.shareRowDataForPermission = function(userPermission) {
            var user = _.findWhere(this.currentUsers, { id: userPermission.userId });
            if (user) {
                return {
                    user: {
                        access: userPermission.access,
                        permissionLabel: {read: 'View', write: 'Edit'}[userPermission.access.toLowerCase()],
                        userId: user.id,
                        userName: user.userName
                    },
                    editable: this.editable
                };
            } else console.warn('User ' + userPermission.userId + ' in permissions is not a current user');
        };

        this.updatePopovers = function() {
            this.makePopover(this.select('permissionsSelector'));
        };

        this.makePopover = function(el) {
            el.popover({
                html: true,
                placement: 'bottom',
                container: this.$node,
                content: function() {
                    var row = $(this).closest('.user-row');
                    return $(permissionsTemplate($(this).data())).data('userRow', row);
                }
            });
        };

        this.onChangeTitle = function(event) {
            var $target = $(event.target),
                val = $target.val();

            if ($.trim(val).length === 0) {
                return;
            }

            if (val !== this.attr.data.title) {
                this.attr.data.title = val;
                this.saveWorkspace(false, {
                    title: val
                });
            }
        };

        this.onPermissionsChange = function(event) {
            var self = this,
                $target = $(event.target),
                newPermissions = $target.data('permissions'),
                list = $target.closest('.permissions-list'),
                userRow = list.data('userRow'),
                badge = userRow.find('.permissions'),
                userId = userRow.data('userId'),
                user = _.findWhere(this.attr.data.users, { userId: userId });

            if (user) {
                user.access = newPermissions;
                badge.popover('disable').addClass('loading');
                this.saveWorkspace(true, {
                    userUpdates: [user]
                })
                    .done(function() {
                        var newUserRow = $(shareRowTemplate(self.shareRowDataForPermission(user)));
                        userRow.replaceWith(newUserRow);
                        self.makePopover(newUserRow.find('.badge'));
                    });
            } else console.warn('Unable to update permissions because user "' + userId + '" not found');
        };

        this.onDelete = function(event) {
            var self = this,
                workspaceId = this.attr.data.workspaceId,
                $target = $(event.target),
                previousText = $target.text();

            this.trigger('workspaceDeleting', this.attr.data);

            $target.text('Deleting...').attr('disabled', true);

            this.workspaceService['delete'](workspaceId)
                .always(function() {
                    $target.text(previousText).removeAttr('disabled');
                })
                .done(function() {
                    self.trigger('workspaceDeleted', { workspaceId: workspaceId });
                });
        };

        this.onCopy = function(event) {
            var self = this,
                workspaceId = this.attr.data.workspaceId,
                $target = $(event.target),
                previousText = $target.text();

            $target.text('Copying...').attr('disabled', true);

            this.workspaceService.copy(workspaceId)
                .always(function() {
                    $target.text(previousText).removeAttr('disabled');
                })
                .done(function(workspace) {
                    self.trigger(document, 'workspaceCopied', { workspaceId: workspace.workspaceId });
                });
        };

        this.onRevokeAccess = function(event) {
            var self = this,
                list = $(event.target).closest('.permissions-list'),
                row = list.data('userRow'),
                userId = row.data('userId'),
                badge = row.find('.permissions').popover('disable').addClass('loading');

            this.attr.data.users = _.reject(this.attr.data.users, function(user) {
                return user.userId === userId;
            });
            this.saveWorkspace(true, {
                userDeletes: [userId]
            })
                .fail(function() {
                    var originalHtml = badge.html();
                    badge.removeClass('loading').addClass('badge-important').text('Error');
                    _.delay(function() {
                        badge.html(originalHtml).removeClass('badge-important').popover('enable');
                    }, 2000)
                })
                .done(function() {
                    row.remove();
                });
        };

        this.onShareWorkspaceWithUser = function(event, data) {

            var self = this,
                form = this.select('shareFormSelector'),
                user = {
                    userId: data.user.id,
                    access: 'READ'
                },
                row = $(shareRowTemplate(this.shareRowDataForPermission(user))).insertBefore(form),
                badge = row.find('.permissions');

            this.attr.data.users.push(user);

            badge.addClass('loading');
            this.saveWorkspace(true, {
                userUpdates: [user]
            })
                .always(function() {
                    badge.removeClass('loading');
                    badge.popover('destroy');
                })
                .fail(function() {
                    badge.addClass('badge-important').text('Error');
                    _.delay(function() {
                        row.remove();
                    }, 2000);
                })
                .done(function() {
                    _.defer(function() {
                        self.makePopover(badge);
                    });
                });
        };

        this.setupTypeahead = function() {
            var self = this,
                userMap = {};

            this.select('userSearchSelector').typeahead({
                source: function(query, callback) {
                    // TODO: pass query to backend to scale
                    self.userService.getCurrentUsers()
                        .done(function(response) {
                            var users = response.users,
                                regex = new RegExp(query, 'i'),
                                search = users.filter(function(user) {
                                    userMap[user.userName] = user;

                                    // Can't share with oneself
                                    if (user.id === self.attr.data.createdBy) return false;

                                    return regex.test(user.userName);
                                }),
                                names = _.pluck(search, 'userName');

                            self.currentUsers = users;
                            callback(names);
                        });
                },
                updater: function(userName) {
                    var user = userMap[userName];
                    if (user) {
                        self.trigger('shareWorkspaceWithUser', {
                            workspace: self.attr.data,
                            user: user
                        });
                    }
                    return '';
                }
            });
        };
    }
});
<commit_msg>Handle failures better in workspace sharing/title changes in ui<commit_after>
define([
    'flight/lib/component',
    'tpl!./form',
    'tpl!./shareRow',
    'tpl!./permissions',
    'service/user',
    'service/workspace'
], function(
    defineComponent,
    template,
    shareRowTemplate,
    permissionsTemplate,
    UserService,
    WorkspaceService) {
    'use strict';

    return defineComponent(Form);

    function Form() {

        this.userService = new UserService();
        this.workspaceService = new WorkspaceService();

        this.defaultAttrs({
            titleSelector: '.workspace-title',
            shareListSelector: '.share-list',
            shareHeader: '.share-header',
            shareFormSelector: '.share-form',
            userSearchSelector: '.share-form input',
            permissionsSelector: '.permissions',
            permissionsRadioSelector: '.popover input',
            deleteSelector: '.delete',
            copySelector: '.copy',
            removeAccessSelector: '.remove-access'
        });

        this.after('teardown', function() {
            $(document).off('click.permPopover');
        });

        this.after('initialize', function() {
            var self = this;

            this.editable = this.attr.data.isEditable;

            this.$node.html(template({
                workspace: this.attr.data,
                editable: this.editable
            }));
            this.userService.getCurrentUsers().done(this.loadUserPermissionsList.bind(this));
            this.on('click', {
                copySelector: this.onCopy
            });

            if (this.editable) {
                this.setupTypeahead();
                $(document).on('click.permPopover', function(event) {
                    var $target = $(event.target);

                    if ($target.closest('.permissions').length === 0) {
                        self.$node.find('.permissions').popover('hide');
                    }
                });
                this.on('shareWorkspaceWithUser', this.onShareWorkspaceWithUser);
                this.on('click', {
                    deleteSelector: this.onDelete,
                    removeAccessSelector: this.onRevokeAccess
                });
                this.on('change', {
                    permissionsRadioSelector: this.onPermissionsChange
                });
                this.select('titleSelector').on('change keyup paste', this.onChangeTitle.bind(this));
            }
        });

        var timeout;
        this.saveWorkspace = function(immediate, options) {
            var self = this,
                changes = options.changes,
                revert = options.revert,
                d = $.Deferred(),
                save = function() {
                    self.trigger(document, 'workspaceSaving', self.attr.data);
                    return self.workspaceService.save(self.attr.data.workspaceId, changes)
                        .fail(function() {
                            self.attr.data = revert;
                            self.trigger(document, 'workspaceSaved', revert);
                            d.reject();
                        })
                        .done(function(workspace) {
                            self.trigger(document, 'workspaceSaved', self.attr.data);
                            d.resolve({ workspace: self.attr.data });
                        });
                }

            if (immediate) {
                save();
            } else {
                clearTimeout(timeout);
                timeout = setTimeout(function() {
                    save();
                }, 1000);
            }

            return d;
        };

        this.loadUserPermissionsList = function(response) {
            var self = this,
                workspace = this.attr.data,
                html = $();

            this.currentUsers = response.users;

            (workspace.users || (workspace.users = [])).forEach(function(userPermission) {
                if (userPermission.userId != window.currentUser.id) {
                    var data = self.shareRowDataForPermission(userPermission);
                    if (data) {
                        html = html.add(shareRowTemplate(data));
                    }
                }
            });
            this.select('shareHeader').after(html).find('.loading').remove();
            if (this.editable) {
                this.select('shareFormSelector').show();
                this.updatePopovers();
            }
        };

        this.shareRowDataForPermission = function(userPermission) {
            var user = _.findWhere(this.currentUsers, { id: userPermission.userId });
            if (user) {
                return {
                    user: {
                        access: userPermission.access,
                        permissionLabel: {read: 'View', write: 'Edit'}[userPermission.access.toLowerCase()],
                        userId: user.id,
                        userName: user.userName
                    },
                    editable: this.editable
                };
            } else console.warn('User ' + userPermission.userId + ' in permissions is not a current user');
        };

        this.updatePopovers = function() {
            this.makePopover(this.select('permissionsSelector'));
        };

        this.makePopover = function(el) {
            el.popover({
                html: true,
                placement: 'bottom',
                container: this.$node,
                content: function() {
                    var row = $(this).closest('.user-row');
                    return $(permissionsTemplate($(this).data())).data('userRow', row);
                }
            });
        };

        this.onChangeTitle = function(event) {
            var self = this,
                $target = $(event.target),
                val = $target.val();

            if ($.trim(val).length === 0) {
                return;
            }

            if (val !== this.attr.data.title) {
                if (!this.titleRevert) {
                    this.titleRevert = $.extend(true, {}, this.attr.data);
                }
                this.attr.data.title = val;
                this.saveWorkspace(false, {
                    changes: {
                        title: val
                    },
                    revert: this.titleRevert
                }).fail(function() {
                    $target.val(self.titleRevert.title);
                }).always(function() {
                    self.titleRevert = null;
                });
            }
        };

        this.onPermissionsChange = function(event) {
            var self = this,
                $target = $(event.target),
                newPermissions = $target.data('permissions'),
                list = $target.closest('.permissions-list'),
                userRow = list.data('userRow'),
                badge = userRow.find('.permissions'),
                userId = userRow.data('userId'),
                user = _.findWhere(this.attr.data.users, { userId: userId });

            if (user) {
                var revert = $.extend(true, {}, this.attr.data);
                user.access = newPermissions;
                badge.popover('disable').addClass('loading');
                this.saveWorkspace(true, {
                    changes: {
                        userUpdates: [user]
                    },
                    revert: revert
                })
                    .done(function() {
                        var newUserRow = $(shareRowTemplate(self.shareRowDataForPermission(user)));
                        userRow.replaceWith(newUserRow);
                        self.makePopover(newUserRow.find('.badge'));
                    });
            } else console.warn('Unable to update permissions because user "' + userId + '" not found');
        };

        this.onDelete = function(event) {
            var self = this,
                workspaceId = this.attr.data.workspaceId,
                $target = $(event.target),
                previousText = $target.text();

            this.trigger('workspaceDeleting', this.attr.data);

            $target.text('Deleting...').attr('disabled', true);

            this.workspaceService['delete'](workspaceId)
                .always(function() {
                    $target.text(previousText).removeAttr('disabled');
                })
                .done(function() {
                    self.trigger('workspaceDeleted', { workspaceId: workspaceId });
                });
        };

        this.onCopy = function(event) {
            var self = this,
                workspaceId = this.attr.data.workspaceId,
                $target = $(event.target),
                previousText = $target.text();

            $target.text('Copying...').attr('disabled', true);

            this.workspaceService.copy(workspaceId)
                .always(function() {
                    $target.text(previousText).removeAttr('disabled');
                })
                .done(function(workspace) {
                    self.trigger(document, 'workspaceCopied', { workspaceId: workspace.workspaceId });
                });
        };

        this.onRevokeAccess = function(event) {
            var self = this,
                list = $(event.target).closest('.permissions-list'),
                row = list.data('userRow'),
                userId = row.data('userId'),
                badge = row.find('.permissions').popover('disable').addClass('loading'),
                revert = $.extend(true, {}, this.attr.data);

            this.attr.data.users = _.reject(this.attr.data.users, function(user) {
                return user.userId === userId;
            });
            this.saveWorkspace(true, {
                changes: {
                    userDeletes: [userId]
                },
                revert: revert
            })
                .fail(function() {
                    var originalHtml = badge.html();
                    badge.removeClass('loading').addClass('badge-important').text('Error');
                    _.delay(function() {
                        badge.html(originalHtml).removeClass('badge-important').popover('enable');
                    }, 2000)
                })
                .done(function() {
                    row.remove();
                });
        };

        this.onShareWorkspaceWithUser = function(event, data) {

            var self = this,
                form = this.select('shareFormSelector'),
                user = {
                    userId: data.user.id,
                    access: 'READ'
                },
                row = $(shareRowTemplate(this.shareRowDataForPermission(user))).insertBefore(form),
                badge = row.find('.permissions'),
                revert = $.extend(true, {}, this.attr.data);

            this.attr.data.users.push(user);

            badge.addClass('loading');
            this.saveWorkspace(true, {
                changes: {
                    userUpdates: [user]
                },
                revert: revert
            })
                .always(function() {
                    badge.removeClass('loading');
                    badge.popover('destroy');
                })
                .fail(function() {
                    badge.addClass('badge-important').text('Error');
                    _.delay(function() {
                        row.remove();
                    }, 2000);
                })
                .done(function() {
                    _.defer(function() {
                        self.makePopover(badge);
                    });
                });
        };

        this.setupTypeahead = function() {
            var self = this,
                userMap = {};

            this.select('userSearchSelector').typeahead({
                source: function(query, callback) {
                    // TODO: pass query to backend to scale
                    self.userService.getCurrentUsers()
                        .done(function(response) {
                            var users = response.users,
                                regex = new RegExp(query, 'i'),
                                search = users.filter(function(user) {
                                    userMap[user.userName] = user;

                                    // Can't share with oneself
                                    if (user.id === self.attr.data.createdBy) return false;

                                    return regex.test(user.userName);
                                }),
                                names = _.pluck(search, 'userName');

                            self.currentUsers = users;
                            callback(names);
                        });
                },
                updater: function(userName) {
                    var user = userMap[userName];
                    if (user) {
                        self.trigger('shareWorkspaceWithUser', {
                            workspace: self.attr.data,
                            user: user
                        });
                    }
                    return '';
                }
            });
        };
    }
});
<|endoftext|>


<commit_before>define(function (require) {

    var xocolor = {};

    xocolor.colors = [
        ['#B20008', '#FF2B34'],
        ['#FF2B34', '#B20008'],
        ['#E6000A', '#FF2B34'],
        ['#FF2B34', '#E6000A'],
        ['#FFADCE', '#FF2B34'],
        ['#9A5200', '#FF2B34'],
        ['#FF2B34', '#9A5200'],
        ['#FF8F00', '#FF2B34'],
        ['#FF2B34', '#FF8F00'],
        ['#FFC169', '#FF2B34'],
        ['#807500', '#FF2B34'],
        ['#FF2B34', '#807500'],
        ['#BE9E00', '#FF2B34'],
        ['#FF2B34', '#BE9E00'],
        ['#F8E800', '#FF2B34'],
        ['#008009', '#FF2B34'],
        ['#FF2B34', '#008009'],
        ['#00B20D', '#FF2B34'],
        ['#FF2B34', '#00B20D'],
        ['#8BFF7A', '#FF2B34'],
        ['#00588C', '#FF2B34'],
        ['#FF2B34', '#00588C'],
        ['#005FE4', '#FF2B34'],
        ['#FF2B34', '#005FE4'],
        ['#BCCDFF', '#FF2B34'],
        ['#5E008C', '#FF2B34'],
        ['#FF2B34', '#5E008C'],
        ['#7F00BF', '#FF2B34'],
        ['#FF2B34', '#7F00BF'],
        ['#D1A3FF', '#FF2B34'],
        ['#9A5200', '#FF8F00'],
        ['#FF8F00', '#9A5200'],
        ['#C97E00', '#FF8F00'],
        ['#FF8F00', '#C97E00'],
        ['#FFC169', '#FF8F00'],
        ['#807500', '#FF8F00'],
        ['#FF8F00', '#807500'],
        ['#BE9E00', '#FF8F00'],
        ['#FF8F00', '#BE9E00'],
        ['#F8E800', '#FF8F00'],
        ['#008009', '#FF8F00'],
        ['#FF8F00', '#008009'],
        ['#00B20D', '#FF8F00'],
        ['#FF8F00', '#00B20D'],
        ['#8BFF7A', '#FF8F00'],
        ['#00588C', '#FF8F00'],
        ['#FF8F00', '#00588C'],
        ['#005FE4', '#FF8F00'],
        ['#FF8F00', '#005FE4'],
        ['#BCCDFF', '#FF8F00'],
        ['#5E008C', '#FF8F00'],
        ['#FF8F00', '#5E008C'],
        ['#A700FF', '#FF8F00'],
        ['#FF8F00', '#A700FF'],
        ['#D1A3FF', '#FF8F00'],
        ['#B20008', '#FF8F00'],
        ['#FF8F00', '#B20008'],
        ['#FF2B34', '#FF8F00'],
        ['#FF8F00', '#FF2B34'],
        ['#FFADCE', '#FF8F00'],
        ['#807500', '#F8E800'],
        ['#F8E800', '#807500'],
        ['#BE9E00', '#F8E800'],
        ['#F8E800', '#BE9E00'],
        ['#FFFA00', '#EDDE00'],
        ['#008009', '#F8E800'],
        ['#F8E800', '#008009'],
        ['#00EA11', '#F8E800'],
        ['#F8E800', '#00EA11'],
        ['#8BFF7A', '#F8E800'],
        ['#00588C', '#F8E800'],
        ['#F8E800', '#00588C'],
        ['#00A0FF', '#F8E800'],
        ['#F8E800', '#00A0FF'],
        ['#BCCEFF', '#F8E800'],
        ['#5E008C', '#F8E800'],
        ['#F8E800', '#5E008C'],
        ['#AC32FF', '#F8E800'],
        ['#F8E800', '#AC32FF'],
        ['#D1A3FF', '#F8E800'],
        ['#B20008', '#F8E800'],
        ['#F8E800', '#B20008'],
        ['#FF2B34', '#F8E800'],
        ['#F8E800', '#FF2B34'],
        ['#FFADCE', '#F8E800'],
        ['#9A5200', '#F8E800'],
        ['#F8E800', '#9A5200'],
        ['#FF8F00', '#F8E800'],
        ['#F8E800', '#FF8F00'],
        ['#FFC169', '#F8E800'],
        ['#008009', '#00EA11'],
        ['#00EA11', '#008009'],
        ['#00B20D', '#00EA11'],
        ['#00EA11', '#00B20D'],
        ['#8BFF7A', '#00EA11'],
        ['#00588C', '#00EA11'],
        ['#00EA11', '#00588C'],
        ['#005FE4', '#00EA11'],
        ['#00EA11', '#005FE4'],
        ['#BCCDFF', '#00EA11'],
        ['#5E008C', '#00EA11'],
        ['#00EA11', '#5E008C'],
        ['#7F00BF', '#00EA11'],
        ['#00EA11', '#7F00BF'],
        ['#D1A3FF', '#00EA11'],
        ['#B20008', '#00EA11'],
        ['#00EA11', '#B20008'],
        ['#FF2B34', '#00EA11'],
        ['#00EA11', '#FF2B34'],
        ['#FFADCE', '#00EA11'],
        ['#9A5200', '#00EA11'],
        ['#00EA11', '#9A5200'],
        ['#FF8F00', '#00EA11'],
        ['#00EA11', '#FF8F00'],
        ['#FFC169', '#00EA11'],
        ['#807500', '#00EA11'],
        ['#00EA11', '#807500'],
        ['#BE9E00', '#00EA11'],
        ['#00EA11', '#BE9E00'],
        ['#F8E800', '#00EA11'],
        ['#00588C', '#00A0FF'],
        ['#00A0FF', '#00588C'],
        ['#005FE4', '#00A0FF'],
        ['#00A0FF', '#005FE4'],
        ['#BCCDFF', '#00A0FF'],
        ['#5E008C', '#00A0FF'],
        ['#00A0FF', '#5E008C'],
        ['#9900E6', '#00A0FF'],
        ['#00A0FF', '#9900E6'],
        ['#D1A3FF', '#00A0FF'],
        ['#B20008', '#00A0FF'],
        ['#00A0FF', '#B20008'],
        ['#FF2B34', '#00A0FF'],
        ['#00A0FF', '#FF2B34'],
        ['#FFADCE', '#00A0FF'],
        ['#9A5200', '#00A0FF'],
        ['#00A0FF', '#9A5200'],
        ['#FF8F00', '#00A0FF'],
        ['#00A0FF', '#FF8F00'],
        ['#FFC169', '#00A0FF'],
        ['#807500', '#00A0FF'],
        ['#00A0FF', '#807500'],
        ['#BE9E00', '#00A0FF'],
        ['#00A0FF', '#BE9E00'],
        ['#F8E800', '#00A0FF'],
        ['#008009', '#00A0FF'],
        ['#00A0FF', '#008009'],
        ['#00B20D', '#00A0FF'],
        ['#00A0FF', '#00B20D'],
        ['#8BFF7A', '#00A0FF'],
        ['#5E008C', '#AC32FF'],
        ['#AC32FF', '#5E008C'],
        ['#7F00BF', '#AC32FF'],
        ['#AC32FF', '#7F00BF'],
        ['#D1A3FF', '#AC32FF'],
        ['#B20008', '#AC32FF'],
        ['#AC32FF', '#B20008'],
        ['#FF2B34', '#AC32FF'],
        ['#AC32FF', '#FF2B34'],
        ['#FFADCE', '#AC32FF'],
        ['#9A5200', '#AC32FF'],
        ['#AC32FF', '#9A5200'],
        ['#FF8F00', '#AC32FF'],
        ['#AC32FF', '#FF8F00'],
        ['#FFC169', '#AC32FF'],
        ['#807500', '#AC32FF'],
        ['#AC32FF', '#807500'],
        ['#BE9E00', '#AC32FF'],
        ['#AC32FF', '#BE9E00'],
        ['#F8E800', '#AC32FF'],
        ['#008009', '#AC32FF'],
        ['#AC32FF', '#008009'],
        ['#00B20D', '#AC32FF'],
        ['#AC32FF', '#00B20D'],
        ['#8BFF7A', '#AC32FF'],
        ['#00588C', '#AC32FF'],
        ['#AC32FF', '#00588C'],
        ['#005FE4', '#AC32FF'],
        ['#AC32FF', '#005FE4'],
        ['#BCCDFF', '#AC32FF']
    ];

    return xocolor;

});
<commit_msg>Run js-beautify on xocolor<commit_after>define(function (require) {

    var xocolor = {};

    xocolor.colors = [
        ['#B20008', '#FF2B34'],
         ['#FF2B34', '#B20008'],
         ['#E6000A', '#FF2B34'],
         ['#FF2B34', '#E6000A'],
         ['#FFADCE', '#FF2B34'],
         ['#9A5200', '#FF2B34'],
         ['#FF2B34', '#9A5200'],
         ['#FF8F00', '#FF2B34'],
         ['#FF2B34', '#FF8F00'],
         ['#FFC169', '#FF2B34'],
         ['#807500', '#FF2B34'],
         ['#FF2B34', '#807500'],
         ['#BE9E00', '#FF2B34'],
         ['#FF2B34', '#BE9E00'],
         ['#F8E800', '#FF2B34'],
         ['#008009', '#FF2B34'],
         ['#FF2B34', '#008009'],
         ['#00B20D', '#FF2B34'],
         ['#FF2B34', '#00B20D'],
         ['#8BFF7A', '#FF2B34'],
         ['#00588C', '#FF2B34'],
         ['#FF2B34', '#00588C'],
         ['#005FE4', '#FF2B34'],
         ['#FF2B34', '#005FE4'],
         ['#BCCDFF', '#FF2B34'],
         ['#5E008C', '#FF2B34'],
         ['#FF2B34', '#5E008C'],
         ['#7F00BF', '#FF2B34'],
         ['#FF2B34', '#7F00BF'],
         ['#D1A3FF', '#FF2B34'],
         ['#9A5200', '#FF8F00'],
         ['#FF8F00', '#9A5200'],
         ['#C97E00', '#FF8F00'],
         ['#FF8F00', '#C97E00'],
         ['#FFC169', '#FF8F00'],
         ['#807500', '#FF8F00'],
         ['#FF8F00', '#807500'],
         ['#BE9E00', '#FF8F00'],
         ['#FF8F00', '#BE9E00'],
         ['#F8E800', '#FF8F00'],
         ['#008009', '#FF8F00'],
         ['#FF8F00', '#008009'],
         ['#00B20D', '#FF8F00'],
         ['#FF8F00', '#00B20D'],
         ['#8BFF7A', '#FF8F00'],
         ['#00588C', '#FF8F00'],
         ['#FF8F00', '#00588C'],
         ['#005FE4', '#FF8F00'],
         ['#FF8F00', '#005FE4'],
         ['#BCCDFF', '#FF8F00'],
         ['#5E008C', '#FF8F00'],
         ['#FF8F00', '#5E008C'],
         ['#A700FF', '#FF8F00'],
         ['#FF8F00', '#A700FF'],
         ['#D1A3FF', '#FF8F00'],
         ['#B20008', '#FF8F00'],
         ['#FF8F00', '#B20008'],
         ['#FF2B34', '#FF8F00'],
         ['#FF8F00', '#FF2B34'],
         ['#FFADCE', '#FF8F00'],
         ['#807500', '#F8E800'],
         ['#F8E800', '#807500'],
         ['#BE9E00', '#F8E800'],
         ['#F8E800', '#BE9E00'],
         ['#FFFA00', '#EDDE00'],
         ['#008009', '#F8E800'],
         ['#F8E800', '#008009'],
         ['#00EA11', '#F8E800'],
         ['#F8E800', '#00EA11'],
         ['#8BFF7A', '#F8E800'],
         ['#00588C', '#F8E800'],
         ['#F8E800', '#00588C'],
         ['#00A0FF', '#F8E800'],
         ['#F8E800', '#00A0FF'],
         ['#BCCEFF', '#F8E800'],
         ['#5E008C', '#F8E800'],
         ['#F8E800', '#5E008C'],
         ['#AC32FF', '#F8E800'],
         ['#F8E800', '#AC32FF'],
         ['#D1A3FF', '#F8E800'],
         ['#B20008', '#F8E800'],
         ['#F8E800', '#B20008'],
         ['#FF2B34', '#F8E800'],
         ['#F8E800', '#FF2B34'],
         ['#FFADCE', '#F8E800'],
         ['#9A5200', '#F8E800'],
         ['#F8E800', '#9A5200'],
         ['#FF8F00', '#F8E800'],
         ['#F8E800', '#FF8F00'],
         ['#FFC169', '#F8E800'],
         ['#008009', '#00EA11'],
         ['#00EA11', '#008009'],
         ['#00B20D', '#00EA11'],
         ['#00EA11', '#00B20D'],
         ['#8BFF7A', '#00EA11'],
         ['#00588C', '#00EA11'],
         ['#00EA11', '#00588C'],
         ['#005FE4', '#00EA11'],
         ['#00EA11', '#005FE4'],
         ['#BCCDFF', '#00EA11'],
         ['#5E008C', '#00EA11'],
         ['#00EA11', '#5E008C'],
         ['#7F00BF', '#00EA11'],
         ['#00EA11', '#7F00BF'],
         ['#D1A3FF', '#00EA11'],
         ['#B20008', '#00EA11'],
         ['#00EA11', '#B20008'],
         ['#FF2B34', '#00EA11'],
         ['#00EA11', '#FF2B34'],
         ['#FFADCE', '#00EA11'],
         ['#9A5200', '#00EA11'],
         ['#00EA11', '#9A5200'],
         ['#FF8F00', '#00EA11'],
         ['#00EA11', '#FF8F00'],
         ['#FFC169', '#00EA11'],
         ['#807500', '#00EA11'],
         ['#00EA11', '#807500'],
         ['#BE9E00', '#00EA11'],
         ['#00EA11', '#BE9E00'],
         ['#F8E800', '#00EA11'],
         ['#00588C', '#00A0FF'],
         ['#00A0FF', '#00588C'],
         ['#005FE4', '#00A0FF'],
         ['#00A0FF', '#005FE4'],
         ['#BCCDFF', '#00A0FF'],
         ['#5E008C', '#00A0FF'],
         ['#00A0FF', '#5E008C'],
         ['#9900E6', '#00A0FF'],
         ['#00A0FF', '#9900E6'],
         ['#D1A3FF', '#00A0FF'],
         ['#B20008', '#00A0FF'],
         ['#00A0FF', '#B20008'],
         ['#FF2B34', '#00A0FF'],
         ['#00A0FF', '#FF2B34'],
         ['#FFADCE', '#00A0FF'],
         ['#9A5200', '#00A0FF'],
         ['#00A0FF', '#9A5200'],
         ['#FF8F00', '#00A0FF'],
         ['#00A0FF', '#FF8F00'],
         ['#FFC169', '#00A0FF'],
         ['#807500', '#00A0FF'],
         ['#00A0FF', '#807500'],
         ['#BE9E00', '#00A0FF'],
         ['#00A0FF', '#BE9E00'],
         ['#F8E800', '#00A0FF'],
         ['#008009', '#00A0FF'],
         ['#00A0FF', '#008009'],
         ['#00B20D', '#00A0FF'],
         ['#00A0FF', '#00B20D'],
         ['#8BFF7A', '#00A0FF'],
         ['#5E008C', '#AC32FF'],
         ['#AC32FF', '#5E008C'],
         ['#7F00BF', '#AC32FF'],
         ['#AC32FF', '#7F00BF'],
         ['#D1A3FF', '#AC32FF'],
         ['#B20008', '#AC32FF'],
         ['#AC32FF', '#B20008'],
         ['#FF2B34', '#AC32FF'],
         ['#AC32FF', '#FF2B34'],
         ['#FFADCE', '#AC32FF'],
         ['#9A5200', '#AC32FF'],
         ['#AC32FF', '#9A5200'],
         ['#FF8F00', '#AC32FF'],
         ['#AC32FF', '#FF8F00'],
         ['#FFC169', '#AC32FF'],
         ['#807500', '#AC32FF'],
         ['#AC32FF', '#807500'],
         ['#BE9E00', '#AC32FF'],
         ['#AC32FF', '#BE9E00'],
         ['#F8E800', '#AC32FF'],
         ['#008009', '#AC32FF'],
         ['#AC32FF', '#008009'],
         ['#00B20D', '#AC32FF'],
         ['#AC32FF', '#00B20D'],
         ['#8BFF7A', '#AC32FF'],
         ['#00588C', '#AC32FF'],
         ['#AC32FF', '#00588C'],
         ['#005FE4', '#AC32FF'],
         ['#AC32FF', '#005FE4'],
         ['#BCCDFF', '#AC32FF']
    ];

    return xocolor;

});
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const WebpackError = require("./WebpackError");

/** @typedef {import("./Module")} Module */

class ModuleRestoreError extends WebpackError {
	/**
	 * @param {Module} module module tied to dependency
	 * @param {string | Error} err error thrown
	 */
	constructor(module, err) {
		let message = "Module restore failed: ";
		let details = undefined;
		if (err !== null && typeof err === "object") {
			if (typeof err.stack === "string" && err.stack) {
				const stack = err.stack;
				message += stack;
			} else if (typeof err.message === "string" && err.message) {
				message += err.message;
			} else {
				message += err;
			}
		} else {
			message = String(err);
		}

		super(message);

		this.name = "ModuleRestoreError";
		this.details = details;
		this.module = module;
		this.error = err;

		Error.captureStackTrace(this, this.constructor);
	}
}

module.exports = ModuleRestoreError;
<commit_msg>fix message update in ModuleRestoreError<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const WebpackError = require("./WebpackError");

/** @typedef {import("./Module")} Module */

class ModuleRestoreError extends WebpackError {
	/**
	 * @param {Module} module module tied to dependency
	 * @param {string | Error} err error thrown
	 */
	constructor(module, err) {
		let message = "Module restore failed: ";
		let details = undefined;
		if (err !== null && typeof err === "object") {
			if (typeof err.stack === "string" && err.stack) {
				const stack = err.stack;
				message += stack;
			} else if (typeof err.message === "string" && err.message) {
				message += err.message;
			} else {
				message += err;
			}
		} else {
			message += String(err);
		}

		super(message);

		this.name = "ModuleRestoreError";
		this.details = details;
		this.module = module;
		this.error = err;

		Error.captureStackTrace(this, this.constructor);
	}
}

module.exports = ModuleRestoreError;
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var Tapable = require("tapable");
var MultiModule = require("./MultiModule");

function MultiModuleFactory() {
	Tapable.call(this);
}
module.exports = MultiModuleFactory;

MultiModuleFactory.prototype = Object.create(Tapable.prototype);
MultiModuleFactory.prototype.constructor = MultiModuleFactory;

MultiModuleFactory.prototype.create = function(data, callback) {
	var dependency = data.dependencies[0];
	callback(null, new MultiModule(data.context, dependency.dependencies, dependency.name));
};
<commit_msg>Refactor(ES6): MultiModuleFactory.js<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
const Tapable = require("tapable");
const MultiModule = require("./MultiModule");

module.exports = class MultiModuleFactory extends Tapable {
  constructor() {
		super();
	}

	create(data, callback) {
		const dependency = data.dependencies[0];
		callback(null, new MultiModule(data.context, dependency.dependencies, dependency.name));
	}
};
<|endoftext|>


<commit_before>/* Tests the streaming xhr without stubbing anything. Really just a test that
*  we've got the interface of the in-browser XHR object pinned down  */

(function(){

   AsyncTestCase("testStreamingXhr", {

      // shorten the waiting time before a test fails. Default 30s is too long:
      setUp: function(){
         jstestdriver.plugins.async.CallbackPool.TIMEOUT = ASYNC_TEST_TIMEOUT;
      },

      testCanAjaxInASmallKnownFile: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // in practice, since we're running on an internal network and this is a small file,
            // we'll probably only get one callback
            streamingXhr(
               '/test/test/json/smallestPossible.json',
               callbacks.add(function(nextDrip){
                  combinedResult += nextDrip;
               })
            );
         });

         queue.call("check we got the json back", function(){
            assertEquals('{}', combinedResult);
         });
      },

      testCanAjaxInAVeryLargeFileWithoutMissingAny: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               '/test/test/json/twentyThousandRecords.json',

               function(nextDrip){
                  combinedResult += nextDrip;
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // when to move onto the next queuer
               callbacks.noop()
            )
         });

         queue.call("check we got the correct json back", function(){

            // should have given valid json;
            var parsedResult = JSON.parse(combinedResult);

            // as per the name, should have 20,000 records in that file:
            assertEquals(20000, parsedResult.result.length);
         });
      },

      testCanAjaxInAStreamingFileWithoutMissingAny: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               '/stream/tenSlowNumbers.json',

               function(nextDrip){
                  combinedResult += nextDrip;
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // when to move onto the next queuer
               callbacks.noop()
            )
         });

         queue.call("check we got the correct json back", function(){

            // should have given valid json;
            var parsedResult = JSON.parse(combinedResult);

            // as per the name, should have 20,000 records in that file:
            assertEquals([0,1,2,3,4,5,6,7,8,9], parsedResult);
         });
      },

      testDoesntCallbackWithoutNewData: function(queue) {

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               '/test/test/json/twentyThousandRecords.json',

               function(nextDrip){
                  if( nextDrip.length === 0 ) {
                     fail('zero-length drip received');
                  }
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // we're done
               callbacks.noop()
            )
         });

      },

      testAjaxingOverStreamingHttpGivesMultipleCallbacks: function(queue) {

         document.domain = 'localhost';

         var numberOfProgressCallbacks = 0;

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               '/stream/tenSlowNumbers.json',

               function onProgress( drip ){
                  console.log('I got a drip', drip, numberOfProgressCallbacks);
                  numberOfProgressCallbacks++;
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // when to move onto the next queuer
               callbacks.noop()
            )
         });

         queue.call("check we got multiple callbacks", function(){

            if( numberOfProgressCallbacks < 10)(
               fail("I had " + numberOfProgressCallbacks + " progress callback(s), should have" +
                   " had at least 10")
            );
         });
      }
   });

})();<commit_msg>improved error message on failing test case. FF failing here<commit_after>/* Tests the streaming xhr without stubbing anything. Really just a test that
*  we've got the interface of the in-browser XHR object pinned down  */

(function(){

   AsyncTestCase("testStreamingXhr", {

      // shorten the waiting time before a test fails. Default 30s is too long:
      setUp: function(){
         jstestdriver.plugins.async.CallbackPool.TIMEOUT = ASYNC_TEST_TIMEOUT;
      },

      testCanAjaxInASmallKnownFile: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // in practice, since we're running on an internal network and this is a small file,
            // we'll probably only get one callback
            streamingXhr(
               '/test/test/json/smallestPossible.json',
               callbacks.add(function(nextDrip){
                  combinedResult += nextDrip;
               })
            );
         });

         queue.call("check we got the json back", function(){
            assertEquals('{}', combinedResult);
         });
      },

      testCanAjaxInAVeryLargeFileWithoutMissingAny: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               '/test/test/json/twentyThousandRecords.json',

               function(nextDrip){
                  combinedResult += nextDrip;
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // when to move onto the next queuer
               callbacks.noop()
            )
         });

         queue.call("check we got the correct json back", function(){

            // should have given valid json;
            var parsedResult = JSON.parse(combinedResult);

            // as per the name, should have 20,000 records in that file:
            assertEquals(20000, parsedResult.result.length);
         });
      },

      testCanAjaxInAStreamingFileWithoutMissingAny: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               '/stream/tenSlowNumbers.json',

               function(nextDrip){
                  combinedResult += nextDrip;
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // when to move onto the next queuer
               callbacks.noop()
            )
         });

         queue.call("check we got the correct json back", function(){

            // should have given valid json;
            try{
               var parsedResult = JSON.parse(combinedResult);
            } catch(e) {
               fail('could not parse json "' + combinedResult + '" because ' + e);
            }

            // as per the name, should have 20,000 records in that file:
            assertEquals([0,1,2,3,4,5,6,7,8,9], parsedResult);
         });
      },

      testDoesntCallbackWithoutNewData: function(queue) {

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               '/test/test/json/twentyThousandRecords.json',

               function(nextDrip){
                  if( nextDrip.length === 0 ) {
                     fail('zero-length drip received');
                  }
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // we're done
               callbacks.noop()
            )
         });

      },

      testAjaxingOverStreamingHttpGivesMultipleCallbacks: function(queue) {

         document.domain = 'localhost';

         var numberOfProgressCallbacks = 0;

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               '/stream/tenSlowNumbers.json',

               function onProgress( drip ){
                  console.log('I got a drip', drip, numberOfProgressCallbacks);
                  numberOfProgressCallbacks++;
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // when to move onto the next queuer
               callbacks.noop()
            )
         });

         queue.call("check we got multiple callbacks", function(){

            if( numberOfProgressCallbacks < 10)(
               fail("I had " + numberOfProgressCallbacks + " progress callback(s), should have" +
                   " had at least 10")
            );
         });
      }
   });

})();<|endoftext|>