<commit_before>/*
 * ! ${copyright}
 */

sap.ui.define([
	'sap/ui/mdc/field/FieldValueHelpTableWrapperBase',
	"sap/ui/mdc/util/loadModules",
	"sap/base/util/deepEqual",
	"sap/ui/mdc/library",
	"sap/ui/mdc/enum/PersistenceMode",
	"sap/ui/mdc/p13n/Engine",
	'sap/ui/mdc/condition/FilterConverter',
	"sap/ui/thirdparty/jquery"
	], function(
		FieldValueHelpTableWrapperBase,
		loadModules,
		deepEqual,
		library,
		PersistenceMode,
		Engine,
		FilterConverter,
		jQuery
	) {
	"use strict";

	var SelectionMode = library.SelectionMode;

	var _mTableModules = {
		"Table": "sap/ui/mdc/field/FieldValueHelpUITableWrapper",
		"ResponsiveTable": "sap/ui/mdc/field/FieldValueHelpMTableWrapper"
	};

	/**
	 * Constructor for a new FieldValueHelpMdcTableWrapper.
	 *
	 * The FieldValueHelp element supports different types of content. This is a wrapper to use a
	 * sap.ui.mdc.Table control as content.
	 *
	 * @param {string} [sId] ID for the new control, generated automatically if no ID is given
	 * @param {object} [mSettings] Initial settings for the new control
	 * @class Wrapper to use a sap.m.Table control as content of a FieldValueHelp element
	 * @extends sap.ui.mdc.field.FieldValueHelpTableWrapperBase
	 * @version ${version}
	 * @constructor
	 * @private
	 * @ui5-restricted sap.fe
	 * @MDC_PUBLIC_CANDIDATE
 	 * @experimental
	 * @since 1.88.0
	 * @alias sap.ui.mdc.field.FieldValueHelpMdcTableWrapper
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var FieldValueHelpMdcTableWrapper = FieldValueHelpTableWrapperBase.extend("sap.ui.mdc.field.FieldValueHelpMdcTableWrapper", /** @lends sap.ui.mdc.field.FieldValueHelpMdcTableWrapper.prototype */
	{
		metadata: {
			library: "sap.ui.mdc",
			aggregations: {
				table: {
					type: "sap.ui.mdc.Table",
					multiple: false
				}
			},
			defaultAggregation: "table"
		}
	});

	FieldValueHelpMdcTableWrapper.prototype.init = function() {
		FieldValueHelpTableWrapperBase.prototype.init.apply(this, arguments);
		this.OInnerWrapperClass = null; // wrapper class for internal table type;
	};

	FieldValueHelpMdcTableWrapper.prototype.setParent = function(oParent, sAggregationName) {
		/* MDC.Table personalization inside ValueHelps should never be persisted,
		 * therefore we add the Fieldhelp to a PersistenceProvider with transient configuration.
		 */
		if (oParent) {
			Engine.getInstance().defaultProviderRegistry.attach(oParent, PersistenceMode.Transient);
		}
		FieldValueHelpTableWrapperBase.prototype.setParent.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._getStringType = function() {
		var oTable = this.getTable();
		var sType, oType = sType = oTable && oTable.getType();
		if (!oType) {
			sType = "Table"; // back to the default behaviour
		} else if (typeof oType === "object") {
			if (oType.isA("sap.ui.mdc.table.ResponsiveTableType")) {
				sType = "ResponsiveTable";
			} else {
				sType = "Table";
			}
		}
		return sType;
	};

	FieldValueHelpMdcTableWrapper.prototype.fieldHelpOpen = function(bSuggestion) {
		var oTable = this.getTable();
		if (oTable) {
			if (this.OInnerWrapperClass) {
				return this.OInnerWrapperClass.prototype.fieldHelpOpen.call(this, bSuggestion);
			}
		}
		return this;
	};

	/*
	* Provides a table wrapper class for dealing with specifics of mdc.tables inner table whenever the wrappers table aggregation or a given mdc.tables _content aggregation receive a new table.
	* The wrapper classes initialize method is applied to the current outer wrapper instance and cleanup is done for an eventually already existing wrapper.
	*/
	FieldValueHelpMdcTableWrapper.prototype._updateInnerWrapperClass = function () {

		var sTableType = this._getStringType();
		var sModule = _mTableModules[sTableType];

		if (sModule && this._sInnerWrapperType !== sTableType) {
			this._sInnerWrapperType = sTableType;

			if (this.OInnerWrapperClass) {
				this.OInnerWrapperClass.prototype.dispose.apply(this);
				this.OInnerWrapperClass = null;
			}

			this._oInnerWrapperClassPromise = loadModules(sModule).then(function (aModules) {
				this.OInnerWrapperClass = aModules[0];
				this.OInnerWrapperClass.prototype.initialize.apply(this);
			}.bind(this));
		}
	};

	/*
	* Adjust the tables layout depending on fields maxConditions and suggestion/dialog mode. Additionally uses inner wrapper class to adjust inner table
	*/
	FieldValueHelpMdcTableWrapper.prototype._adjustTable = function (bSuggestion) {

		var oTable = this.getTable();

		if (oTable) {

			var oParent = this.getParent();

			if (oParent) {
				oTable.setHeight("100%");
				oTable.setSelectionMode(this._getMaxConditions() === 1 ? SelectionMode.Single : SelectionMode.Multi);

				var oFieldHelp = this._getFieldHelp();
				var oFilterBar = oFieldHelp._getFilterBar();
				var bFilterChange = oFilterBar && oTable.getFilter() !== oFilterBar.getId();
				if (bFilterChange) {
					oTable.setFilter(oFilterBar);
				}

			}

			if (this.OInnerWrapperClass) {
				this.OInnerWrapperClass.prototype._adjustTable.call(this, bSuggestion);
			}
		}
	};

	FieldValueHelpMdcTableWrapper.prototype.exit = function() {
		var oParent = this.getParent();
		if (oParent) {
			Engine.getInstance().defaultProviderRegistry.detach(oParent);
		}

		this._oCurrentConditions = null;
		this._bSuggestion = null;

		if (this._oInnerWrapperClassPromise) {
			this._oInnerWrapperClassPromise = null;
		}
		if (this.OInnerWrapperClass) {
			this.OInnerWrapperClass.prototype.dispose.apply(this);
			this.OInnerWrapperClass = null;
		}

		this._sInnerWrapperType = null;
		this._bSearchTriggered = null;

		FieldValueHelpTableWrapperBase.prototype.exit.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype.isSuspended = function() {
		var oTable = this.getTable();
		var oListBinding = this.getListBinding();
		return oListBinding ? oListBinding.isSuspended() : oTable && !oTable.getAutoBindOnInit();
	};

	FieldValueHelpMdcTableWrapper.prototype.getListBinding = function() {
		var oTable = this.getTable();
		return oTable && oTable.getRowBinding();
	};

	// TODO: This is a hack to make the m.Table itemPress work as it seems to be suppressed in mdc.Table for some reason.

	var oMDCTableDelegate = {
		onmouseover: function (oEvent) {
			var oItem = jQuery(oEvent.target).control(0);
			if (oItem && oItem.isA("sap.m.ColumnListItem")) {
				oItem.setType("Active");
			}
		}
	};
	var _handleOuterDelegate = function (oTable, bAdd) {
		if (bAdd) {
			oTable.addDelegate(oMDCTableDelegate, true, this);
			return;
		}
		oTable.removeDelegate(oMDCTableDelegate);
	};

	// ------ >

	FieldValueHelpMdcTableWrapper.prototype._handleTableChanged = function (sMutation, oTable) {
		var oInnerTable;
		if (sMutation === "insert") {
			this._updateInnerWrapperClass();
			_handleOuterDelegate.call(this, oTable, true);

			oInnerTable = this._getWrappedTable();
			if (oInnerTable) {
				this._handleInnerTableChanged("insert", oInnerTable);
			}
			this._oObserver.observe(oTable, {aggregations: ["_content"]});
		} else {
			_handleOuterDelegate.call(this, oTable);
			oInnerTable = oTable._oTable; // as _getWrappedTable will not return a table right now
			if (oInnerTable) {
				this._handleInnerTableChanged(sMutation, oInnerTable);
			}
			this._oObserver.unobserve(oTable);
		}
	};

	/*
	* Hide toolbar for now
	*/
	FieldValueHelpMdcTableWrapper.prototype._handleToolbarExtensions = function (oInnerTable) {

		if (oInnerTable.mAggregations["extension"] && oInnerTable.mAggregations["extension"].length) {
			oInnerTable.getAggregation("extension").forEach(function (oExt) {
				oExt.setVisible(false);
			});
		}

		if (oInnerTable.mAggregations["headerToolbar"]) {
			var oToolbar = oInnerTable.getAggregation("headerToolbar");
			oToolbar.setVisible(false);
		}
	};

	FieldValueHelpMdcTableWrapper.prototype._handleInnerTableChanged = function (sMutation, oInnerTable) {
		if (sMutation === "insert") {
			this._updateInnerWrapperClass();
			this._handleToolbarExtensions(oInnerTable);
			this._oObserver.observe(oInnerTable, {bindings: ["rows"]});
		}

		this._oInnerWrapperClassPromise.then(function() {
			this.OInnerWrapperClass.prototype._handleTableChanged.call(this, sMutation, oInnerTable);
			this.getTable().initialized().then(function () {
				this.fireDataUpdate({contentChange: true});
			}.bind(this));
		}.bind(this));
	};

	FieldValueHelpMdcTableWrapper.prototype.applyFilters = function(aFilters, sSearch, oFilterBar) {

		var oTable = this.getTable();

		if (oTable && oFilterBar) {
			var oListBinding = this.getListBinding();
			var bListBindingSuspended = oListBinding && oListBinding.isSuspended();
			var oFieldHelp = this._getFieldHelp();

			if (oListBinding && !bListBindingSuspended && !this._bSearchTriggered) {
				var sFBSearch = oFilterBar.getSearch() || "";
				var sBindingSearch = oListBinding.mParameters.$search || "";
				var oCurrentFilterBarConditions = oFilterBar.getConditions();
				var oConditionTypes = oFieldHelp._getTypesForConditions(oCurrentFilterBarConditions);
				var oCreatedFBFilters = oCurrentFilterBarConditions && oConditionTypes && FilterConverter.createFilters(oCurrentFilterBarConditions, oConditionTypes, undefined, oFieldHelp.getCaseSensitive());
				var aFBFilters = oCreatedFBFilters ? [].concat(oCreatedFBFilters) : [];
				var aBindingFilters = oListBinding.aApplicationFilters.reduce(function (aResult, oFilter) {
					return aResult.concat(oFilter._bMultiFilter ? oFilter.aFilters : oFilter);
				}, []);
				var bFiltersChanged = !deepEqual(aFBFilters, aBindingFilters);
				var bSearchChanged = sFBSearch !== sBindingSearch;
				var bTableHasOverlay = oTable._oTable && oTable._oTable.getShowOverlay && oTable._oTable.getShowOverlay();

				if (bFiltersChanged || bSearchChanged || bTableHasOverlay) {
					this._handleScrolling();
					oFilterBar.triggerSearch();
					this._bSearchTriggered = true;
				}
			}

			if (bListBindingSuspended) {
				oListBinding.resume();
			}

			if (!oListBinding && oTable.getAutoBindOnInit()) {
				this._oTablePromise.then(function () {
					if (!this._bIsBeingDestroyed) {
						this.applyFilters(aFilters, sSearch, oFilterBar);
					}
				}.bind(this));
			}
		}
	};

	FieldValueHelpMdcTableWrapper.prototype._observeChanges = function (oChanges, bNoSelection) {

		if (oChanges.name === "_content") {
			this._handleInnerTableChanged(oChanges.mutation, oChanges.child);
		}

		if (this.OInnerWrapperClass) {
			this.OInnerWrapperClass.prototype._observeChanges.call(this, oChanges, true);
		} else {
			FieldValueHelpTableWrapperBase.prototype._observeChanges.call(this, oChanges, true);
		}
	};

	FieldValueHelpMdcTableWrapper.prototype._handleUpdateFinished = function (oEvent) {
		this._bSearchTriggered = false;
		return this.OInnerWrapperClass.prototype._handleUpdateFinished.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._handleEvents = function (oEvent) {
		if (this.OInnerWrapperClass) {
			return this.OInnerWrapperClass.prototype._handleEvents.apply(this, arguments);
		}
	};

	FieldValueHelpMdcTableWrapper.prototype._handleItemPress = function (oEvent) {
		return this.OInnerWrapperClass.prototype._handleItemPress.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._handleSelectionChange = function (oEvent) {
		var bIsTableReady = this._isTableReady();
		return this._iRunningTableSelectionUpdates || !bIsTableReady || this._bBusy ? undefined : this._fireSelectionChange.call(this, false);
	};

	FieldValueHelpMdcTableWrapper.prototype._getTableItems = function (bSelectedOnly, bNoVirtual) {
		return this.OInnerWrapperClass.prototype._getTableItems.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._modifyTableSelection = function (aItems, oItem, bSelected, iItemIndex) {
		return this.OInnerWrapperClass.prototype._modifyTableSelection.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._getDataFromItem = function (oItem, aInParameters, aOutParameters) {
		return this.OInnerWrapperClass.prototype._getDataFromItem.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._handleTableEvent = function (oEvent) {
		return this.OInnerWrapperClass.prototype._handleTableEvent.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._isTableReady = function () {

		var oTable = this._getWrappedTable();

		if (oTable && oTable._bInvalid) {
			return false;
		}

		return FieldValueHelpTableWrapperBase.prototype._isTableReady.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._getWrappedTable = function () {
		var oTable = this.getTable();
		return oTable && oTable._oTable;
	};

	FieldValueHelpMdcTableWrapper.prototype._handleScrolling = function () {
		return this.OInnerWrapperClass.prototype._handleScrolling.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype.getDialogContent = function() {
		if (this.OInnerWrapperClass) {
			return this.OInnerWrapperClass.prototype.getDialogContent.apply(this, arguments);
		}
	};

	FieldValueHelpMdcTableWrapper.prototype.initialize = function() {
		if (this.OInnerWrapperClass) {
			return this.OInnerWrapperClass.prototype.initialize.apply(this, arguments);
		}
	};

	FieldValueHelpMdcTableWrapper.prototype.getSuggestionContent = function() {
		return this.getTable();
	};

	return FieldValueHelpMdcTableWrapper;
});
<commit_msg>[INTERNAL][FIX] MDC.FieldValueHelp: Reset bSearchTriggered on FieldHelp close.<commit_after>/*
 * ! ${copyright}
 */

sap.ui.define([
	'sap/ui/mdc/field/FieldValueHelpTableWrapperBase',
	"sap/ui/mdc/util/loadModules",
	"sap/base/util/deepEqual",
	"sap/ui/mdc/library",
	"sap/ui/mdc/enum/PersistenceMode",
	"sap/ui/mdc/p13n/Engine",
	'sap/ui/mdc/condition/FilterConverter',
	"sap/ui/thirdparty/jquery"
	], function(
		FieldValueHelpTableWrapperBase,
		loadModules,
		deepEqual,
		library,
		PersistenceMode,
		Engine,
		FilterConverter,
		jQuery
	) {
	"use strict";

	var SelectionMode = library.SelectionMode;

	var _mTableModules = {
		"Table": "sap/ui/mdc/field/FieldValueHelpUITableWrapper",
		"ResponsiveTable": "sap/ui/mdc/field/FieldValueHelpMTableWrapper"
	};

	/**
	 * Constructor for a new FieldValueHelpMdcTableWrapper.
	 *
	 * The FieldValueHelp element supports different types of content. This is a wrapper to use a
	 * sap.ui.mdc.Table control as content.
	 *
	 * @param {string} [sId] ID for the new control, generated automatically if no ID is given
	 * @param {object} [mSettings] Initial settings for the new control
	 * @class Wrapper to use a sap.m.Table control as content of a FieldValueHelp element
	 * @extends sap.ui.mdc.field.FieldValueHelpTableWrapperBase
	 * @version ${version}
	 * @constructor
	 * @private
	 * @ui5-restricted sap.fe
	 * @MDC_PUBLIC_CANDIDATE
 	 * @experimental
	 * @since 1.88.0
	 * @alias sap.ui.mdc.field.FieldValueHelpMdcTableWrapper
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var FieldValueHelpMdcTableWrapper = FieldValueHelpTableWrapperBase.extend("sap.ui.mdc.field.FieldValueHelpMdcTableWrapper", /** @lends sap.ui.mdc.field.FieldValueHelpMdcTableWrapper.prototype */
	{
		metadata: {
			library: "sap.ui.mdc",
			aggregations: {
				table: {
					type: "sap.ui.mdc.Table",
					multiple: false
				}
			},
			defaultAggregation: "table"
		}
	});

	FieldValueHelpMdcTableWrapper.prototype.init = function() {
		FieldValueHelpTableWrapperBase.prototype.init.apply(this, arguments);
		this.OInnerWrapperClass = null; // wrapper class for internal table type;
	};

	FieldValueHelpMdcTableWrapper.prototype.setParent = function(oParent, sAggregationName) {
		/* MDC.Table personalization inside ValueHelps should never be persisted,
		 * therefore we add the Fieldhelp to a PersistenceProvider with transient configuration.
		 */
		if (oParent) {
			Engine.getInstance().defaultProviderRegistry.attach(oParent, PersistenceMode.Transient);
		}
		FieldValueHelpTableWrapperBase.prototype.setParent.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._getStringType = function() {
		var oTable = this.getTable();
		var sType, oType = sType = oTable && oTable.getType();
		if (!oType) {
			sType = "Table"; // back to the default behaviour
		} else if (typeof oType === "object") {
			if (oType.isA("sap.ui.mdc.table.ResponsiveTableType")) {
				sType = "ResponsiveTable";
			} else {
				sType = "Table";
			}
		}
		return sType;
	};

	FieldValueHelpMdcTableWrapper.prototype.fieldHelpOpen = function(bSuggestion) {
		var oTable = this.getTable();
		if (oTable) {
			if (this.OInnerWrapperClass) {
				return this.OInnerWrapperClass.prototype.fieldHelpOpen.call(this, bSuggestion);
			}
		}
		return this;
	};

	FieldValueHelpMdcTableWrapper.prototype.fieldHelpClose = function() {
		this._bSearchTriggered = false;
		FieldValueHelpTableWrapperBase.prototype.fieldHelpClose.apply(this, arguments);
		return this;
	};

	/*
	* Provides a table wrapper class for dealing with specifics of mdc.tables inner table whenever the wrappers table aggregation or a given mdc.tables _content aggregation receive a new table.
	* The wrapper classes initialize method is applied to the current outer wrapper instance and cleanup is done for an eventually already existing wrapper.
	*/
	FieldValueHelpMdcTableWrapper.prototype._updateInnerWrapperClass = function () {

		var sTableType = this._getStringType();
		var sModule = _mTableModules[sTableType];

		if (sModule && this._sInnerWrapperType !== sTableType) {
			this._sInnerWrapperType = sTableType;

			if (this.OInnerWrapperClass) {
				this.OInnerWrapperClass.prototype.dispose.apply(this);
				this.OInnerWrapperClass = null;
			}

			this._oInnerWrapperClassPromise = loadModules(sModule).then(function (aModules) {
				this.OInnerWrapperClass = aModules[0];
				this.OInnerWrapperClass.prototype.initialize.apply(this);
			}.bind(this));
		}
	};

	/*
	* Adjust the tables layout depending on fields maxConditions and suggestion/dialog mode. Additionally uses inner wrapper class to adjust inner table
	*/
	FieldValueHelpMdcTableWrapper.prototype._adjustTable = function (bSuggestion) {

		var oTable = this.getTable();

		if (oTable) {

			var oParent = this.getParent();

			if (oParent) {
				oTable.setHeight("100%");
				oTable.setSelectionMode(this._getMaxConditions() === 1 ? SelectionMode.Single : SelectionMode.Multi);

				var oFieldHelp = this._getFieldHelp();
				var oFilterBar = oFieldHelp._getFilterBar();
				var bFilterChange = oFilterBar && oTable.getFilter() !== oFilterBar.getId();
				if (bFilterChange) {
					oTable.setFilter(oFilterBar);
				}

			}

			if (this.OInnerWrapperClass) {
				this.OInnerWrapperClass.prototype._adjustTable.call(this, bSuggestion);
			}
		}
	};

	FieldValueHelpMdcTableWrapper.prototype.exit = function() {
		var oParent = this.getParent();
		if (oParent) {
			Engine.getInstance().defaultProviderRegistry.detach(oParent);
		}

		this._oCurrentConditions = null;
		this._bSuggestion = null;

		if (this._oInnerWrapperClassPromise) {
			this._oInnerWrapperClassPromise = null;
		}
		if (this.OInnerWrapperClass) {
			this.OInnerWrapperClass.prototype.dispose.apply(this);
			this.OInnerWrapperClass = null;
		}

		this._sInnerWrapperType = null;
		this._bSearchTriggered = null;

		FieldValueHelpTableWrapperBase.prototype.exit.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype.isSuspended = function() {
		var oTable = this.getTable();
		var oListBinding = this.getListBinding();
		return oListBinding ? oListBinding.isSuspended() : oTable && !oTable.getAutoBindOnInit();
	};

	FieldValueHelpMdcTableWrapper.prototype.getListBinding = function() {
		var oTable = this.getTable();
		return oTable && oTable.getRowBinding();
	};

	// TODO: This is a hack to make the m.Table itemPress work as it seems to be suppressed in mdc.Table for some reason.

	var oMDCTableDelegate = {
		onmouseover: function (oEvent) {
			var oItem = jQuery(oEvent.target).control(0);
			if (oItem && oItem.isA("sap.m.ColumnListItem")) {
				oItem.setType("Active");
			}
		}
	};
	var _handleOuterDelegate = function (oTable, bAdd) {
		if (bAdd) {
			oTable.addDelegate(oMDCTableDelegate, true, this);
			return;
		}
		oTable.removeDelegate(oMDCTableDelegate);
	};

	// ------ >

	FieldValueHelpMdcTableWrapper.prototype._handleTableChanged = function (sMutation, oTable) {
		var oInnerTable;
		if (sMutation === "insert") {
			this._updateInnerWrapperClass();
			_handleOuterDelegate.call(this, oTable, true);

			oInnerTable = this._getWrappedTable();
			if (oInnerTable) {
				this._handleInnerTableChanged("insert", oInnerTable);
			}
			this._oObserver.observe(oTable, {aggregations: ["_content"]});
		} else {
			_handleOuterDelegate.call(this, oTable);
			oInnerTable = oTable._oTable; // as _getWrappedTable will not return a table right now
			if (oInnerTable) {
				this._handleInnerTableChanged(sMutation, oInnerTable);
			}
			this._oObserver.unobserve(oTable);
		}
	};

	/*
	* Hide toolbar for now
	*/
	FieldValueHelpMdcTableWrapper.prototype._handleToolbarExtensions = function (oInnerTable) {

		if (oInnerTable.mAggregations["extension"] && oInnerTable.mAggregations["extension"].length) {
			oInnerTable.getAggregation("extension").forEach(function (oExt) {
				oExt.setVisible(false);
			});
		}

		if (oInnerTable.mAggregations["headerToolbar"]) {
			var oToolbar = oInnerTable.getAggregation("headerToolbar");
			oToolbar.setVisible(false);
		}
	};

	FieldValueHelpMdcTableWrapper.prototype._handleInnerTableChanged = function (sMutation, oInnerTable) {
		if (sMutation === "insert") {
			this._updateInnerWrapperClass();
			this._handleToolbarExtensions(oInnerTable);
			this._oObserver.observe(oInnerTable, {bindings: ["rows"]});
		}

		this._oInnerWrapperClassPromise.then(function() {
			this.OInnerWrapperClass.prototype._handleTableChanged.call(this, sMutation, oInnerTable);
			this.getTable().initialized().then(function () {
				this.fireDataUpdate({contentChange: true});
			}.bind(this));
		}.bind(this));
	};

	FieldValueHelpMdcTableWrapper.prototype.applyFilters = function(aFilters, sSearch, oFilterBar) {

		var oTable = this.getTable();

		if (oTable && oFilterBar) {
			var oListBinding = this.getListBinding();
			var bListBindingSuspended = oListBinding && oListBinding.isSuspended();
			var oFieldHelp = this._getFieldHelp();

			if (oListBinding && !bListBindingSuspended && !this._bSearchTriggered) {
				var sFBSearch = oFilterBar.getSearch() || "";
				var sBindingSearch = oListBinding.mParameters.$search || "";
				var oCurrentFilterBarConditions = oFilterBar.getConditions();
				var oConditionTypes = oFieldHelp._getTypesForConditions(oCurrentFilterBarConditions);
				var oCreatedFBFilters = oCurrentFilterBarConditions && oConditionTypes && FilterConverter.createFilters(oCurrentFilterBarConditions, oConditionTypes, undefined, oFieldHelp.getCaseSensitive());
				var aFBFilters = oCreatedFBFilters ? [].concat(oCreatedFBFilters) : [];
				var aBindingFilters = oListBinding.aApplicationFilters.reduce(function (aResult, oFilter) {
					return aResult.concat(oFilter._bMultiFilter ? oFilter.aFilters : oFilter);
				}, []);
				var bFiltersChanged = !deepEqual(aFBFilters, aBindingFilters);
				var bSearchChanged = sFBSearch !== sBindingSearch;
				var bTableHasOverlay = oTable._oTable && oTable._oTable.getShowOverlay && oTable._oTable.getShowOverlay();

				if (bFiltersChanged || bSearchChanged || bTableHasOverlay) {
					this._handleScrolling();
					oFilterBar.triggerSearch();
					this._bSearchTriggered = true;
				}
			}

			if (bListBindingSuspended) {
				oListBinding.resume();
			}

			if (!oListBinding && oTable.getAutoBindOnInit()) {
				this._oTablePromise.then(function () {
					if (!this._bIsBeingDestroyed) {
						this.applyFilters(aFilters, sSearch, oFilterBar);
					}
				}.bind(this));
			}
		}
	};

	FieldValueHelpMdcTableWrapper.prototype._observeChanges = function (oChanges, bNoSelection) {

		if (oChanges.name === "_content") {
			this._handleInnerTableChanged(oChanges.mutation, oChanges.child);
		}

		if (this.OInnerWrapperClass) {
			this.OInnerWrapperClass.prototype._observeChanges.call(this, oChanges, true);
		} else {
			FieldValueHelpTableWrapperBase.prototype._observeChanges.call(this, oChanges, true);
		}
	};

	FieldValueHelpMdcTableWrapper.prototype._handleUpdateFinished = function (oEvent) {
		this._bSearchTriggered = false;
		return this.OInnerWrapperClass.prototype._handleUpdateFinished.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._handleEvents = function (oEvent) {
		if (this.OInnerWrapperClass) {
			return this.OInnerWrapperClass.prototype._handleEvents.apply(this, arguments);
		}
	};

	FieldValueHelpMdcTableWrapper.prototype._handleItemPress = function (oEvent) {
		return this.OInnerWrapperClass.prototype._handleItemPress.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._handleSelectionChange = function (oEvent) {
		var bIsTableReady = this._isTableReady();
		return this._iRunningTableSelectionUpdates || !bIsTableReady || this._bBusy ? undefined : this._fireSelectionChange.call(this, false);
	};

	FieldValueHelpMdcTableWrapper.prototype._getTableItems = function (bSelectedOnly, bNoVirtual) {
		return this.OInnerWrapperClass.prototype._getTableItems.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._modifyTableSelection = function (aItems, oItem, bSelected, iItemIndex) {
		return this.OInnerWrapperClass.prototype._modifyTableSelection.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._getDataFromItem = function (oItem, aInParameters, aOutParameters) {
		return this.OInnerWrapperClass.prototype._getDataFromItem.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._handleTableEvent = function (oEvent) {
		return this.OInnerWrapperClass.prototype._handleTableEvent.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._isTableReady = function () {

		var oTable = this._getWrappedTable();

		if (oTable && oTable._bInvalid) {
			return false;
		}

		return FieldValueHelpTableWrapperBase.prototype._isTableReady.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype._getWrappedTable = function () {
		var oTable = this.getTable();
		return oTable && oTable._oTable;
	};

	FieldValueHelpMdcTableWrapper.prototype._handleScrolling = function () {
		return this.OInnerWrapperClass.prototype._handleScrolling.apply(this, arguments);
	};

	FieldValueHelpMdcTableWrapper.prototype.getDialogContent = function() {
		if (this.OInnerWrapperClass) {
			return this.OInnerWrapperClass.prototype.getDialogContent.apply(this, arguments);
		}
	};

	FieldValueHelpMdcTableWrapper.prototype.initialize = function() {
		if (this.OInnerWrapperClass) {
			return this.OInnerWrapperClass.prototype.initialize.apply(this, arguments);
		}
	};

	FieldValueHelpMdcTableWrapper.prototype.getSuggestionContent = function() {
		return this.getTable();
	};

	return FieldValueHelpMdcTableWrapper;
});
<|endoftext|>


<commit_before>const _ = require('lodash');
const debug = require('debug')('W2:portal:extractPageView');
const fs = require('fs');
const path = require('path');
const Promise = require('bluebird');
const RoutesInfo = require('@quoin/expressjs-routes-info');
const urlTemplate = require('url-template');

const basicTypes = require('./../../../../lib/core/basic-types');
const convertCustomLinks = require('./../convert-custom-links');
const createObjResource = require('./create-obj-resource');
const embed = require('./embed');
const sortItems = require('./sort-items');

const IMAGE_PATH = urlTemplate.parse('/public/iic_images/{ImageURL}'); // FIXME: Hard-coded path.
const CONTENT_LINK_RE = require('./../../../../lib/core/content-link-re');

function parseLinks(overviews) {
    if (overviews) {
        return overviews.map((overview) => {
            if (overview && overview.Content && overview.Content.match(CONTENT_LINK_RE)) {
                const contentBasicProperty = _.filter(overview.basicProperties, (prop) => prop.name === 'Content'); // FIXME: Hard-coded
                overview.containsHTML = contentBasicProperty.length && contentBasicProperty[0].propertyType === basicTypes.Text;
                if (overview.containsHTML) {
                    overview.Content = convertCustomLinks(overview.Content);
                }
            }
            return overview;
        });
    }
    return overviews;
}

function extractRelationship(req, resource, persistence, hsEntity, entity) {
    const relationship = hsEntity.getRelationship();

    return Promise.resolve()
        .then(() => relationship.getDocuments(persistence, entity))
        .then((references) => {
            const onlyExistingReferences = references.filter((reference) => reference.id && reference.type);
            return Promise.map(onlyExistingReferences, (reference) => {
                const referenceResource = createObjResource(reference, true);
                resource.styles = {
                    CSV: (hsEntity.style === 'CSV'),
                    Preview: (hsEntity.style === 'Preview'),
                    Table: (hsEntity.style === 'Table'),
                    Tile: (hsEntity.style === 'Tile')
                };
                if (hsEntity.style === 'Preview') {
                    const referenceEntity = hsEntity.getRelationship().getTargetEntity();
                    return referenceEntity.getOverview(persistence, reference)
                        .then(parseLinks)
                        .then((overviews) => {
                            if (overviews && overviews.length) {
                                return overviews[0];
                            }
                            return [];
                        })
                        .then(convertToResource.bind(null, req))
                        .then((overview) => {
                            if (!_.isArray(overview)) {
                                referenceResource.embed('overview', overview);
                            }
                            return referenceResource;
                        })
                        .catch((err) => {
                            // The entity does not offer a relationship named
                            // 'Overview'?
                            debug(`Could not find overview for: reference=`, reference);
                            debug(`Could not find overview for: referenceEntity=`, referenceEntity);
                            debug(`Could not find overview: Error=`, err);
                            return referenceResource;
                        });
                }
                return referenceResource;
            });
        })
        .then((references) => {
            const relationshipResource = createObjResource(relationship, true);
            relationshipResource.embed('references', references);
            resource.embed('relationships', relationshipResource);
            return relationshipResource;
        });
}

function imagePath(req, image) {
    const publicFolder = req.app.get('public-folder');
    const publicFolderPath = req.app.get('public-folder-path');

    let filePath;

    if (image && image.ImageURL && image.ImageURL.indexOf(publicFolderPath) === 0) {
        filePath = path.join(publicFolder, image.ImageURL.substring(publicFolderPath.length));
    } else {
        filePath = path.join(publicFolder, 'iic_images', image.ImageURL || '');
        image.ImageURL = IMAGE_PATH.expand(image);
    }

    try {
        const stats = fs.lstatSync(filePath);
        if (!stats.isFile() && !/^(http|\?)/.test(image.ImageURL)) {
            image.ImageURL = '';
        }
    } catch (e) {
        image.ImageURL = '';
    }
}

function customResource(req, key, item) {
    const resource = convertToResource(req, item);
    if (key === 'Target') {
        resource.link('preview', RoutesInfo.expand('W2:portal:preview', {
            type: item.type,
            id: item.id
        }));
    }
    return resource;
}

function convertToResource(req, data) {
    if (!data) {
        return null;
    }

    if (_.isArray(data)) {
        return data.map(convertToResource.bind(null, req));
    }

    if (data.type === 'Image') {
        imagePath(req, data);
    }

    const basicProperties = _.reduce(
        data,
        (memo, value, key) => {
            if (!_.isArray(value)) {
                return _.extend(memo, {
                    [key]: value
                });
            }
            return memo;
        },
        {}
    );

    let propsToPick = null;
    if (data.basicProperties && data.basicProperties.length) {
        propsToPick = data.basicProperties.reduce((memo, value) => {
            memo.push(value.name);
            return memo;
        }, []);
    }

    const resource = createObjResource(basicProperties, true, propsToPick);

    _.forEach(data, (value, key) => {
        if (_.isArray(value)) {
            resource.embed(key, value.map(customResource.bind(null, req, key)));
        }
    });

    if (resource.type === 'ImageArea') {
        if (resource.HRef) {
            resource.link('target', resource.HRef);
        } else if (resource._embedded && resource._embedded.Targets && resource._embedded.Targets.length) {
            resource.link('target', resource._embedded.Targets[0]._links.self.href);
            resource.link('preview', resource._embedded.Targets[0]._links.preview.href);
        }
    }

    return resource;
}

function createOverviewPanel(req, persistence, hsCurrentEntity, currentInstance) {
    return Promise.resolve()
        // Find the overview.
        .then(() => hsCurrentEntity.getOverview(persistence, currentInstance))
        .then(parseLinks)
        .then(convertToResource.bind(null, req))
        .then((overviews) => {
            const resource = createObjResource({
                alternatingColors: false,
                type: 'Overview'
            });

            resource.embed('overviews', overviews);
            return resource;
        });
}

function addSeparatorPanelItems(panel, items) {
    panel.separatorPanelItems.forEach((item) => {
        items.push(createObjResource(item));
    });
    return items;
}

function addRelationshipPanelItems(req, panel, persistence, entity, items) {
    return Promise.map(
        panel.relationshipPanelItems,
        (item) => {
            const itemResource = createObjResource(item);
            items.push(itemResource);
            return extractRelationship(req, itemResource, persistence, item, entity);
        }
    ).then(() => items);
}

function addBasicPropertyPanelItems(panel, entity, items) {
    panel.basicPropertyPanelItems.forEach((item) => {
        item.value = entity[item.name];
        const itemResource = createObjResource(item);
        itemResource.model = {
            propertyType: item.basicProperty[0].propertyType
        };
        items.push(itemResource);
    });
    return items;
}

function addEnumPanelItems(panel, entity, items) {
    panel.enumPanelItems.forEach((item) => {
        item.value = entity[item.name];
        const itemResource = createObjResource(item);
        items.push(itemResource);
    });
    return items;
}

module.exports = (req, responseResource, persistence, hsEntity, entity) => Promise.resolve()
    .then(() => hsEntity.getPageView('DefaultPortalView'))
    .then((pageView) => pageView.getPanels())
    .then((panels) => {
        const embeddedPanels = [];
        return Promise.map(panels,
            (panel, panelIndex) => {
                const panelResource = createObjResource(panel);
                embeddedPanels.push(panelResource);

                return Promise.resolve([])
                    .then((items) => addSeparatorPanelItems(panel, items))
                    .then((items) => addRelationshipPanelItems(req, panel, persistence, entity, items))
                    .then((items) => addBasicPropertyPanelItems(panel, entity, items))
                    .then((items) => addEnumPanelItems(panel, entity, items))
                    .then((items) => sortItems(items))
                    .then((items) => embed(panelResource, 'panelItems', items));
            }
        )
            .then(() => createOverviewPanel(req, persistence, hsEntity, entity))
            .then((overviewPanel) => {
                if (overviewPanel) {
                // We increment the position becase we will add the overview at
                // the first position of the panels.
                    embeddedPanels.forEach((panel) => {
                    // It is some time a Number, some time a String.
                        panel.position = Number(panel.position) + 1;
                    });
                    overviewPanel.position = 0;
                    embeddedPanels.unshift(overviewPanel);
                    embeddedPanels.sort((a, b) => a.position - b.position);
                }
                return embeddedPanels;
            });
    })
    .then((panels) => responseResource.embed('panels', panels))
;
<commit_msg>Fixed ordering of overview paragraphs. Fixes #61<commit_after>const _ = require('lodash');
const debug = require('debug')('W2:portal:extractPageView');
const fs = require('fs');
const path = require('path');
const Promise = require('bluebird');
const RoutesInfo = require('@quoin/expressjs-routes-info');
const urlTemplate = require('url-template');
const warpjsUtils = require('@warp-works/warpjs-utils');

const basicTypes = require('./../../../../lib/core/basic-types');
const convertCustomLinks = require('./../convert-custom-links');
const createObjResource = require('./create-obj-resource');
const embed = require('./embed');
const sortItems = require('./sort-items');

const IMAGE_PATH = urlTemplate.parse('/public/iic_images/{ImageURL}'); // FIXME: Hard-coded path.
const CONTENT_LINK_RE = require('./../../../../lib/core/content-link-re');

function parseLinks(overviews) {
    if (overviews) {
        return overviews.map((overview) => {
            if (overview && overview.Content && overview.Content.match(CONTENT_LINK_RE)) {
                const contentBasicProperty = _.filter(overview.basicProperties, (prop) => prop.name === 'Content'); // FIXME: Hard-coded
                overview.containsHTML = contentBasicProperty.length && contentBasicProperty[0].propertyType === basicTypes.Text;
                if (overview.containsHTML) {
                    overview.Content = convertCustomLinks(overview.Content);
                }
            }
            return overview;
        });
    }
    return overviews;
}

function extractRelationship(req, resource, persistence, hsEntity, entity) {
    const relationship = hsEntity.getRelationship();

    return Promise.resolve()
        .then(() => relationship.getDocuments(persistence, entity))
        .then((references) => {
            const onlyExistingReferences = references.filter((reference) => reference.id && reference.type);
            return Promise.map(onlyExistingReferences, (reference) => {
                const referenceResource = createObjResource(reference, true);
                resource.styles = {
                    CSV: (hsEntity.style === 'CSV'),
                    Preview: (hsEntity.style === 'Preview'),
                    Table: (hsEntity.style === 'Table'),
                    Tile: (hsEntity.style === 'Tile')
                };
                if (hsEntity.style === 'Preview') {
                    const referenceEntity = hsEntity.getRelationship().getTargetEntity();
                    return referenceEntity.getOverview(persistence, reference)
                        .then(parseLinks)
                        .then((overviews) => {
                            if (overviews && overviews.length) {
                                return overviews[0];
                            }
                            return [];
                        })
                        .then(convertToResource.bind(null, req))
                        .then((overview) => {
                            if (!_.isArray(overview)) {
                                referenceResource.embed('overview', overview);
                            }
                            return referenceResource;
                        })
                        .catch((err) => {
                            // The entity does not offer a relationship named
                            // 'Overview'?
                            debug(`Could not find overview for: reference=`, reference);
                            debug(`Could not find overview for: referenceEntity=`, referenceEntity);
                            debug(`Could not find overview: Error=`, err);
                            return referenceResource;
                        });
                }
                return referenceResource;
            });
        })
        .then((references) => {
            const relationshipResource = createObjResource(relationship, true);
            relationshipResource.embed('references', references);
            resource.embed('relationships', relationshipResource);
            return relationshipResource;
        });
}

function imagePath(req, image) {
    const publicFolder = req.app.get('public-folder');
    const publicFolderPath = req.app.get('public-folder-path');

    let filePath;

    if (image && image.ImageURL && image.ImageURL.indexOf(publicFolderPath) === 0) {
        filePath = path.join(publicFolder, image.ImageURL.substring(publicFolderPath.length));
    } else {
        filePath = path.join(publicFolder, 'iic_images', image.ImageURL || '');
        image.ImageURL = IMAGE_PATH.expand(image);
    }

    try {
        const stats = fs.lstatSync(filePath);
        if (!stats.isFile() && !/^(http|\?)/.test(image.ImageURL)) {
            image.ImageURL = '';
        }
    } catch (e) {
        image.ImageURL = '';
    }
}

function customResource(req, key, item) {
    const resource = convertToResource(req, item);
    if (key === 'Target') {
        resource.link('preview', RoutesInfo.expand('W2:portal:preview', {
            type: item.type,
            id: item.id
        }));
    }
    return resource;
}

function convertToResource(req, data) {
    if (!data) {
        return null;
    }

    if (_.isArray(data)) {
        return data.map(convertToResource.bind(null, req));
    }

    if (data.type === 'Image') {
        imagePath(req, data);
    }

    const basicProperties = _.reduce(
        data,
        (memo, value, key) => {
            if (!_.isArray(value)) {
                return _.extend(memo, {
                    [key]: value
                });
            }
            return memo;
        },
        {}
    );

    let propsToPick = null;
    if (data.basicProperties && data.basicProperties.length) {
        propsToPick = data.basicProperties.reduce((memo, value) => {
            memo.push(value.name);
            return memo;
        }, []);
    }

    const resource = createObjResource(basicProperties, true, propsToPick);

    _.forEach(data, (value, key) => {
        if (_.isArray(value)) {
            resource.embed(key, value.map(customResource.bind(null, req, key)));
        }
    });

    if (resource.type === 'ImageArea') {
        if (resource.HRef) {
            resource.link('target', resource.HRef);
        } else if (resource._embedded && resource._embedded.Targets && resource._embedded.Targets.length) {
            resource.link('target', resource._embedded.Targets[0]._links.self.href);
            resource.link('preview', resource._embedded.Targets[0]._links.preview.href);
        }
    }

    return resource;
}

function createOverviewPanel(req, persistence, hsCurrentEntity, currentInstance) {
    return Promise.resolve()
        // Find the overview.
        .then(() => hsCurrentEntity.getOverview(persistence, currentInstance))
        .then(parseLinks)
        .then(convertToResource.bind(null, req))
        .then((overviews) => overviews.sort(warpjsUtils.byPositionThenName))
        .then((overviews) => {
            const resource = createObjResource({
                alternatingColors: false,
                type: 'Overview'
            });

            resource.embed('overviews', overviews);
            return resource;
        });
}

function addSeparatorPanelItems(panel, items) {
    panel.separatorPanelItems.forEach((item) => {
        items.push(createObjResource(item));
    });
    return items;
}

function addRelationshipPanelItems(req, panel, persistence, entity, items) {
    return Promise.map(
        panel.relationshipPanelItems,
        (item) => {
            const itemResource = createObjResource(item);
            items.push(itemResource);
            return extractRelationship(req, itemResource, persistence, item, entity);
        }
    ).then(() => items);
}

function addBasicPropertyPanelItems(panel, entity, items) {
    panel.basicPropertyPanelItems.forEach((item) => {
        item.value = entity[item.name];
        const itemResource = createObjResource(item);
        itemResource.model = {
            propertyType: item.basicProperty[0].propertyType
        };
        items.push(itemResource);
    });
    return items;
}

function addEnumPanelItems(panel, entity, items) {
    panel.enumPanelItems.forEach((item) => {
        item.value = entity[item.name];
        const itemResource = createObjResource(item);
        items.push(itemResource);
    });
    return items;
}

module.exports = (req, responseResource, persistence, hsEntity, entity) => Promise.resolve()
    .then(() => hsEntity.getPageView('DefaultPortalView'))
    .then((pageView) => pageView.getPanels())
    .then((panels) => {
        const embeddedPanels = [];
        return Promise.map(panels,
            (panel, panelIndex) => {
                const panelResource = createObjResource(panel);
                embeddedPanels.push(panelResource);

                return Promise.resolve([])
                    .then((items) => addSeparatorPanelItems(panel, items))
                    .then((items) => addRelationshipPanelItems(req, panel, persistence, entity, items))
                    .then((items) => addBasicPropertyPanelItems(panel, entity, items))
                    .then((items) => addEnumPanelItems(panel, entity, items))
                    .then((items) => sortItems(items))
                    .then((items) => embed(panelResource, 'panelItems', items));
            }
        )
            .then(() => createOverviewPanel(req, persistence, hsEntity, entity))
            .then((overviewPanel) => {
                if (overviewPanel) {
                // We increment the position becase we will add the overview at
                // the first position of the panels.
                    embeddedPanels.forEach((panel) => {
                    // It is some time a Number, some time a String.
                        panel.position = Number(panel.position) + 1;
                    });
                    overviewPanel.position = 0;
                    embeddedPanels.unshift(overviewPanel);
                    embeddedPanels.sort((a, b) => a.position - b.position);
                }
                return embeddedPanels;
            });
    })
    .then((panels) => responseResource.embed('panels', panels))
;
<|endoftext|>


<commit_before>var JPAudioPlayerBlock = {
	validate:function(){
		var failed=0;
		if ($("#audioBlock-singleAudio input[name=fID]").val() <= 0) {
			alert(ccm_t('choose-file'));
			failed = 1;
		}
		if(failed){
			ccm_isBlockError=1;
			return false;
		}
		return true;
	}
}

ccmValidateBlockForm = function() { return JPAudioPlayerBlock.validate(); }
<commit_msg>Add note about block validation.<commit_after>/*
// Validation is currently broken in 5.7
var JPAudioPlayerBlock = {
	validate:function(){
		var failed=0;
		if ($("#audioBlock-singleAudio input[name=fID]").val() <= 0) {
			alert(ccm_t('choose-file'));
			failed = 1;
		}
		if(failed){
			ccm_isBlockError=1;
			return false;
		}
		return true;
	}
}

ccmValidateBlockForm = function() { return JPAudioPlayerBlock.validate(); }
*/<|endoftext|>


<commit_before>import React from 'react'

import {
  WS_STATUS_CONNECTING,
  WS_STATUS_CONNECTED,
  WS_STATUS_ERROR
} from '../js/constants'

import { connect }
  from 'react-redux'
import CircularProgress
  from 'material-ui/lib/circular-progress'

class Ui extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    const {
      ui : { status, error },
      sendMessage,
    } = this.props
    switch (status) {
      case WS_STATUS_CONNECTING:
        return (

            <CircularProgress size={1} />

        )
      case WS_STATUS_CONNECTED:
        return (
          <App sendMessage={sendMessage} />
        )
      case WS_STATUS_ERROR:
      default:
        return (
          <Dialog
            title   = 'Application error'
            actions = {[]}
            modal   = {true}
            open    = {true}>
            {error}
          </Dialog>
        )
    }
  }
}

const styles = {
  spinner: {
    width          : '100%',
    height         : '100%',
    display        : 'flex',
    justifyContent : 'center',
    alignItems     : 'center',
  }
}

const UiComponent = connect(state => ({
  app : state.app,
}))(Ui)

export default UiComponent
<commit_msg>add missing imports<commit_after>import React from 'react'

import {
  WS_STATUS_CONNECTING,
  WS_STATUS_CONNECTED,
  WS_STATUS_ERROR
} from '../js/constants'

import { connect }
  from 'react-redux'
import CircularProgress
  from 'material-ui/lib/circular-progress'
import Dialog
  from 'material-ui/lib/dialog'

class Ui extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    const {
      app : { status, error },
      sendMessage,
    } = this.props
    switch (status) {
      case WS_STATUS_CONNECTING:
        return (

            <CircularProgress size={1} />

        )
      case WS_STATUS_CONNECTED:
        return (
          <App sendMessage={sendMessage} />
        )
      case WS_STATUS_ERROR:
      default:
        return (
          <Dialog
            title   = 'Application error'
            actions = {[]}
            modal   = {true}
            open    = {true}>
            {error}
          </Dialog>
        )
    }
  }
}

const styles = {
  spinner: {
    width          : '100%',
    height         : '100%',
    display        : 'flex',
    justifyContent : 'center',
    alignItems     : 'center',
  }
}

const UiComponent = connect(state => ({
  app : state.app,
}))(Ui)

export default UiComponent
<|endoftext|>


<commit_before>var RSVP  = require('rsvp');
var chalk = require('chalk');

module.exports = {
  description: 'install ember-material-lite into a typical project',
  normalizeEntityName: function() {}, // no-op since we're just adding dependencies

  beforeInstall: function (options) {
    return RSVP.all([
      this.addBowerPackageToProject('material-design-lite', '~1.0.4')
    ]);
  },

  afterInstall: function () {
    return RSVP.all([
      this.addPackageToProject('ember-cli-sass', '^4.2.1'),
      this.addPackageToProject('ember-cli-autoprefixer', '~0.6.0'),
      this.addPackageToProject('ember-new-computed', '^1.0.3'),
      this.addPackageToProject('ember-truth-helpers', '~1.2.0'),
      this.addPackageToProject('ember-composability', '~0.3.0'),
    ]);
  }
};
<commit_msg>Upgrade ember-cli-sass to 5.3.1<commit_after>var RSVP  = require('rsvp');
var chalk = require('chalk');

module.exports = {
  description: 'install ember-material-lite into a typical project',
  normalizeEntityName: function() {}, // no-op since we're just adding dependencies

  beforeInstall: function (options) {
    return RSVP.all([
      this.addBowerPackageToProject('material-design-lite', '~1.0.4')
    ]);
  },

  afterInstall: function () {
    return RSVP.all([
      this.addPackageToProject('ember-cli-sass', '^5.3.1'),
      this.addPackageToProject('ember-cli-autoprefixer', '~0.6.0'),
      this.addPackageToProject('ember-new-computed', '^1.0.3'),
      this.addPackageToProject('ember-truth-helpers', '~1.2.0'),
      this.addPackageToProject('ember-composability', '~0.3.0'),
    ]);
  }
};
<|endoftext|>


<commit_before>describe('Timezone check', () => {
  // use strict is required by node 4
  'use strict';

  //@todo: the module should behave independently from time zones.

});
<commit_msg>test: delete empty timezone spec<commit_after><|endoftext|>


<commit_before>(function($) {
  $.extend($.summernote.lang, {
    'fi-FI': {
      font: {
        bold: 'Lihavoitu',
        italic: 'Kursiivi',
        underline: 'Alleviivaa',
        clear: 'Tyhjennä muotoilu',
        height: 'Riviväli',
        name: 'Kirjasintyyppi',
        strikethrough: 'Yliviivaus',
        subscript: 'Subscript',
        superscript: 'Superscript',
        size: 'Kirjasinkoko'
      },
      image: {
        image: 'Kuva',
        insert: 'Lisää kuva',
        resizeFull: 'Koko leveys',
        resizeHalf: 'Puolikas leveys',
        resizeQuarter: 'Neljäsosa leveys',
        floatLeft: 'Sijoita vasemmalle',
        floatRight: 'Sijoita oikealle',
        floatNone: 'Ei sijoitusta',
        shapeRounded: 'Shape: Rounded',
        shapeCircle: 'Shape: Circle',
        shapeThumbnail: 'Shape: Thumbnail',
        shapeNone: 'Shape: None',
        dragImageHere: 'Vedä kuva tähän',
        selectFromFiles: 'Valitse tiedostoista',
        maximumFileSize: 'Maximum file size',
        maximumFileSizeError: 'Maximum file size exceeded.',
        url: 'URL-osoitteen mukaan',
        remove: 'Poista kuva',
        original: 'Original'
      },
      video: {
        video: 'Video',
        videoLink: 'Linkki videoon',
        insert: 'Lisää video',
        url: 'Videon URL-osoite?',
        providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion tai Youku)'
      },
      link: {
        link: 'Linkki',
        insert: 'Lisää linkki',
        unlink: 'Poista linkki',
        edit: 'Muokkaa',
        textToDisplay: 'Näytettävä teksti',
        url: 'Linkin URL-osoite?',
        openInNewWindow: 'Avaa uudessa ikkunassa'
      },
      table: {
        table: 'Taulukko',
        addRowAbove: 'Add row above',
        addRowBelow: 'Add row below',
        addColLeft: 'Add column left',
        addColRight: 'Add column right',
        delRow: 'Delete row',
        delCol: 'Delete column',
        delTable: 'Delete table'
      },
      hr: {
        insert: 'Lisää vaakaviiva'
      },
      style: {
        style: 'Tyyli',
        p: 'Normaali',
        blockquote: 'Lainaus',
        pre: 'Koodi',
        h1: 'Otsikko 1',
        h2: 'Otsikko 2',
        h3: 'Otsikko 3',
        h4: 'Otsikko 4',
        h5: 'Otsikko 5',
        h6: 'Otsikko 6'
      },
      lists: {
        unordered: 'Luettelomerkitty luettelo',
        ordered: 'Numeroitu luettelo'
      },
      options: {
        help: 'Ohje',
        fullscreen: 'Koko näyttö',
        codeview: 'HTML-näkymä'
      },
      paragraph: {
        paragraph: 'Kappale',
        outdent: 'Pienennä sisennystä',
        indent: 'Suurenna sisennystä',
        left: 'Tasaus vasemmalle',
        center: 'Keskitä',
        right: 'Tasaus oikealle',
        justify: 'Tasaa'
      },
      color: {
        recent: 'Viimeisin väri',
        more: 'Lisää värejä',
        background: 'Taustaväri',
        foreground: 'Tekstin väri',
        transparent: 'Läpinäkyvä',
        setTransparent: 'Aseta läpinäkyväksi',
        reset: 'Palauta',
        resetToDefault: 'Palauta oletusarvoksi'
      },
      shortcut: {
        shortcuts: 'Pikanäppäimet',
        close: 'Sulje',
        textFormatting: 'Tekstin muotoilu',
        action: 'Toiminto',
        paragraphFormatting: 'Kappaleen muotoilu',
        documentStyle: 'Asiakirjan tyyli'
      },
      help: {
        'insertParagraph': 'Insert Paragraph',
        'undo': 'Undoes the last command',
        'redo': 'Redoes the last command',
        'tab': 'Tab',
        'untab': 'Untab',
        'bold': 'Set a bold style',
        'italic': 'Set a italic style',
        'underline': 'Set a underline style',
        'strikethrough': 'Set a strikethrough style',
        'removeFormat': 'Clean a style',
        'justifyLeft': 'Set left align',
        'justifyCenter': 'Set center align',
        'justifyRight': 'Set right align',
        'justifyFull': 'Set full align',
        'insertUnorderedList': 'Toggle unordered list',
        'insertOrderedList': 'Toggle ordered list',
        'outdent': 'Outdent on current paragraph',
        'indent': 'Indent on current paragraph',
        'formatPara': 'Change current block\'s format as a paragraph(P tag)',
        'formatH1': 'Change current block\'s format as H1',
        'formatH2': 'Change current block\'s format as H2',
        'formatH3': 'Change current block\'s format as H3',
        'formatH4': 'Change current block\'s format as H4',
        'formatH5': 'Change current block\'s format as H5',
        'formatH6': 'Change current block\'s format as H6',
        'insertHorizontalRule': 'Insert horizontal rule',
        'linkDialog.show': 'Show Link Dialog'
      },
      history: {
        undo: 'Kumoa',
        redo: 'Toista'
      },
      specialChar: {
        specialChar: 'SPECIAL CHARACTERS',
        select: 'Select Special characters'
      }
    }
  });
})(jQuery);
<commit_msg>Update Finnish translation<commit_after>(function($) {
  $.extend($.summernote.lang, {
    'fi-FI': {
      font: {
        bold: 'Lihavointi',
        italic: 'Kursivointi',
        underline: 'Alleviivaus',
        clear: 'Tyhjennä muotoilu',
        height: 'Riviväli',
        name: 'Kirjasintyyppi',
        strikethrough: 'Yliviivaus',
        subscript: 'Alaindeksi',
        superscript: 'Yläindeksi',
        size: 'Kirjasinkoko'
      },
      image: {
        image: 'Kuva',
        insert: 'Lisää kuva',
        resizeFull: 'Koko leveys',
        resizeHalf: 'Puolikas leveys',
        resizeQuarter: 'Neljäsosa leveys',
        floatLeft: 'Sijoita vasemmalle',
        floatRight: 'Sijoita oikealle',
        floatNone: 'Ei sijoitusta',
        shapeRounded: 'Muoto: Pyöristetty',
        shapeCircle: 'Muoto: Ympyrä',
        shapeThumbnail: 'Muoto: Esikatselukuva',
        shapeNone: 'Muoto: Ei muotoilua',
        dragImageHere: 'Vedä kuva tähän',
        selectFromFiles: 'Valitse tiedostoista',
        maximumFileSize: 'Maksimi tiedosto koko',
        maximumFileSizeError: 'Maksimi tiedosto koko ylitetty.',
        url: 'URL-osoitteen mukaan',
        remove: 'Poista kuva',
        original: 'Alkuperäinen'
      },
      video: {
        video: 'Video',
        videoLink: 'Linkki videoon',
        insert: 'Lisää video',
        url: 'Videon URL-osoite',
        providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion tai Youku)'
      },
      link: {
        link: 'Linkki',
        insert: 'Lisää linkki',
        unlink: 'Poista linkki',
        edit: 'Muokkaa',
        textToDisplay: 'Näytettävä teksti',
        url: 'Linkin URL-osoite',
        openInNewWindow: 'Avaa uudessa ikkunassa'
      },
      table: {
        table: 'Taulukko',
        addRowAbove: 'Lisää rivi yläpuolelle',
        addRowBelow: 'Lisää rivi alapuolelle',
        addColLeft: 'Lisää sarake vasemmalle puolelle',
        addColRight: 'Lisää sarake oikealle puolelle',
        delRow: 'Poista rivi',
        delCol: 'Poista sarake',
        delTable: 'Poista taulukko'
      },
      hr: {
        insert: 'Lisää vaakaviiva'
      },
      style: {
        style: 'Tyyli',
        p: 'Normaali',
        blockquote: 'Lainaus',
        pre: 'Koodi',
        h1: 'Otsikko 1',
        h2: 'Otsikko 2',
        h3: 'Otsikko 3',
        h4: 'Otsikko 4',
        h5: 'Otsikko 5',
        h6: 'Otsikko 6'
      },
      lists: {
        unordered: 'Luettelomerkitty luettelo',
        ordered: 'Numeroitu luettelo'
      },
      options: {
        help: 'Ohje',
        fullscreen: 'Koko näyttö',
        codeview: 'HTML-näkymä'
      },
      paragraph: {
        paragraph: 'Kappale',
        outdent: 'Pienennä sisennystä',
        indent: 'Suurenna sisennystä',
        left: 'Tasaa vasemmalle',
        center: 'Keskitä',
        right: 'Tasaa oikealle',
        justify: 'Tasaa'
      },
      color: {
        recent: 'Viimeisin väri',
        more: 'Lisää värejä',
        background: 'Korostusväri',
        foreground: 'Tekstin väri',
        transparent: 'Läpinäkyvä',
        setTransparent: 'Aseta läpinäkyväksi',
        reset: 'Palauta',
        resetToDefault: 'Palauta oletusarvoksi'
      },
      shortcut: {
        shortcuts: 'Pikanäppäimet',
        close: 'Sulje',
        textFormatting: 'Tekstin muotoilu',
        action: 'Toiminto',
        paragraphFormatting: 'Kappaleen muotoilu',
        documentStyle: 'Asiakirjan tyyli'
      },
      help: {
        'insertParagraph': 'Lisää kappale',
        'undo': 'Kumoa viimeisin komento',
        'redo': 'Tee uudelleen kumottu komento',
        'tab': 'Sarkain',
        'untab': 'Sarkainmerkin poisto',
        'bold': 'Lihavointi',
        'italic': 'Kursiivi',
        'underline': 'Alleviivaus',
        'strikethrough': 'Yliviivaus',
        'removeFormat': 'Poista asetetut tyylit',
        'justifyLeft': 'Tasaa vasemmalle',
        'justifyCenter': 'Keskitä',
        'justifyRight': 'Tasaa oikealle',
        'justifyFull': 'Tasaa',
        'insertUnorderedList': 'Luettelomerkillä varustettu lista',
        'insertOrderedList': 'Numeroitu lista',
        'outdent': 'Pienennä sisennystä',
        'indent': 'Suurenna sisennystä',
        'formatPara': 'Muuta kappaleen formaatti p',
        'formatH1': 'Muuta kappaleen formaatti H1',
        'formatH2': 'Muuta kappaleen formaatti H2',
        'formatH3': 'Muuta kappaleen formaatti H3',
        'formatH4': 'Muuta kappaleen formaatti H4',
        'formatH5': 'Muuta kappaleen formaatti H5',
        'formatH6': 'Muuta kappaleen formaatti H6',
        'insertHorizontalRule': 'Lisää vaakaviiva',
        'linkDialog.show': 'Lisää linkki'
      },
      history: {
        undo: 'Kumoa',
        redo: 'Toista'
      },
      specialChar: {
        specialChar: 'ERIKOISMERKIT',
        select: 'Valitse erikoismerkit'
      }
    }
  });
})(jQuery);
<|endoftext|>


<commit_before>/*global tarteaucitron */
tarteaucitron.lang = {
    "adblock": "Hola! Este sitio web es transparente y le da la opción de activar los servicios de terceros.",
    "adblock_call": "Por favor deshabilite su AdBlocker para comenzar a personalizar.",
    "reload": "Actualizar esta página",

    "alertBigScroll": "Al continuar para desplazarse,",
    "alertBigClick": "Si continuas navegando por este sitio web,",
    "alertBig": "estar permitiendo servicios terceros",

    "alertBigPrivacy": "Este sitio web usa cookies y te permite controlar lo que deseas activar",
    "alertSmall": "Gestionar servicios",
    "personalize": "Personalizar",
    "acceptAll": "OK, aceptar todas",
    "close": "Cerrar",

    "all": "Preference for all services",

    "info": "Protegiendo tu privacidad",
    "disclaimer": "Aceptando estos servicios terceros, estas aceptando sus cookies y el uso de tecnologías de rastreo necesarias para su correcto funcionamiento.",
    "allow": "Permitir",
    "deny": "Denegar",
    "noCookie": "Este servicio no usa cookie.",
    "useCookie": "Este servicio puede instalar",
    "useCookieCurrent": "Este servicio ha instalado",
    "useNoCookie": "Este servicio no ha instalado ninguna cookie.",
    "more": "Leer más",
    "source": "Ver sitio web oficial",
    "credit": "Gestor de cookies realizada por tarteaucitron.js",

    "fallback": "esta deshabilitado.",

    "ads": {
        "title": "Red de publicidad",
        "details": "Las redes publicitarias pueden generar ingresos mediante la venta de espacios publicitarios en el sitio."
    },
    "analytic": {
        "title": "Mediciión de audiencia",
        "details": "Los servicios de medición de audiencia se usan para generar asistencia estadísticas útiles para mejorar el sitio."
    },
    "social": {
        "title": "Redes sociales",
        "details": "Las redes sociales pueden aumentar la usabilidad del sitio web y ayudar a promoverlo a través de la contribución."
    },
    "video": {
        "title": "Videos",
        "details": "Los servicios para compartir videos ayudan a añadir contenido enriquecido en el sitio web y aumentar su visibilidad."
    },
    "comment": {
        "title": "Comentarios",
        "details": "El gestor de comentarios facilita la clasificación de comentarios y luchar contra spam."
    },
    "support": {
        "title": "Soporte",
        "details": "Los servicios de soporte te permiten contactar con el sitio web y ayudar a mejorarlo."
    },
    "api": {
        "title": "APIs",
        "details": "APIs se utilizan para cargar scripts: geolocalización, motor de búsqueda, traducciones, ..."
    },
    "other": {
        "title": "Otro",
        "details": "Servicios para mostrar contenido web."
    }
};
<commit_msg>Fixed #89 : spanish translation for settings<commit_after>/*global tarteaucitron */
tarteaucitron.lang = {
    "adblock": "Hola! Este sitio web es transparente y le da la opción de activar los servicios de terceros.",
    "adblock_call": "Por favor deshabilite su AdBlocker para empezar a personalizar los servicios.",
    "reload": "Actualizar esta página",

    "alertBigScroll": "Al continuar para desplazarse,",
    "alertBigClick": "Si continuas navegando por este sitio web,",
    "alertBig": "estar permitiendo servicios terceros",

    "alertBigPrivacy": "Este sitio web usa cookies y te permite controlar lo que deseas activar",
    "alertSmall": "Gestionar servicios",
    "personalize": "Personalizar",
    "acceptAll": "OK, aceptar todas",
    "close": "Cerrar",

    "all": "Ajustes para todos los servicios",

    "info": "Protegiendo tu privacidad",
    "disclaimer": "Aceptando estos servicios terceros, estas aceptando sus cookies y el uso de tecnologías de rastreo necesarias para su correcto funcionamiento.",
    "allow": "Permitir",
    "deny": "Denegar",
    "noCookie": "Este servicio no usa cookie.",
    "useCookie": "Este servicio puede instalar",
    "useCookieCurrent": "Este servicio ha instalado",
    "useNoCookie": "Este servicio no ha instalado ninguna cookie.",
    "more": "Leer más",
    "source": "Ver sitio web oficial",
    "credit": "Gestor de cookies realizada por tarteaucitron.js",

    "fallback": "está deshabilitado.",

    "ads": {
        "title": "Red de publicidad",
        "details": "Las redes publicitarias pueden generar ingresos mediante la venta de espacios publicitarios en el sitio."
    },
    "analytic": {
        "title": "Mediciión de audiencia",
        "details": "Los servicios de medición de audiencia se usan para generar asistencia estadísticas útiles para mejorar el sitio."
    },
    "social": {
        "title": "Redes sociales",
        "details": "Las redes sociales pueden aumentar la usabilidad del sitio web y ayudar a promoverlo a través de la contribución."
    },
    "video": {
        "title": "Videos",
        "details": "Los servicios para compartir videos ayudan a añadir contenido enriquecido en el sitio web y aumentar su visibilidad."
    },
    "comment": {
        "title": "Comentarios",
        "details": "El gestor de comentarios facilita la clasificación de comentarios y luchar contra spam."
    },
    "support": {
        "title": "Soporte",
        "details": "Los servicios de soporte te permiten contactar con el sitio web y ayudar a mejorarlo."
    },
    "api": {
        "title": "APIs",
        "details": "APIs se utilizan para cargar scripts: geolocalización, motor de búsqueda, traducciones, ..."
    },
    "other": {
        "title": "Otro",
        "details": "Servicios para mostrar contenido web."
    }
};
<|endoftext|>


<commit_before>/* eslint-env mocha */
//const languageProcessor = require('./languageProcessor')
const should = require('chai').should()

describe('languageProcessor', function () {
  beforeEach(() => {
  })

  describe('initialization', function () {
    it('simple get', function (done) {
      // const result = languageProcessor.processText('get')
      var hello = 'hello'
      hello.should.equal('hello')
      done()
    })
  })
})
<commit_msg>mocha tests<commit_after>/* eslint-env mocha */
// Above line makes it work with Mocha

//const languageProcessor = require('./languageProcessor')

describe('languageProcessor', function () {
  beforeEach(() => {
  })

  describe('initialization', function () {
    it('simple get', function (done) {
      // const result = languageProcessor.processText('get')
      var hello = 'hello'
      hello.should.equal('hello')
      done()
    })

    it('simple get2', function (done) {
      // const result = languageProcessor.processText('get')
      var hello = 'hello'
      hello.should.equal('hello')
      done()
    })
  })
})
<|endoftext|>


<commit_before>const suffix = ' ms'

module.exports = function logBenchmarks() {
	this.separator()

	let total = this.benchmarks.All

	Object.keys(this.benchmarks)
	.forEach(phase => {
		let time = this.benchmarks[phase]

		if(isNaN(parseInt(time)))
			return

		let timeString = time.toString()
		let spacer = ' '.repeat(Math.max(this.columns - phase.length - ':'.length - timeString.length - suffix.length, 0))
		let color = null

		if(time >= 1000)
			color = chalk.red
		else if(time >= 100)
			color = chalk.yellow
		else
			color = chalk.green

		console.log(`${phase}:${spacer}${color(timeString)}${chalk.dim(suffix)}`)
	})

	// Free memory
	delete this.benchmarks
}<commit_msg>Reverted due to restart problems<commit_after>const suffix = ' ms'

module.exports = function logBenchmarks() {
	this.separator()

	let total = this.benchmarks.All

	Object.keys(this.benchmarks)
	.forEach(phase => {
		let time = this.benchmarks[phase]

		if(isNaN(parseInt(time)))
			return

		let timeString = time.toString()
		let spacer = ' '.repeat(Math.max(this.columns - phase.length - ':'.length - timeString.length - suffix.length, 0))
		let color = null

		if(time >= 1000)
			color = chalk.red
		else if(time >= 100)
			color = chalk.yellow
		else
			color = chalk.green

		console.log(`${phase}:${spacer}${color(timeString)}${chalk.dim(suffix)}`)
	})
}<|endoftext|>


<commit_before>

function InvocationService(url, auth, auth_cb) {

    var _url = url;
    var deprecationWarningSent = false;

    function deprecationWarning() {
        if (!deprecationWarningSent) {
            deprecationWarningSent = true;
            if (!window.console) return;
            console.log(
                "DEPRECATION WARNING: '*_async' method names will be removed",
                "in a future version. Please use the identical methods without",
                "the'_async' suffix.");
        }
    }

    var _auth = auth ? auth : { 'token' : '', 'user_id' : ''};
    var _auth_cb = auth_cb;

    this.start_session = function (session_id, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.start_session",
        [session_id], 1, _callback, _errorCallback);
};

    this.start_session_async = function (session_id, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.start_session", [session_id], 1, _callback, _error_callback);
    };

    this.list_files = function (session_id, cwd, d, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.list_files",
        [session_id, cwd, d], 2, _callback, _errorCallback);
};

    this.list_files_async = function (session_id, cwd, d, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.list_files", [session_id, cwd, d], 2, _callback, _error_callback);
    };

    this.remove_files = function (session_id, cwd, filename, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.remove_files",
        [session_id, cwd, filename], 0, _callback, _errorCallback);
};

    this.remove_files_async = function (session_id, cwd, filename, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.remove_files", [session_id, cwd, filename], 0, _callback, _error_callback);
    };

    this.rename_file = function (session_id, cwd, from, to, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.rename_file",
        [session_id, cwd, from, to], 0, _callback, _errorCallback);
};

    this.rename_file_async = function (session_id, cwd, from, to, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.rename_file", [session_id, cwd, from, to], 0, _callback, _error_callback);
    };

    this.copy = function (session_id, cwd, from, to, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.copy",
        [session_id, cwd, from, to], 0, _callback, _errorCallback);
};

    this.copy_async = function (session_id, cwd, from, to, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.copy", [session_id, cwd, from, to], 0, _callback, _error_callback);
    };

    this.make_directory = function (session_id, cwd, directory, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.make_directory",
        [session_id, cwd, directory], 0, _callback, _errorCallback);
};

    this.make_directory_async = function (session_id, cwd, directory, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.make_directory", [session_id, cwd, directory], 0, _callback, _error_callback);
    };

    this.remove_directory = function (session_id, cwd, directory, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.remove_directory",
        [session_id, cwd, directory], 0, _callback, _errorCallback);
};

    this.remove_directory_async = function (session_id, cwd, directory, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.remove_directory", [session_id, cwd, directory], 0, _callback, _error_callback);
    };

    this.change_directory = function (session_id, cwd, directory, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.change_directory",
        [session_id, cwd, directory], 1, _callback, _errorCallback);
};

    this.change_directory_async = function (session_id, cwd, directory, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.change_directory", [session_id, cwd, directory], 1, _callback, _error_callback);
    };

    this.put_file = function (session_id, filename, contents, cwd, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.put_file",
        [session_id, filename, contents, cwd], 0, _callback, _errorCallback);
};

    this.put_file_async = function (session_id, filename, contents, cwd, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.put_file", [session_id, filename, contents, cwd], 0, _callback, _error_callback);
    };

    this.get_file = function (session_id, filename, cwd, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.get_file",
        [session_id, filename, cwd], 1, _callback, _errorCallback);
};

    this.get_file_async = function (session_id, filename, cwd, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.get_file", [session_id, filename, cwd], 1, _callback, _error_callback);
    };

    this.run_pipeline = function (session_id, pipeline, input, max_output_size, cwd, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.run_pipeline",
        [session_id, pipeline, input, max_output_size, cwd], 2, _callback, _errorCallback);
};

    this.run_pipeline_async = function (session_id, pipeline, input, max_output_size, cwd, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.run_pipeline", [session_id, pipeline, input, max_output_size, cwd], 2, _callback, _error_callback);
    };

    this.run_pipeline2 = function (session_id, pipeline, input, max_output_size, cwd, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.run_pipeline2",
        [session_id, pipeline, input, max_output_size, cwd], 3, _callback, _errorCallback);
};

    this.run_pipeline2_async = function (session_id, pipeline, input, max_output_size, cwd, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.run_pipeline2", [session_id, pipeline, input, max_output_size, cwd], 3, _callback, _error_callback);
    };

    this.exit_session = function (session_id, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.exit_session",
        [session_id], 0, _callback, _errorCallback);
};

    this.exit_session_async = function (session_id, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.exit_session", [session_id], 0, _callback, _error_callback);
    };

    this.valid_commands = function (_callback, _errorCallback) {
    return json_call_ajax("InvocationService.valid_commands",
        [], 1, _callback, _errorCallback);
};

    this.valid_commands_async = function (_callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.valid_commands", [], 1, _callback, _error_callback);
    };

    this.installed_modules = function (_callback, _errorCallback) {
    return json_call_ajax("InvocationService.installed_modules",
        [], 1, _callback, _errorCallback);
};

    this.installed_modules_async = function (_callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.installed_modules", [], 1, _callback, _error_callback);
    };

    this.get_tutorial_text = function (step, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.get_tutorial_text",
        [step], 3, _callback, _errorCallback);
};

    this.get_tutorial_text_async = function (step, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.get_tutorial_text", [step], 3, _callback, _error_callback);
    };

    /*
     * JSON call using jQuery method.
     */
    function json_call_ajax(method, params, numRets, callback, errorCallback) {
        var deferred = $.Deferred();

        if (typeof callback === 'function') {
           deferred.done(callback);
        }

        if (typeof errorCallback === 'function') {
           deferred.fail(errorCallback);
        }

        var rpc = {
            params : params,
            method : method,
            version: "1.1",
            id: String(Math.random()).slice(2),
        };

        var beforeSend = null;
        var token = (_auth_cb && typeof _auth_cb === 'function') ? _auth_cb()
            : (_auth.token ? _auth.token : null);
        if (token != null) {
            beforeSend = function (xhr) {
                xhr.setRequestHeader("Authorization", _auth.token);
            }
        }

        jQuery.ajax({
            url: _url,
            dataType: "text",
            type: 'POST',
            processData: false,
            data: JSON.stringify(rpc),
            beforeSend: beforeSend,
            success: function (data, status, xhr) {
                var result;
                try {
                    var resp = JSON.parse(data);
                    result = (numRets === 1 ? resp.result[0] : resp.result);
                } catch (err) {
                    deferred.reject({
                        status: 503,
                        error: err,
                        url: _url,
                        resp: data
                    });
                    return;
                }
                deferred.resolve(result);
            },
            error: function (xhr, textStatus, errorThrown) {
                var error;
                if (xhr.responseText) {
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        error = resp.error;
                    } catch (err) { // Not JSON
                        error = "Unknown error - " + xhr.responseText;
                    }
                } else {
                    error = "Unknown Error";
                }
                deferred.reject({
                    status: 500,
                    error: error
                });
            }
        });
        return deferred.promise();
    }
}

<commit_msg>fixed erroneously generated token param<commit_after>

function InvocationService(url, auth, auth_cb) {

    var _url = url;
    var deprecationWarningSent = false;

    function deprecationWarning() {
        if (!deprecationWarningSent) {
            deprecationWarningSent = true;
            if (!window.console) return;
            console.log(
                "DEPRECATION WARNING: '*_async' method names will be removed",
                "in a future version. Please use the identical methods without",
                "the'_async' suffix.");
        }
    }

    var _auth = auth ? auth : { 'token' : '', 'user_id' : ''};
    var _auth_cb = auth_cb;

    this.start_session = function (session_id, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.start_session",
        [session_id], 1, _callback, _errorCallback);
};

    this.start_session_async = function (session_id, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.start_session", [session_id], 1, _callback, _error_callback);
    };

    this.list_files = function (session_id, cwd, d, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.list_files",
        [session_id, cwd, d], 2, _callback, _errorCallback);
};

    this.list_files_async = function (session_id, cwd, d, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.list_files", [session_id, cwd, d], 2, _callback, _error_callback);
    };

    this.remove_files = function (session_id, cwd, filename, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.remove_files",
        [session_id, cwd, filename], 0, _callback, _errorCallback);
};

    this.remove_files_async = function (session_id, cwd, filename, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.remove_files", [session_id, cwd, filename], 0, _callback, _error_callback);
    };

    this.rename_file = function (session_id, cwd, from, to, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.rename_file",
        [session_id, cwd, from, to], 0, _callback, _errorCallback);
};

    this.rename_file_async = function (session_id, cwd, from, to, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.rename_file", [session_id, cwd, from, to], 0, _callback, _error_callback);
    };

    this.copy = function (session_id, cwd, from, to, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.copy",
        [session_id, cwd, from, to], 0, _callback, _errorCallback);
};

    this.copy_async = function (session_id, cwd, from, to, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.copy", [session_id, cwd, from, to], 0, _callback, _error_callback);
    };

    this.make_directory = function (session_id, cwd, directory, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.make_directory",
        [session_id, cwd, directory], 0, _callback, _errorCallback);
};

    this.make_directory_async = function (session_id, cwd, directory, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.make_directory", [session_id, cwd, directory], 0, _callback, _error_callback);
    };

    this.remove_directory = function (session_id, cwd, directory, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.remove_directory",
        [session_id, cwd, directory], 0, _callback, _errorCallback);
};

    this.remove_directory_async = function (session_id, cwd, directory, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.remove_directory", [session_id, cwd, directory], 0, _callback, _error_callback);
    };

    this.change_directory = function (session_id, cwd, directory, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.change_directory",
        [session_id, cwd, directory], 1, _callback, _errorCallback);
};

    this.change_directory_async = function (session_id, cwd, directory, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.change_directory", [session_id, cwd, directory], 1, _callback, _error_callback);
    };

    this.put_file = function (session_id, filename, contents, cwd, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.put_file",
        [session_id, filename, contents, cwd], 0, _callback, _errorCallback);
};

    this.put_file_async = function (session_id, filename, contents, cwd, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.put_file", [session_id, filename, contents, cwd], 0, _callback, _error_callback);
    };

    this.get_file = function (session_id, filename, cwd, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.get_file",
        [session_id, filename, cwd], 1, _callback, _errorCallback);
};

    this.get_file_async = function (session_id, filename, cwd, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.get_file", [session_id, filename, cwd], 1, _callback, _error_callback);
    };

    this.run_pipeline = function (session_id, pipeline, input, max_output_size, cwd, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.run_pipeline",
        [session_id, pipeline, input, max_output_size, cwd], 2, _callback, _errorCallback);
};

    this.run_pipeline_async = function (session_id, pipeline, input, max_output_size, cwd, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.run_pipeline", [session_id, pipeline, input, max_output_size, cwd], 2, _callback, _error_callback);
    };

    this.run_pipeline2 = function (session_id, pipeline, input, max_output_size, cwd, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.run_pipeline2",
        [session_id, pipeline, input, max_output_size, cwd], 3, _callback, _errorCallback);
};

    this.run_pipeline2_async = function (session_id, pipeline, input, max_output_size, cwd, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.run_pipeline2", [session_id, pipeline, input, max_output_size, cwd], 3, _callback, _error_callback);
    };

    this.exit_session = function (session_id, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.exit_session",
        [session_id], 0, _callback, _errorCallback);
};

    this.exit_session_async = function (session_id, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.exit_session", [session_id], 0, _callback, _error_callback);
    };

    this.valid_commands = function (_callback, _errorCallback) {
    return json_call_ajax("InvocationService.valid_commands",
        [], 1, _callback, _errorCallback);
};

    this.valid_commands_async = function (_callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.valid_commands", [], 1, _callback, _error_callback);
    };

    this.installed_modules = function (_callback, _errorCallback) {
    return json_call_ajax("InvocationService.installed_modules",
        [], 1, _callback, _errorCallback);
};

    this.installed_modules_async = function (_callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.installed_modules", [], 1, _callback, _error_callback);
    };

    this.get_tutorial_text = function (step, _callback, _errorCallback) {
    return json_call_ajax("InvocationService.get_tutorial_text",
        [step], 3, _callback, _errorCallback);
};

    this.get_tutorial_text_async = function (step, _callback, _error_callback) {
        deprecationWarning();
        return json_call_ajax("InvocationService.get_tutorial_text", [step], 3, _callback, _error_callback);
    };

    /*
     * JSON call using jQuery method.
     */
    function json_call_ajax(method, params, numRets, callback, errorCallback) {
        var deferred = $.Deferred();

        if (typeof callback === 'function') {
           deferred.done(callback);
        }

        if (typeof errorCallback === 'function') {
           deferred.fail(errorCallback);
        }

        var rpc = {
            params : params,
            method : method,
            version: "1.1",
            id: String(Math.random()).slice(2),
        };

        var beforeSend = null;
        var token = (_auth_cb && typeof _auth_cb === 'function') ? _auth_cb()
            : (_auth.token ? _auth.token : null);
        if (token != null) {
            beforeSend = function (xhr) {
                xhr.setRequestHeader("Authorization", token);
            }
        }

        jQuery.ajax({
            url: _url,
            dataType: "text",
            type: 'POST',
            processData: false,
            data: JSON.stringify(rpc),
            beforeSend: beforeSend,
            success: function (data, status, xhr) {
                var result;
                try {
                    var resp = JSON.parse(data);
                    result = (numRets === 1 ? resp.result[0] : resp.result);
                } catch (err) {
                    deferred.reject({
                        status: 503,
                        error: err,
                        url: _url,
                        resp: data
                    });
                    return;
                }
                deferred.resolve(result);
            },
            error: function (xhr, textStatus, errorThrown) {
                var error;
                if (xhr.responseText) {
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        error = resp.error;
                    } catch (err) { // Not JSON
                        error = "Unknown error - " + xhr.responseText;
                    }
                } else {
                    error = "Unknown Error";
                }
                deferred.reject({
                    status: 500,
                    error: error
                });
            }
        });
        return deferred.promise();
    }
}

<|endoftext|>