<commit_before>/*!
 * ${copyright}
 */
sap.ui.define([
	"sap/ui/base/EventProvider",
	"sap/base/Log",
	"sap/ui/integration/services/Service"
], function (
	EventProvider,
	Log,
	Service
) {
	"use strict";

	/**
	 * Constructor for a new ServiceManager.
	 *
	 * @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
	 * Parses an object and decides which services needs to be instantiated
	 * and handles their lifecycle.
	 * It also provides instances of the services by getService method.
	 *
	 * mServiceFactoryReferences object format:
	 *
	 *	"services": {
	 *		"Navigation": {
	 *			"factoryName": "demoapp.demoappservices.SampleNavigationFactory"
	 *		},
	 *		"SomeOtherService": {
	 *			"factoryName": "demoapp.demoappservices.SomeOtherServiceFactory"
	 * 		}
	 *	}
	 *
	 * @extends sap.ui.base.EventProvider
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @param {Object} mServiceFactoryReferences A map with service descriptions.
	 * @param {Object} oServiceContext A context to be used for newly created service instances.
	 * @private
	 * @alias sap.ui.integration.util.ServiceManager
	 */
	var ServiceManager = EventProvider.extend("sap.ui.integration.util.ServiceManager", {
		metadata: {
			library: "sap.ui.integration"
		},
		constructor: function (mServiceFactoryReferences, oServiceContext) {
			if (!mServiceFactoryReferences) {
				throw new Error("Missing manifest services reference!");
			}
			if (!oServiceContext) {
				throw new Error("Missing context object");
			}
			this._mServiceFactoryReferences = mServiceFactoryReferences;
			this._mServices = {};
			this._oServiceContext = oServiceContext;
			this._initAllServices();
		}
	});

	/**
	 * Initializes all services based on _mServiceFactoryReferences.
	 * @private
	 */
	ServiceManager.prototype._initAllServices = function () {
		for (var sServiceName in this._mServiceFactoryReferences) {
			this._initService(sServiceName);
		}
	};

	/**
	 * Initializes a service which can then be available by getService(sServiceName).
	 *
	 * @private
	 * @param {string} sName The name of the service or a service configuration object.
	 * @returns {Promise} A promise resolved when the service instance is ready.
	 */
	ServiceManager.prototype._initService = function (sName) {
		var oServiceRef = this._mServices[sName] || {};

		oServiceRef.promise = ServiceManager._getService(this._oServiceContext, sName, this._mServiceFactoryReferences)
			.then(function (oServiceInstance) {
				oServiceRef.instance = oServiceInstance;
			}).catch(function (oError) {
				Log.error(oError.message);
			});

		this._mServices[sName] = oServiceRef;

		return oServiceRef.promise;
	};

	/**
	 * Returns an instance of a service based on its name.
	 *
	 * @param {string} sServiceName The name of the service inside sap.ui5/services. If not passed the first registered service will be returned.
	 * @returns {Promise} A promise resolved when the service instance is ready.
	 */
	ServiceManager.prototype.getService = function (sServiceName) {
		var sErrorMessage = "Invalid service";
		return new Promise(function (fnResolve, fnReject) {

			if (!sServiceName
				|| !this._mServices[sServiceName]
				|| !Object.keys(this._mServices[sServiceName])) {
				return Promise.reject(sErrorMessage);
			}

			this._mServices[sServiceName].promise.then(function () {
				if (this._mServices[sServiceName].instance instanceof Service) {
					fnResolve(this._mServices[sServiceName].instance);
				} else {
					fnReject(sErrorMessage);
				}
			}.bind(this)).catch(fnReject);
		}.bind(this));
	};

	ServiceManager.prototype.destroy = function () {
		this._mServices = null;
	};

	// Copied from Component.js
	// Creates an instance of a service based on the manifest settings
	ServiceManager._getService = function (oInstance, sName, mServices) {
		return new Promise(function (fnResolve, fnReject) {
			var oServiceEntry,
				sFactory;
			if (oInstance.bIsDestroyed) {
				return Promise.reject(new Error("Service " + sName + " could not be loaded as the requestor " + oInstance.getMetadata().getName() + " was destroyed."));
			}
			if (!mServices) {
				return Promise.reject(new Error("No Services declared"));
			} else {
				oServiceEntry = mServices[sName];
			}
			if (!oServiceEntry || !oServiceEntry.factoryName) {
				return Promise.reject(new Error("No Service '" + sName + "' declared or factoryName missing"));
			} else {
				sFactory = oServiceEntry.factoryName;
			}
			sap.ui.require(["sap/ui/core/service/ServiceFactoryRegistry"], function (ServiceFactoryRegistry) {
				// lookup the factory in the registry
				var oServiceFactory = ServiceFactoryRegistry.get(sFactory);
				if (oServiceFactory) {
					// create a new Service instance with the current Component as context
					oServiceFactory.createInstance({
						scopeObject: oInstance,
						scopeType: "component",
						settings: oServiceEntry.settings || {}
					}).then(function (oServiceInstance) {
						if (oServiceInstance.getInterface) {
							fnResolve(oServiceInstance.getInterface());
						} else {
							fnResolve(oServiceInstance);
						}
					}).catch(fnReject);
				} else {
					// the service factory could not be found in the registry
					var oError = new Error("ServiceFactory '" + sFactory + "' for Service '" + sName + "' not found in ServiceFactoryRegistry");
					oError._optional = oServiceEntry.optional;
					fnReject(oError);
				}
			});
		});
	};

	return ServiceManager;
});
<commit_msg>[INTERNAL] sap.ui.integration.util.ServiceManager: Service instantiation fixed<commit_after>/*!
 * ${copyright}
 */
sap.ui.define([
	"sap/ui/base/EventProvider",
	"sap/base/Log"
], function (
	EventProvider,
	Log
) {
	"use strict";

	/**
	 * Constructor for a new ServiceManager.
	 *
	 * @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
	 * Parses an object and decides which services needs to be instantiated
	 * and handles their lifecycle.
	 * It also provides instances of the services by getService method.
	 *
	 * mServiceFactoryReferences object format:
	 *
	 *	"services": {
	 *		"Navigation": {
	 *			"factoryName": "demoapp.demoappservices.SampleNavigationFactory"
	 *		},
	 *		"SomeOtherService": {
	 *			"factoryName": "demoapp.demoappservices.SomeOtherServiceFactory"
	 * 		}
	 *	}
	 *
	 * @extends sap.ui.base.EventProvider
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @param {Object} mServiceFactoryReferences A map with service descriptions.
	 * @param {Object} oServiceContext A context to be used for newly created service instances.
	 * @private
	 * @alias sap.ui.integration.util.ServiceManager
	 */
	var ServiceManager = EventProvider.extend("sap.ui.integration.util.ServiceManager", {
		metadata: {
			library: "sap.ui.integration"
		},
		constructor: function (mServiceFactoryReferences, oServiceContext) {
			if (!mServiceFactoryReferences) {
				throw new Error("Missing manifest services reference!");
			}
			if (!oServiceContext) {
				throw new Error("Missing context object");
			}
			this._mServiceFactoryReferences = mServiceFactoryReferences;
			this._mServices = {};
			this._oServiceContext = oServiceContext;
			this._initAllServices();
		}
	});

	/**
	 * Initializes all services based on _mServiceFactoryReferences.
	 * @private
	 */
	ServiceManager.prototype._initAllServices = function () {
		for (var sServiceName in this._mServiceFactoryReferences) {
			this._initService(sServiceName);
		}
	};

	/**
	 * Initializes a service which can then be available by getService(sServiceName).
	 *
	 * @private
	 * @param {string} sName The name of the service or a service configuration object.
	 * @returns {Promise} A promise resolved when the service instance is ready.
	 */
	ServiceManager.prototype._initService = function (sName) {
		var oServiceRef = this._mServices[sName] || {};

		oServiceRef.promise = ServiceManager._getService(this._oServiceContext, sName, this._mServiceFactoryReferences)
			.then(function (oServiceInstance) {
				oServiceRef.instance = oServiceInstance;
			}).catch(function (oError) {
				Log.error(oError.message);
			});

		this._mServices[sName] = oServiceRef;

		return oServiceRef.promise;
	};

	/**
	 * Returns an instance of a service based on its name.
	 *
	 * @param {string} sServiceName The name of the service inside sap.ui5/services. If not passed the first registered service will be returned.
	 * @returns {Promise} A promise resolved when the service instance is ready.
	 */
	ServiceManager.prototype.getService = function (sServiceName) {
		var sErrorMessage = "Invalid service";
		return new Promise(function (fnResolve, fnReject) {

			if (!sServiceName
				|| !this._mServices[sServiceName]
				|| !Object.keys(this._mServices[sServiceName])) {
				return Promise.reject(sErrorMessage);
			}

			this._mServices[sServiceName].promise.then(function () {
				fnResolve(this._mServices[sServiceName].instance);
			}.bind(this)).catch(fnReject);
		}.bind(this));
	};

	ServiceManager.prototype.destroy = function () {
		this._mServices = null;
	};

	// Copied from Component.js
	// Creates an instance of a service based on the manifest settings
	ServiceManager._getService = function (oInstance, sName, mServices) {
		return new Promise(function (fnResolve, fnReject) {
			var oServiceEntry,
				sFactory;
			if (oInstance.bIsDestroyed) {
				return Promise.reject(new Error("Service " + sName + " could not be loaded as the requestor " + oInstance.getMetadata().getName() + " was destroyed."));
			}
			if (!mServices) {
				return Promise.reject(new Error("No Services declared"));
			} else {
				oServiceEntry = mServices[sName];
			}
			if (!oServiceEntry || !oServiceEntry.factoryName) {
				return Promise.reject(new Error("No Service '" + sName + "' declared or factoryName missing"));
			} else {
				sFactory = oServiceEntry.factoryName;
			}
			sap.ui.require(["sap/ui/core/service/ServiceFactoryRegistry"], function (ServiceFactoryRegistry) {
				// lookup the factory in the registry
				var oServiceFactory = ServiceFactoryRegistry.get(sFactory);
				if (oServiceFactory) {
					// create a new Service instance with the current Component as context
					oServiceFactory.createInstance({
						scopeObject: oInstance,
						scopeType: "component",
						settings: oServiceEntry.settings || {}
					}).then(function (oServiceInstance) {
						if (oServiceInstance.getInterface) {
							fnResolve(oServiceInstance.getInterface());
						} else {
							fnResolve(oServiceInstance);
						}
					}).catch(fnReject);
				} else {
					// the service factory could not be found in the registry
					var oError = new Error("ServiceFactory '" + sFactory + "' for Service '" + sName + "' not found in ServiceFactoryRegistry");
					oError._optional = oServiceEntry.optional;
					fnReject(oError);
				}
			});
		});
	};

	return ServiceManager;
});
<|endoftext|>


<commit_before>goog.provide('recoil.ui.widgets.NumberWidget');

goog.require('goog.events');
goog.require('goog.events.InputHandler');
goog.require('goog.events.PasteHandler');
goog.require('goog.ui.Component');
goog.require('recoil.frp.Util');
goog.require('recoil.ui.BoolWithExplaination');
goog.require('recoil.ui.widgets.LabelWidget');

/**
 *
 * @param {recoil.ui.WidgetScope} scope
 * @constructor
 * @extends recoil.ui.LabeledWidget
 */
recoil.ui.widgets.NumberWidget = function(scope) {
    this.scope_ = scope;

    this.labelWidget_ = new recoil.ui.widgets.LabelWidget(scope);
    this.number_ = new recoil.ui.widgets.NumberWidget.NumberInput();

    goog.dom.getDomHelper();

    this.helper_ = new recoil.ui.ComponentWidgetHelper(scope, this.input_, this, this.updateState_);

//    this.changeHelper_ = new recoil.ui.EventHelper(scope, this.number_, goog.events.InputHandler.EventType.INPUT);
};

recoil.ui.widgets.NumberWidget.DomHelper_ = function() {
    goog.dom.getDomHelper();
};

/**
 * @constructor
 * @extends {goog.ui.LabelInput}}
 */
recoil.ui.widgets.NumberWidget.NumberInput = function () {
    goog.ui.LabelInput.call(this);
    this.min_ = undefined;
    this.max_ = undefined;
    this.step_ = undefined;

    // we need this because some browsers don't filter keys
    this.keyFilter_ = function (e) {

        // Allow: backspace, delete, tab, escape, enter and .
        if (goog.array.contains([46, 8, 9, 27, 13, 110, 190],e.keyCode) ||
            // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
            // Allow: Ctrl+C
            (e.keyCode == 67 && e.ctrlKey === true) ||
            // Allow: Ctrl+C
            (e.keyCode == 86 && e.ctrlKey === true) ||
            // Allow: Ctrl+X
               (e.keyCode == 88 && e.ctrlKey === true) ||
            // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
            console.log("keypress prevented", e.keyCode);
        }
    };

};

goog.inherits(recoil.ui.widgets.NumberWidget.NumberInput, goog.ui.LabelInput);

/**
 * Creates the DOM nodes needed for the label input.
 * @override
 */
recoil.ui.widgets.NumberWidget.NumberInput.prototype.createDom = function() {
    var element =  this.getDomHelper().createDom(
        goog.dom.TagName.INPUT,
        {'type': goog.dom.InputType.NUMBER, step: 0.1});

    goog.events.listen(element
                       ,goog.events.EventType.KEYDOWN, this.keyFilter_);
    goog.events.listen(new goog.events.InputHandler(element)
                       ,goog.events.InputHandler.EventType.INPUT,
                       function (e) {
//                           var txt = e.clipboardData.getData('text/plain');
                           console.log("paste",e);
                           //filter stuff here
                       });

    this.setElementInternal(element);
};

/**
 *
 * @return {goog.ui.Component}
 */
recoil.ui.widgets.NumberWidget.prototype.getComponent = function() {
    return this.number_;
};

/**
 *
 * @return {recoil.ui.widgets.Widget}
 */
recoil.ui.widgets.NumberWidget.prototype.getLabel = function() {
    return this.labelWidget_;
};

/**
 *
 * @param {recoil.frp.Behaviour<T>} name
 * @param {recoil.frp.Behaviour<T>} value
 * @param {recoil.frp.Behaviour<BoolWithExplaination>} enabled
 */
recoil.ui.widgets.NumberWidget.prototype.attach = function(name, value, enabled) {
/*
    var frp = this.helper_.getFrp();
    var util = new recoil.frp.Util(frp);

    this.nameB_ = util.toBehaviour(name);
    this.valueB_ = util.toBehaviour(value);
    this.enabledB_ = util.toBehaviour(enabled);

    var readyB = util.isAllGood(this.nameB_, this.valueB_, this.enabledB_);

    this.labelWidget_.attach(this.nameB_, this.valueB_, recoil.ui.BoolWithExplaination.and(frp, this.enabledB_, readyB));
    var reallyEnabledB = recoil.ui.BoolWithExplaination.and(frp, this.enabledB_, readyB);
    this.helper_.attach(this.valueB_, reallyEnabledB, util.toBehaviour(this.labelWidget_));

    var me = this;
    this.changeHelper_.listen(this.scope_.getFrp().createCallback(function(v) {
        var inputEl = v.target;
        console.log("INPUT SET");
        me.valueB_.set(inputEl.value);
    }, this.valueB_));*/
};

/**
 *
 * @param data
 */
recoil.ui.widgets.NumberWidget.prototype.attachStruct = function(data) {

    var nameB = recoil.struct.get('name', data);
    var enabledB = recoil.struct.get('enabled', data);
    var valueB = recoil.struct.get('value', data);

    this.attach(nameB.get(), valueB.get(), enabledB.get());
};

/**
 *
 * @param {recoil.ui.WidgetHelper} helper
 * @private
 */
recoil.ui.widgets.NumberWidget.prototype.updateState_ = function(helper) {

    if (helper.isGood()) {
        this.input_.setValue(this.valueB_.get());
    }
};

<commit_msg>number widget<commit_after>goog.provide('recoil.ui.widgets.NumberWidget');

goog.require('goog.events');
goog.require('goog.events.InputHandler');
goog.require('goog.events.PasteHandler');
goog.require('goog.ui.Component');
goog.require('recoil.frp.Util');
goog.require('recoil.ui.BoolWithExplaination');
goog.require('recoil.ui.widgets.LabelWidget');

/**
 *
 * @param {recoil.ui.WidgetScope} scope
 * @constructor
 * @extends recoil.ui.LabeledWidget
 */
recoil.ui.widgets.NumberWidget = function(scope) {
    this.scope_ = scope;

    this.labelWidget_ = new recoil.ui.widgets.LabelWidget(scope);
    this.number_ = new recoil.ui.widgets.NumberWidget.NumberInput();

    goog.dom.getDomHelper();

    this.helper_ = new recoil.ui.ComponentWidgetHelper(scope, this.input_, this, this.updateState_);

//    this.changeHelper_ = new recoil.ui.EventHelper(scope, this.number_, goog.events.InputHandler.EventType.INPUT);
};

recoil.ui.widgets.NumberWidget.DomHelper_ = function() {
    goog.dom.getDomHelper();
};

/**
 * @constructor
 * @extends {goog.ui.LabelInput}}
 */
recoil.ui.widgets.NumberWidget.NumberInput = function () {
    goog.ui.LabelInput.call(this);
    this.min_ = undefined;
    this.max_ = undefined;
    this.step_ = undefined;

    // we need this because some browsers don't filter keys
    this.keyFilter_ = function (e) {

        // Allow: backspace, delete, tab, escape, enter and .
        if (goog.array.contains([46, 8, 9, 27, 13, 110, 190],e.keyCode) ||
            // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
            // Allow: Ctrl+C
            (e.keyCode == 67 && e.ctrlKey === true) ||
            // Allow: Ctrl+C
            (e.keyCode == 86 && e.ctrlKey === true) ||
            // Allow: Ctrl+X
               (e.keyCode == 88 && e.ctrlKey === true) ||
            // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    };

};

goog.inherits(recoil.ui.widgets.NumberWidget.NumberInput, goog.ui.LabelInput);

/**
 * Creates the DOM nodes needed for the label input.
 * @override
 */
recoil.ui.widgets.NumberWidget.NumberInput.prototype.createDom = function() {
    var element =  this.getDomHelper().createDom(
        goog.dom.TagName.INPUT,
        {'type': goog.dom.InputType.NUMBER, step: 0.1});

    goog.events.listen(element
                       ,goog.events.EventType.KEYDOWN, this.keyFilter_);
    goog.events.listen(new goog.events.PasteHandler(element)
                       ,goog.events.PasteHandler.EventType.PASTE,
                       function (e) {
                           var inputEl = e.target;
                           var origText = inputEl;

                           var clip = e.getBrowserEvent().clipboardData;
                           var txt = clip.getData('text/plain');

                           txt = txt.replace(/[^0-9.+]/g, "F");
                           console.log("paste",e, txt);
                           clip.clearData('text/plain');
                           clip.setData('text/plain', txt);
//            e.preventDefault();
//                           e.stopPropagation();
                           //filter stuff here
                       });

    this.setElementInternal(element);
};

/**
 *
 * @return {goog.ui.Component}
 */
recoil.ui.widgets.NumberWidget.prototype.getComponent = function() {
    return this.number_;
};

/**
 *
 * @return {recoil.ui.widgets.Widget}
 */
recoil.ui.widgets.NumberWidget.prototype.getLabel = function() {
    return this.labelWidget_;
};

/**
 *
 * @param {recoil.frp.Behaviour<T>} name
 * @param {recoil.frp.Behaviour<T>} value
 * @param {recoil.frp.Behaviour<BoolWithExplaination>} enabled
 */
recoil.ui.widgets.NumberWidget.prototype.attach = function(name, value, enabled) {
/*
    var frp = this.helper_.getFrp();
    var util = new recoil.frp.Util(frp);

    this.nameB_ = util.toBehaviour(name);
    this.valueB_ = util.toBehaviour(value);
    this.enabledB_ = util.toBehaviour(enabled);

    var readyB = util.isAllGood(this.nameB_, this.valueB_, this.enabledB_);

    this.labelWidget_.attach(this.nameB_, this.valueB_, recoil.ui.BoolWithExplaination.and(frp, this.enabledB_, readyB));
    var reallyEnabledB = recoil.ui.BoolWithExplaination.and(frp, this.enabledB_, readyB);
    this.helper_.attach(this.valueB_, reallyEnabledB, util.toBehaviour(this.labelWidget_));

    var me = this;
    this.changeHelper_.listen(this.scope_.getFrp().createCallback(function(v) {
        var inputEl = v.target;
        console.log("INPUT SET");
        me.valueB_.set(inputEl.value);
    }, this.valueB_));*/
};

/**
 *
 * @param data
 */
recoil.ui.widgets.NumberWidget.prototype.attachStruct = function(data) {

    var nameB = recoil.struct.get('name', data);
    var enabledB = recoil.struct.get('enabled', data);
    var valueB = recoil.struct.get('value', data);

    this.attach(nameB.get(), valueB.get(), enabledB.get());
};

/**
 *
 * @param {recoil.ui.WidgetHelper} helper
 * @private
 */
recoil.ui.widgets.NumberWidget.prototype.updateState_ = function(helper) {

    if (helper.isGood()) {
        this.input_.setValue(this.valueB_.get());
    }
};

<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular.module('app')
        .directive('textWidget', ['$parse', '$compile', 'Lang', 'Connector', function($parse, $compile, Lang, Connector) {
            return {
                link: function(scope, element, attrs) {
                    element.removeAttr('text-widget');
                    element[0].innerHTML =  "

{{item.label}}
<svg class='text-widget'>"+
                                                "<text style='fill: #000'>{{item.value}}</text>"+
                                            "</svg>
";
                    $compile(element)(scope);
                }
            };
        }])
    .directive('resizeAfterRender', function ($timeout) {
            return {
                restrict: 'A',
                link: function (scope, element, attr) {
                    if (scope.$last)
                    if (scope.$last === true) {
                        $timeout(function (e) {
                            var childs = element[0].parentNode.children;
                            for (var i = 0; i < childs.length; i++) {
                                childs[i].style.display = "";
                                var svg = childs[i].children[1];
                                var text = svg.firstChild;
                                var bbox = text.getBBox();

                               /* var svgns = "http://www.w3.org/2000/svg";
                                var rect = document.createElementNS(svgns, 'rect');
                                rect.setAttributeNS(null, 'x', bbox.x);
                                rect.setAttributeNS(null, 'y', bbox.y);
                                rect.setAttributeNS(null, 'width', bbox.width);
                                rect.setAttributeNS(null, 'height', bbox.height);
                                svg.appendChild(rect);
*/
                                svg.setAttribute('viewBox', [bbox.x, bbox.y, bbox.width, bbox.height].join(' '));

                            }
                            scope.model.rendered = true;
                        }, 0, false, element);
                    }
                }
            }
        });
})();<commit_msg>fixes<commit_after>(function() {
    'use strict';

    angular.module('app')
        .directive('textWidget', ['$parse', '$compile', 'Lang', 'Connector', function($parse, $compile, Lang, Connector) {
            return {
                link: function(scope, element, attrs) {
                    element.removeAttr('text-widget');
                    element[0].innerHTML =  "

{{item.label}}
<svg class='text-widget'>"+
                                                "<text style='fill: #000'>{{item.value}}</text>"+
                                            "</svg>
";
                    $compile(element)(scope);
                }
            };
        }])
    .directive('resizeAfterRender', function ($timeout) {
            return {
                restrict: 'A',
                link: function (scope, element, attr) {
                    if (scope.$last)
                    if (scope.$last === true) {
                        $timeout(function (e) {
                            var childs = element[0].parentNode.children;
                            for (var i = 0; i < childs.length; i++) {
                                childs[i].style.display = "";
                                var svg = childs[i].children[1];
                                var text = svg.firstChild;
                                var bbox = text.getBBox();

                               /* var svgns = "http://www.w3.org/2000/svg";
                                var rect = document.createElementNS(svgns, 'rect');
                                rect.setAttributeNS(null, 'x', bbox.x);
                                rect.setAttributeNS(null, 'y', bbox.y);
                                rect.setAttributeNS(null, 'width', bbox.width);
                                rect.setAttributeNS(null, 'height', bbox.height);
                                svg.appendChild(rect);
*/
                                svg.setAttribute('viewBox', [bbox.x, bbox.y, bbox.width, bbox.height].join(' '));

                            }
                            scope.model.rendered = true;
                        }, 0, false, element);
                    }
                }
            };
        });
})();<|endoftext|>


<commit_before>const Web3PromiEvent = require("web3-core-promievent");
const BlockchainUtils = require("truffle-blockchain-utils");
const Web3 = require("web3");
const utils = require("../utils");
const execute = require("../execute");
const bootstrap = require("./bootstrap");

module.exports = Contract => {
  return {
    setProvider: function(provider) {
      if (!provider) {
        throw new Error(
          "Invalid provider passed to setProvider(); provider is " + provider
        );
      }

      this.web3.setProvider(provider);
      this.currentProvider = provider;
    },

    new: function() {
      var constructor = this;
      var promiEvent = new Web3PromiEvent();

      if (!constructor.currentProvider) {
        var err =
          constructor.contractName +
          " error: Please call setProvider() first before calling new().";
        throw new Error(err);
      }

      if (!constructor.bytecode || constructor.bytecode === "0x") {
        var err =
          `${
            constructor.contractName
          } error: contract binary not set. Can't deploy new instance.\n` +
          `This contract may be abstract, not implement an abstract parent's methods completely\n` +
          `or not invoke an inherited contract's constructor correctly\n`;

        throw new Error(err);
      }

      var args = Array.prototype.slice.call(arguments);

      // Promievent and flag that allows instance to resolve (rather than just receipt)
      var context = {
        contract: constructor,
        promiEvent: promiEvent,
        onlyEmitReceipt: true
      };

      constructor
        .detectNetwork()
        .then(network => {
          utils.checkLibraries.apply(constructor);
          return execute.deploy.call(
            constructor,
            args,
            context,
            network.blockLimit
          );
        })
        .catch(promiEvent.reject);

      return promiEvent.eventEmitter;
    },

    at: function(address) {
      var constructor = this;

      return new Promise(function(accept, reject) {
        if (
          address == null ||
          typeof address != "string" ||
          address.length != 42
        ) {
          var err =
            "Invalid address passed to " +
            constructor.contractName +
            ".at(): " +
            address;
          reject(new Error(err));
        }

        return constructor.detectNetwork().then(function() {
          var instance = new constructor(address);

          return constructor.web3.eth.getCode(address).then(function(code) {
            if (!code || code.replace("0x", "").replace(/0/g, "") === "") {
              var err =
                "Cannot create instance of " +
                constructor.contractName +
                "; no code at address " +
                address;
              reject(new Error(err));
            }

            accept(instance);
          });
        });
      });
    },

    deployed: function() {
      var constructor = this;
      return constructor.detectNetwork().then(function() {
        // We don't have a network config for the one we found
        if (constructor._json.networks[constructor.network_id] == null) {
          var error =
            constructor.contractName +
            " has not been deployed to detected network" +
            " (network/artifact mismatch)";
          throw new Error(error);
        }

        // If we found the network but it's not deployed
        if (!constructor.isDeployed()) {
          var error =
            constructor.contractName +
            " has not been deployed to detected network (" +
            constructor.network_id +
            ")";

          throw new Error(error);
        }

        return new constructor(constructor.address);
      });
    },

    defaults: function(class_defaults) {
      if (this.class_defaults == null) {
        this.class_defaults = {};
      }

      if (class_defaults == null) {
        class_defaults = {};
      }

      var constructor = this;
      Object.keys(class_defaults).forEach(function(key) {
        var value = class_defaults[key];
        constructor.class_defaults[key] = value;
      });

      return this.class_defaults;
    },

    hasNetwork: function(network_id) {
      return this._json.networks[network_id + ""] != null;
    },

    isDeployed: function() {
      if (this.network_id == null) {
        return false;
      }

      if (this._json.networks[this.network_id] == null) {
        return false;
      }

      return !!this.network.address;
    },

    detectNetwork: function() {
      var constructor = this;

      return new Promise(function(accept, reject) {
        // Try to get the current blockLimit
        constructor.web3.eth
          .getBlock("latest")
          .then(function(block) {
            // Try to detect the network we have artifacts for.
            if (constructor.network_id) {
              // We have a network id and a configuration, let's go with it.
              if (constructor.networks[constructor.network_id] != null) {
                return accept({
                  id: constructor.network_id,
                  blockLimit: block.gasLimit
                });
              }
            }

            constructor.web3.eth.net
              .getId()
              .then(function(network_id) {
                // If we found the network via a number, let's use that.
                if (constructor.hasNetwork(network_id)) {
                  constructor.setNetwork(network_id);
                  return accept({
                    id: constructor.network_id,
                    blockLimit: block.gasLimit
                  });
                }

                // Otherwise, go through all the networks that are listed as
                // blockchain uris and see if they match.
                var uris = Object.keys(constructor._json.networks).filter(
                  function(network) {
                    return network.indexOf("blockchain://") == 0;
                  }
                );

                var matches = uris.map(function(uri) {
                  return BlockchainUtils.matches.bind(
                    BlockchainUtils,
                    uri,
                    constructor.web3.currentProvider
                  );
                });

                utils.parallel(matches, function(err, results) {
                  if (err) return reject(err);

                  for (var i = 0; i < results.length; i++) {
                    if (results[i]) {
                      constructor.setNetwork(uris[i]);
                      return accept({
                        id: constructor.network_id,
                        blockLimit: block.gasLimit
                      });
                    }
                  }

                  // We found nothing. Set the network id to whatever the provider states.
                  constructor.setNetwork(network_id);
                  return accept({
                    id: constructor.network_id,
                    blockLimit: block.gasLimit
                  });
                });
              })
              .catch(reject);
          })
          .catch(reject);
      });
    },

    setNetwork: function(network_id) {
      if (!network_id) return;
      this.network_id = network_id + "";
    },

    setWallet: function(wallet) {
      this.web3.eth.accounts.wallet = wallet;
    },

    // Overrides the deployed address to null.
    // You must call this explicitly so you don't inadvertently do this otherwise.
    resetAddress: function() {
      delete this.network.address;
    },

    link: function(name, address) {
      var constructor = this;

      // Case: Contract.link(instance)
      if (typeof name == "function") {
        var contract = name;

        if (contract.isDeployed() == false) {
          throw new Error("Cannot link contract without an address.");
        }

        this.link(contract.contractName, contract.address);

        // Merge events so this contract knows about library's events
        Object.keys(contract.events).forEach(function(topic) {
          constructor.network.events[topic] = contract.events[topic];
        });

        return;
      }

      // Case: Contract.link({<libraryName>: <address>, ... })
      if (typeof name == "object") {
        var obj = name;
        Object.keys(obj).forEach(function(name) {
          var a = obj[name];
          constructor.link(name, a);
        });
        return;
      }

      // Case: Contract.link(<libraryName>, <address>)
      if (this._json.networks[this.network_id] == null) {
        this._json.networks[this.network_id] = {
          events: {},
          links: {}
        };
      }

      this.network.links[name] = address;
    },

    // Note, this function can be called with two input types:
    // 1. Object with a bunch of data; this data will be merged with the json data of contract being cloned.
    // 2. network id; this will clone the contract and set a specific network id upon cloning.
    clone: function(json) {
      var constructor = this;

      json = json || {};

      var temp = function TruffleContract() {
        this.constructor = temp;
        return Contract.apply(this, arguments);
      };

      temp.prototype = Object.create(constructor.prototype);

      var network_id;

      // If we have a network id passed
      if (typeof json != "object") {
        network_id = json;
        json = constructor._json;
      }

      json = utils.merge({}, constructor._json || {}, json);

      temp._constructorMethods = this._constructorMethods;
      temp._properties = this._properties;

      temp._property_values = {};
      temp._json = json;

      bootstrap(temp);

      temp.web3 = new Web3();
      temp.class_defaults = temp.prototype.defaults || {};

      if (network_id) {
        temp.setNetwork(network_id);
      }

      // Copy over custom key/values to the contract class
      Object.keys(json).forEach(function(key) {
        if (key.indexOf("x-") != 0) return;
        temp[key] = json[key];
      });

      return temp;
    },

    addProp: function(key, fn) {
      var constructor = this;

      var getter = function() {
        if (fn.get != null) {
          return fn.get.call(constructor);
        }

        return constructor._property_values[key] || fn.call(constructor);
      };

      var setter = function(val) {
        if (fn.set != null) {
          fn.set.call(constructor, val);
          return;
        }

        // If there's not a setter, then the property is immutable.
        throw new Error(key + " property is immutable");
      };

      var definition = {};
      definition.enumerable = false;
      definition.configurable = false;
      definition.get = getter;
      definition.set = setter;

      Object.defineProperty(this, key, definition);
    },

    toJSON: function() {
      return this._json;
    },

    decodeLogs: utils.decodeLogs
  };
};
<commit_msg>Convert Non-strict to strict equality checking Convert non-strict equality checking, using `==`, to the strict version, using `===`.<commit_after>const Web3PromiEvent = require("web3-core-promievent");
const BlockchainUtils = require("truffle-blockchain-utils");
const Web3 = require("web3");
const utils = require("../utils");
const execute = require("../execute");
const bootstrap = require("./bootstrap");

module.exports = Contract => {
  return {
    setProvider: function(provider) {
      if (!provider) {
        throw new Error(
          "Invalid provider passed to setProvider(); provider is " + provider
        );
      }

      this.web3.setProvider(provider);
      this.currentProvider = provider;
    },

    new: function() {
      var constructor = this;
      var promiEvent = new Web3PromiEvent();

      if (!constructor.currentProvider) {
        var err =
          constructor.contractName +
          " error: Please call setProvider() first before calling new().";
        throw new Error(err);
      }

      if (!constructor.bytecode || constructor.bytecode === "0x") {
        var err =
          `${
            constructor.contractName
          } error: contract binary not set. Can't deploy new instance.\n` +
          `This contract may be abstract, not implement an abstract parent's methods completely\n` +
          `or not invoke an inherited contract's constructor correctly\n`;

        throw new Error(err);
      }

      var args = Array.prototype.slice.call(arguments);

      // Promievent and flag that allows instance to resolve (rather than just receipt)
      var context = {
        contract: constructor,
        promiEvent: promiEvent,
        onlyEmitReceipt: true
      };

      constructor
        .detectNetwork()
        .then(network => {
          utils.checkLibraries.apply(constructor);
          return execute.deploy.call(
            constructor,
            args,
            context,
            network.blockLimit
          );
        })
        .catch(promiEvent.reject);

      return promiEvent.eventEmitter;
    },

    at: function(address) {
      var constructor = this;

      return new Promise(function(accept, reject) {
        if (
          address == null ||
          typeof address !== "string" ||
          address.length !== 42
        ) {
          var err =
            "Invalid address passed to " +
            constructor.contractName +
            ".at(): " +
            address;
          reject(new Error(err));
        }

        return constructor.detectNetwork().then(function() {
          var instance = new constructor(address);

          return constructor.web3.eth.getCode(address).then(function(code) {
            if (!code || code.replace("0x", "").replace(/0/g, "") === "") {
              var err =
                "Cannot create instance of " +
                constructor.contractName +
                "; no code at address " +
                address;
              reject(new Error(err));
            }

            accept(instance);
          });
        });
      });
    },

    deployed: function() {
      var constructor = this;
      return constructor.detectNetwork().then(function() {
        // We don't have a network config for the one we found
        if (constructor._json.networks[constructor.network_id] == null) {
          var error =
            constructor.contractName +
            " has not been deployed to detected network" +
            " (network/artifact mismatch)";
          throw new Error(error);
        }

        // If we found the network but it's not deployed
        if (!constructor.isDeployed()) {
          var error =
            constructor.contractName +
            " has not been deployed to detected network (" +
            constructor.network_id +
            ")";

          throw new Error(error);
        }

        return new constructor(constructor.address);
      });
    },

    defaults: function(class_defaults) {
      if (this.class_defaults == null) {
        this.class_defaults = {};
      }

      if (class_defaults == null) {
        class_defaults = {};
      }

      var constructor = this;
      Object.keys(class_defaults).forEach(function(key) {
        var value = class_defaults[key];
        constructor.class_defaults[key] = value;
      });

      return this.class_defaults;
    },

    hasNetwork: function(network_id) {
      return this._json.networks[network_id + ""] != null;
    },

    isDeployed: function() {
      if (this.network_id == null) {
        return false;
      }

      if (this._json.networks[this.network_id] == null) {
        return false;
      }

      return !!this.network.address;
    },

    detectNetwork: function() {
      var constructor = this;

      return new Promise(function(accept, reject) {
        // Try to get the current blockLimit
        constructor.web3.eth
          .getBlock("latest")
          .then(function(block) {
            // Try to detect the network we have artifacts for.
            if (constructor.network_id) {
              // We have a network id and a configuration, let's go with it.
              if (constructor.networks[constructor.network_id] != null) {
                return accept({
                  id: constructor.network_id,
                  blockLimit: block.gasLimit
                });
              }
            }

            constructor.web3.eth.net
              .getId()
              .then(function(network_id) {
                // If we found the network via a number, let's use that.
                if (constructor.hasNetwork(network_id)) {
                  constructor.setNetwork(network_id);
                  return accept({
                    id: constructor.network_id,
                    blockLimit: block.gasLimit
                  });
                }

                // Otherwise, go through all the networks that are listed as
                // blockchain uris and see if they match.
                var uris = Object.keys(constructor._json.networks).filter(
                  function(network) {
                    return network.indexOf("blockchain://") === 0;
                  }
                );

                var matches = uris.map(function(uri) {
                  return BlockchainUtils.matches.bind(
                    BlockchainUtils,
                    uri,
                    constructor.web3.currentProvider
                  );
                });

                utils.parallel(matches, function(err, results) {
                  if (err) return reject(err);

                  for (var i = 0; i < results.length; i++) {
                    if (results[i]) {
                      constructor.setNetwork(uris[i]);
                      return accept({
                        id: constructor.network_id,
                        blockLimit: block.gasLimit
                      });
                    }
                  }

                  // We found nothing. Set the network id to whatever the provider states.
                  constructor.setNetwork(network_id);
                  return accept({
                    id: constructor.network_id,
                    blockLimit: block.gasLimit
                  });
                });
              })
              .catch(reject);
          })
          .catch(reject);
      });
    },

    setNetwork: function(network_id) {
      if (!network_id) return;
      this.network_id = network_id + "";
    },

    setWallet: function(wallet) {
      this.web3.eth.accounts.wallet = wallet;
    },

    // Overrides the deployed address to null.
    // You must call this explicitly so you don't inadvertently do this otherwise.
    resetAddress: function() {
      delete this.network.address;
    },

    link: function(name, address) {
      var constructor = this;

      // Case: Contract.link(instance)
      if (typeof name === "function") {
        var contract = name;

        if (contract.isDeployed() === false) {
          throw new Error("Cannot link contract without an address.");
        }

        this.link(contract.contractName, contract.address);

        // Merge events so this contract knows about library's events
        Object.keys(contract.events).forEach(function(topic) {
          constructor.network.events[topic] = contract.events[topic];
        });

        return;
      }

      // Case: Contract.link({<libraryName>: <address>, ... })
      if (typeof name === "object") {
        var obj = name;
        Object.keys(obj).forEach(function(name) {
          var a = obj[name];
          constructor.link(name, a);
        });
        return;
      }

      // Case: Contract.link(<libraryName>, <address>)
      if (this._json.networks[this.network_id] == null) {
        this._json.networks[this.network_id] = {
          events: {},
          links: {}
        };
      }

      this.network.links[name] = address;
    },

    // Note, this function can be called with two input types:
    // 1. Object with a bunch of data; this data will be merged with the json data of contract being cloned.
    // 2. network id; this will clone the contract and set a specific network id upon cloning.
    clone: function(json) {
      var constructor = this;

      json = json || {};

      var temp = function TruffleContract() {
        this.constructor = temp;
        return Contract.apply(this, arguments);
      };

      temp.prototype = Object.create(constructor.prototype);

      var network_id;

      // If we have a network id passed
      if (typeof json !== "object") {
        network_id = json;
        json = constructor._json;
      }

      json = utils.merge({}, constructor._json || {}, json);

      temp._constructorMethods = this._constructorMethods;
      temp._properties = this._properties;

      temp._property_values = {};
      temp._json = json;

      bootstrap(temp);

      temp.web3 = new Web3();
      temp.class_defaults = temp.prototype.defaults || {};

      if (network_id) {
        temp.setNetwork(network_id);
      }

      // Copy over custom key/values to the contract class
      Object.keys(json).forEach(function(key) {
        if (key.indexOf("x-") !== 0) return;
        temp[key] = json[key];
      });

      return temp;
    },

    addProp: function(key, fn) {
      var constructor = this;

      var getter = function() {
        if (fn.get != null) {
          return fn.get.call(constructor);
        }

        return constructor._property_values[key] || fn.call(constructor);
      };

      var setter = function(val) {
        if (fn.set != null) {
          fn.set.call(constructor, val);
          return;
        }

        // If there's not a setter, then the property is immutable.
        throw new Error(key + " property is immutable");
      };

      var definition = {};
      definition.enumerable = false;
      definition.configurable = false;
      definition.get = getter;
      definition.set = setter;

      Object.defineProperty(this, key, definition);
    },

    toJSON: function() {
      return this._json;
    },

    decodeLogs: utils.decodeLogs
  };
};
<|endoftext|>


<commit_before>export function append(target, node) {
	target.appendChild(node);
}

export function insert(target, node, anchor) {
	target.insertBefore(node, anchor);
}

export function detachNode(node) {
	node.parentNode.removeChild(node);
}

export function detachBetween(before, after) {
	while (before.nextSibling && before.nextSibling !== after) {
		before.parentNode.removeChild(before.nextSibling);
	}
}

export function detachBefore(after) {
	while (after.previousSibling) {
		after.parentNode.removeChild(after.previousSibling);
	}
}

export function detachAfter(before) {
	while (before.nextSibling) {
		before.parentNode.removeChild(before.nextSibling);
	}
}

export function reinsertBetween(before, after, target) {
	while (before.nextSibling && before.nextSibling !== after) {
		target.appendChild(before.parentNode.removeChild(before.nextSibling));
	}
}

export function reinsertChildren(parent, target) {
	while (parent.firstChild) target.appendChild(parent.firstChild);
}

export function reinsertAfter(before, target) {
	while (before.nextSibling) target.appendChild(before.nextSibling);
}

export function reinsertBefore(after, target) {
	var parent = after.parentNode;
	while (parent.firstChild !== after) target.appendChild(parent.firstChild);
}

export function destroyEach(iterations, detach) {
	for (var i = 0; i < iterations.length; i += 1) {
		if (iterations[i]) iterations[i].d(detach);
	}
}

export function createFragment() {
	return document.createDocumentFragment();
}

export function createElement(name) {
	return document.createElement(name);
}

export function createSvgElement(name) {
	return document.createElementNS('http://www.w3.org/2000/svg', name);
}

export function createText(data) {
	return document.createTextNode(data);
}

export function createComment() {
	return document.createComment('');
}

export function addListener(node, event, handler) {
	node.addEventListener(event, handler, false);
}

export function removeListener(node, event, handler) {
	node.removeEventListener(event, handler, false);
}

export function setAttribute(node, attribute, value) {
	node.setAttribute(attribute, value);
}

export function setAttributes(node, attributes) {
	for (var key in attributes) {
		if (key === 'style') {
			node.style.cssText = attributes[key];
		} else if (key in node) {
			node[key] = attributes[key];
		} else {
			if (attributes[key] === undefined) removeAttribute(node, key);
			else setAttribute(node, key, attributes[key]);
		}
	}
}

export function setCustomElementData(node, prop, value) {
	if (prop in node) {
		node[prop] = value;
	} else if (value) {
		setAttribute(node, prop, value);
	} else {
		removeAttribute(node, prop);
	}
}

export function removeAttribute(node, attribute) {
	node.removeAttribute(attribute);
}

export function setXlinkAttribute(node, attribute, value) {
	node.setAttributeNS('http://www.w3.org/1999/xlink', attribute, value);
}

export function getBindingGroupValue(group) {
	var value = [];
	for (var i = 0; i < group.length; i += 1) {
		if (group[i].checked) value.push(group[i].__value);
	}
	return value;
}

export function toNumber(value) {
	return value === '' ? undefined : +value;
}

export function timeRangesToArray(ranges) {
	var array = [];
	for (var i = 0; i < ranges.length; i += 1) {
		array.push({ start: ranges.start(i), end: ranges.end(i) });
	}
	return array;
}

export function children (element) {
	return Array.from(element.childNodes);
}

export function claimElement (nodes, name, attributes, svg) {
	for (var i = 0; i < nodes.length; i += 1) {
		var node = nodes[i];
		if (node.nodeName === name) {
			for (var j = 0; j < node.attributes.length; j += 1) {
				var attribute = node.attributes[j];
				if (!attributes[attribute.name]) node.removeAttribute(attribute.name);
			}
			return nodes.splice(i, 1)[0]; // TODO strip unwanted attributes
		}
	}

	return svg ? createSvgElement(name) : createElement(name);
}

export function claimText (nodes, data) {
	for (var i = 0; i < nodes.length; i += 1) {
		var node = nodes[i];
		if (node.nodeType === 3) {
			node.data = data;
			return nodes.splice(i, 1)[0];
		}
	}

	return createText(data);
}

export function setData(text, data) {
	text.data = '' + data;
}

export function setInputType(input, type) {
	try {
		input.type = type;
	} catch (e) {}
}

export function setStyle(node, key, value) {
	node.style.setProperty(key, value);
}

export function selectOption(select, value) {
	for (var i = 0; i < select.options.length; i += 1) {
		var option = select.options[i];

		if (option.__value === value) {
			option.selected = true;
			return;
		}
	}
}

export function selectOptions(select, value) {
	for (var i = 0; i < select.options.length; i += 1) {
		var option = select.options[i];
		option.selected = ~value.indexOf(option.__value);
	}
}

export function selectValue(select) {
	var selectedOption = select.querySelector(':checked') || select.options[0];
	return selectedOption && selectedOption.__value;
}

export function selectMultipleValue(select) {
	return [].map.call(select.querySelectorAll(':checked'), function(option) {
		return option.__value;
	});
}

export function addResizeListener(element, fn) {
	if (getComputedStyle(element).position === 'static') {
		element.style.position = 'relative';
	}

	const object = document.createElement('object');
	object.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
	object.type = 'text/html';

	let win;

	object.onload = () => {
		win = object.contentDocument.defaultView;
		win.addEventListener('resize', fn);
	};

	if (/Trident/.test(navigator.userAgent)) {
		element.appendChild(object);
		object.data = 'about:blank';
	} else {
		object.data = 'about:blank';
		element.appendChild(object);
	}

	return {
		cancel: () => {
			win && win.removeEventListener && win.removeEventListener('resize', fn);
			element.removeChild(object);
		}
	};
}

export function toggleClass(element, name, toggle) {
	element.classList.toggle(name, toggle);
}
<commit_msg>coerce toggle argument<commit_after>export function append(target, node) {
	target.appendChild(node);
}

export function insert(target, node, anchor) {
	target.insertBefore(node, anchor);
}

export function detachNode(node) {
	node.parentNode.removeChild(node);
}

export function detachBetween(before, after) {
	while (before.nextSibling && before.nextSibling !== after) {
		before.parentNode.removeChild(before.nextSibling);
	}
}

export function detachBefore(after) {
	while (after.previousSibling) {
		after.parentNode.removeChild(after.previousSibling);
	}
}

export function detachAfter(before) {
	while (before.nextSibling) {
		before.parentNode.removeChild(before.nextSibling);
	}
}

export function reinsertBetween(before, after, target) {
	while (before.nextSibling && before.nextSibling !== after) {
		target.appendChild(before.parentNode.removeChild(before.nextSibling));
	}
}

export function reinsertChildren(parent, target) {
	while (parent.firstChild) target.appendChild(parent.firstChild);
}

export function reinsertAfter(before, target) {
	while (before.nextSibling) target.appendChild(before.nextSibling);
}

export function reinsertBefore(after, target) {
	var parent = after.parentNode;
	while (parent.firstChild !== after) target.appendChild(parent.firstChild);
}

export function destroyEach(iterations, detach) {
	for (var i = 0; i < iterations.length; i += 1) {
		if (iterations[i]) iterations[i].d(detach);
	}
}

export function createFragment() {
	return document.createDocumentFragment();
}

export function createElement(name) {
	return document.createElement(name);
}

export function createSvgElement(name) {
	return document.createElementNS('http://www.w3.org/2000/svg', name);
}

export function createText(data) {
	return document.createTextNode(data);
}

export function createComment() {
	return document.createComment('');
}

export function addListener(node, event, handler) {
	node.addEventListener(event, handler, false);
}

export function removeListener(node, event, handler) {
	node.removeEventListener(event, handler, false);
}

export function setAttribute(node, attribute, value) {
	node.setAttribute(attribute, value);
}

export function setAttributes(node, attributes) {
	for (var key in attributes) {
		if (key === 'style') {
			node.style.cssText = attributes[key];
		} else if (key in node) {
			node[key] = attributes[key];
		} else {
			if (attributes[key] === undefined) removeAttribute(node, key);
			else setAttribute(node, key, attributes[key]);
		}
	}
}

export function setCustomElementData(node, prop, value) {
	if (prop in node) {
		node[prop] = value;
	} else if (value) {
		setAttribute(node, prop, value);
	} else {
		removeAttribute(node, prop);
	}
}

export function removeAttribute(node, attribute) {
	node.removeAttribute(attribute);
}

export function setXlinkAttribute(node, attribute, value) {
	node.setAttributeNS('http://www.w3.org/1999/xlink', attribute, value);
}

export function getBindingGroupValue(group) {
	var value = [];
	for (var i = 0; i < group.length; i += 1) {
		if (group[i].checked) value.push(group[i].__value);
	}
	return value;
}

export function toNumber(value) {
	return value === '' ? undefined : +value;
}

export function timeRangesToArray(ranges) {
	var array = [];
	for (var i = 0; i < ranges.length; i += 1) {
		array.push({ start: ranges.start(i), end: ranges.end(i) });
	}
	return array;
}

export function children (element) {
	return Array.from(element.childNodes);
}

export function claimElement (nodes, name, attributes, svg) {
	for (var i = 0; i < nodes.length; i += 1) {
		var node = nodes[i];
		if (node.nodeName === name) {
			for (var j = 0; j < node.attributes.length; j += 1) {
				var attribute = node.attributes[j];
				if (!attributes[attribute.name]) node.removeAttribute(attribute.name);
			}
			return nodes.splice(i, 1)[0]; // TODO strip unwanted attributes
		}
	}

	return svg ? createSvgElement(name) : createElement(name);
}

export function claimText (nodes, data) {
	for (var i = 0; i < nodes.length; i += 1) {
		var node = nodes[i];
		if (node.nodeType === 3) {
			node.data = data;
			return nodes.splice(i, 1)[0];
		}
	}

	return createText(data);
}

export function setData(text, data) {
	text.data = '' + data;
}

export function setInputType(input, type) {
	try {
		input.type = type;
	} catch (e) {}
}

export function setStyle(node, key, value) {
	node.style.setProperty(key, value);
}

export function selectOption(select, value) {
	for (var i = 0; i < select.options.length; i += 1) {
		var option = select.options[i];

		if (option.__value === value) {
			option.selected = true;
			return;
		}
	}
}

export function selectOptions(select, value) {
	for (var i = 0; i < select.options.length; i += 1) {
		var option = select.options[i];
		option.selected = ~value.indexOf(option.__value);
	}
}

export function selectValue(select) {
	var selectedOption = select.querySelector(':checked') || select.options[0];
	return selectedOption && selectedOption.__value;
}

export function selectMultipleValue(select) {
	return [].map.call(select.querySelectorAll(':checked'), function(option) {
		return option.__value;
	});
}

export function addResizeListener(element, fn) {
	if (getComputedStyle(element).position === 'static') {
		element.style.position = 'relative';
	}

	const object = document.createElement('object');
	object.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
	object.type = 'text/html';

	let win;

	object.onload = () => {
		win = object.contentDocument.defaultView;
		win.addEventListener('resize', fn);
	};

	if (/Trident/.test(navigator.userAgent)) {
		element.appendChild(object);
		object.data = 'about:blank';
	} else {
		object.data = 'about:blank';
		element.appendChild(object);
	}

	return {
		cancel: () => {
			win && win.removeEventListener && win.removeEventListener('resize', fn);
			element.removeChild(object);
		}
	};
}

export function toggleClass(element, name, toggle) {
	element.classList.toggle(name, !!toggle);
}
<|endoftext|>


<commit_before>/*
This module provides two functions, wysiwygize() and qwiz(), which
both convert textareas (identified by id) into rich text editors.

### CT.rte.wysiwygize(nodeid, isrestricted, val, cb, mismatchcb)
	- nodeid: id of target textarea (must exist in DOM)
	- isrestricted: if true, disables media insertion
	- val: string value with which to initialize target text area
	- cb: callback to invoke once textarea is initialized
	- mismatchcb: callback to invoke if the reformatted text doesn't match val
	- tables: if true, include stuff for tables
### CT.rte.qwiz(nodeid, val)
	- nodeid: id of target textarea (must exist in DOM)
	- val: string value with which to initialize target text area

CT.rte.qwiz() just builds a simplified (isrestricted=true) rich text area
after first waiting for the nodeid-indicated node to appear in the DOM.

CT.rte requires the open-source TinyMCE library, pulled in via CT.scriptImport().
*/

//CT.scriptImport("CT.lib.tiny_mce.tiny_mce");
CT.scriptImport("https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.7.13/tinymce.min.js");
CT.rte = {
	// wysiwyg editor widget
	"wysiwygize": function(nodeid, isrestricted, val, cb, mismatchcb, tables, spellcheck) {
		if (!("tinyMCE" in window)) // just in case...
			return CT.scriptImport("https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.7.13/tinymce.min.js", function() {
				CT.rte.wysiwygize(nodeid, isrestricted, val, cb, mismatchcb);
			}, true);
		var d = {
			selector: "#" + nodeid,
			menubar: false,
			plugins: [
				'advlist autolink lists link image charmap print preview anchor textcolor',
				'searchreplace visualblocks code fullscreen',
				'insertdatetime media table contextmenu paste code help wordcount'
			  ],
			toolbar: 'insert | undo redo | formatselect | alignleft aligncenter alignright alignjustify | bold italic underline | forecolor backcolor | bullist numlist outdent indent removeformat help',
		};
		if (isrestricted)
			d.toolbar = d.toolbar.slice(9);
		if (tables)
			d.toolbar += ' | table tabledelete | tableprops tablerowprops tablecellprops | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol';
		tinyMCE.init(d);
		var n = CT.dom.id(nodeid);
		var dothiscbs = [];
		var doset = function(s, followup) {
			n.node.setContent(s);
			if (followup && s != n.get() && confirm("Our WYSIWYG text editor seems to have changed the formatting of your text. Don't worry, it probably still looks the same. Press OK to resave your slightly reformatted content, or Cancel if you don't want to."))
				followup();
		};
		n.get = function(stripnbsp) {
			var c = n.node.getContent();
			return stripnbsp ? c.replace(/ /g, " ") : c;
		};
		n.dothis = function(f) {
			f && dothiscbs.push(f);
			n.node = n.node || tinyMCE.get(nodeid);
			if (!n.node)
				return setTimeout(n.dothis, 200);
			for (var i = 0; i < dothiscbs.length; i++)
				dothiscbs[i]();
			dothiscbs.length = 0;
		};
		n.set = function(s, followup) {
			n.node ? doset(s, followup) : n.dothis(function() { doset(s, followup); });
		};
		n.dothis(function() {
			val && n.set(val, mismatchcb);
			if (spellcheck) {
				var ifrid = nodeid + "_ifr";
				CT.dom.doWhenNodeExists(ifrid, function() {
					CT.dom.id(ifrid).contentDocument.body.spellcheck = true;
				});
			}
			cb && cb();
		});
	},
	"qwiz": function(nodeid, val, unrestricted, tables, spellcheck) {
		var n = CT.dom.id(nodeid);
		if (!n) // wait for node to appear in DOM
			return setTimeout(CT.rte.qwiz, 500, nodeid, val, unrestricted, tables, spellcheck);
		!n.get && CT.rte.wysiwygize(nodeid, !unrestricted, val, null, null, tables, spellcheck);
	}
};
<commit_msg>rte qwiz()/wysiwygize(): support fullscreen arg<commit_after>/*
This module provides two functions, wysiwygize() and qwiz(), which
both convert textareas (identified by id) into rich text editors.

### CT.rte.wysiwygize(nodeid, isrestricted, val, cb, mismatchcb)
	- nodeid: id of target textarea (must exist in DOM)
	- isrestricted: if true, disables media insertion
	- val: string value with which to initialize target text area
	- cb: callback to invoke once textarea is initialized
	- mismatchcb: callback to invoke if the reformatted text doesn't match val
	- tables: if true, include stuff for tables
### CT.rte.qwiz(nodeid, val)
	- nodeid: id of target textarea (must exist in DOM)
	- val: string value with which to initialize target text area

CT.rte.qwiz() just builds a simplified (isrestricted=true) rich text area
after first waiting for the nodeid-indicated node to appear in the DOM.

CT.rte requires the open-source TinyMCE library, pulled in via CT.scriptImport().
*/

//CT.scriptImport("CT.lib.tiny_mce.tiny_mce");
CT.scriptImport("https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.7.13/tinymce.min.js");
CT.rte = {
	// wysiwyg editor widget
	"wysiwygize": function(nodeid, isrestricted, val, cb, mismatchcb, tables, spellcheck, fullscreen) {
		if (!("tinyMCE" in window)) // just in case...
			return CT.scriptImport("https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.7.13/tinymce.min.js", function() {
				CT.rte.wysiwygize(nodeid, isrestricted, val, cb, mismatchcb);
			}, true);
		var d = {
			selector: "#" + nodeid,
			menubar: false,
			plugins: [
				'advlist autolink lists link image charmap print preview anchor textcolor',
				'searchreplace visualblocks code fullscreen',
				'insertdatetime media table contextmenu paste code help wordcount'
			  ],
			toolbar: 'insert | undo redo | formatselect | alignleft aligncenter alignright alignjustify | bold italic underline | forecolor backcolor | bullist numlist outdent indent removeformat help',
		};
		if (isrestricted)
			d.toolbar = d.toolbar.slice(9);
		if (fullscreen)
			d.toolbar += ' | fullscreen';
		if (tables)
			d.toolbar += ' | table tabledelete | tableprops tablerowprops tablecellprops | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol';
		tinyMCE.init(d);
		var n = CT.dom.id(nodeid);
		var dothiscbs = [];
		var doset = function(s, followup) {
			n.node.setContent(s);
			if (followup && s != n.get() && confirm("Our WYSIWYG text editor seems to have changed the formatting of your text. Don't worry, it probably still looks the same. Press OK to resave your slightly reformatted content, or Cancel if you don't want to."))
				followup();
		};
		n.get = function(stripnbsp) {
			var c = n.node.getContent();
			return stripnbsp ? c.replace(/ /g, " ") : c;
		};
		n.dothis = function(f) {
			f && dothiscbs.push(f);
			n.node = n.node || tinyMCE.get(nodeid);
			if (!n.node)
				return setTimeout(n.dothis, 200);
			for (var i = 0; i < dothiscbs.length; i++)
				dothiscbs[i]();
			dothiscbs.length = 0;
		};
		n.set = function(s, followup) {
			n.node ? doset(s, followup) : n.dothis(function() { doset(s, followup); });
		};
		n.dothis(function() {
			val && n.set(val, mismatchcb);
			if (spellcheck) {
				var ifrid = nodeid + "_ifr";
				CT.dom.doWhenNodeExists(ifrid, function() {
					CT.dom.id(ifrid).contentDocument.body.spellcheck = true;
				});
			}
			cb && cb();
		});
	},
	"qwiz": function(nodeid, val, unrestricted, tables, spellcheck, fullscreen) {
		var n = CT.dom.id(nodeid);
		if (!n) // wait for node to appear in DOM
			return setTimeout(CT.rte.qwiz, 500, nodeid, val, unrestricted, tables, spellcheck, fullscreen);
		!n.get && CT.rte.wysiwygize(nodeid, !unrestricted, val, null, null, tables, spellcheck, fullscreen);
	}
};
<|endoftext|>


<commit_before>var createStack = require('../util/stack.js');

/**
 * Adds the top two values of the stack and pushes the result.
 **/
var add = function(state) {
  var res = state.valStack.pop() + state.valStack.pop();
  state.valStack.push(res);
};

/**
 * Multiplies the top two values of the stack and pushes the result.
 **/
var mul = function(state) {
  var res = state.valStack.pop() * state.valStack.pop();
  state.valStack.push(res);
};

/**
 * Divides the top two values of the stack where given the stack: [a, b]
 * the result is a / b.
 * Divide-by-zero results in a value of 0.0.
 * Result is pushed to the stack.
 **/
var div = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  if ( b === 0 ) {
    state.valStack.push(0);
  }
  else {
    state.valStack.push(Math.round(a / b));
  }
};

/**
 * Subtracts the top two values of the stack where given the stack: [a, b]
 * the result is a - b.
 * Result is pushed to stack.
 **/
var sub = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.valStack.push(a - b);
};

/**
 * Compares top two values of the value stack [a, b] and pushes the result (a > b) to the
 * boolStack.
 **/
var greaterThan = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.boolStack.push(a > b);
};

/**
 * Compares top two values of the value stack [a, b] and pushes the result (a < b) to the
 * boolStack.
 **/
var lessThan = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.boolStack.push(a < b);
};

/**
 * Compares top two values of the value stack [a, b] and pushes the result (a === b) to the
 * boolStack.
 **/
var equalTo = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.boolStack.push(a === b);
};

/**
 * Compares top two values of the value stack [a, b] and pushes the result (a !== b) to the
 * boolStack.
 **/
var notEqualTo = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.boolStack.push(a !== b);
};

/**
 * Compares top two values of the value stack [a, b] and pushes the result (a >= b) to the
 * boolStack.
 **/
var greaterOrEqual = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.boolStack.push(a >= b);
};

/**
 * Compares top two values of the value stack [a, b] and pushes the result (a <= b) to the
 * boolStack.
 **/
var lessOrEqual = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.boolStack.push(a <= b);
};

/**
 * PUBLIC API
 * All parser functions return either a function which accepts a stack (empty js array),
 * or undefined.
 **/

/**
 * Creates an instance of the bot state used by parser's output.
 **/
var createState = function() {
  return {
    valStack  : createStack(0, 20),
    boolStack : createStack(true, 20)
  };
};

/**
 * Parses the given string for a literal.
 * If the literal is valid then returns a function which pushes the literal unto the stack.
 * Otherwise returns undefined.
 **/
var literal = function(code) {
  var result = parseInt(code, 10);
  if (!isNaN(result)) {
    return function(state) {
      state.valStack.push(result);
    };
  }
  return undefined;
};

/**
 * Parses the given string as a StackOp and returns a function which
 * executes the operation.
 **/
var stackOp = function(code) {
  var lit = literal(code);
  if (lit !== undefined) {
    return lit;
  }

  if (code.match(/add/)) {
    return add;
  }

  if (code.match(/sub/)) {
    return sub;
  }

  if (code.match(/mul/)) {
    return mul;
  }

  if (code.match(/div/)) {
    return div;
  }

  return undefined;
};

/**
 * Parses the given stream of whitespace-stripped tokens and returns a function
 * which, when given a stack, executes the provided code.
 * Returns undefined if this is a invalid body segment (e.g. does not start with
 * the "start" string).
 **/
var bodyBlock = function(tokenList) {
  var ops   = [],
      op    = {},
      opStr = "";

  opStr = tokenList.shift();
  op    = stackOp(opStr);
  while(op !== undefined && tokenList.length > 0) {
    ops.push(op);

    opStr = tokenList.shift();
    op    = stackOp(opStr);
  }

  // If we hit a premature "cond" or "start" then push the token back into the stream
  // for consumption later.
  if (opStr === "cond" || opStr === "start") {
    tokenList.unshift(opStr);
  }

  return function(state) {
    ops.forEach(function(op) {
      op(state);
    });
  };
};

/**
 * Parses the code-point as a BoolOp. If parsing is successful then
 * returns a function which computes the bool op, else returns undefined.
 **/
var boolOp = function(code) {
  if (code.length > 2) { return undefined; } // quick check

  if (code === ">") {
    return greaterThan;
  }

  if (code === "<") {
    return lessThan;
  }

  if (code === "=") {
    return equalTo;
  }

  if (code === "!=") {
    return notEqualTo;
  }

  if (code === ">=") {
    return greaterOrEqual;
  }

  if (code === "<=") {
    return lessOrEqual;
  }

  return undefined;
};

var condExpr = function(code) {
  var op = boolOp(code);
  if (op === undefined) {
    return stackOp(code);
  }

  return op;
};

var condBlock = function(tokenList) {
  var exprStr   = "",
      expr      = {},
      condExprs = [];

  exprStr = tokenList.shift();

  if (exprStr !== "cond") {
    if (exprStr === "start") {
      return function() {
        /* do nothing, there are no conditions */
        return;
      };
    }
    return undefined;
  }

  exprStr = tokenList.shift();
  expr    = condExpr(exprStr);
  while(expr !== undefined && tokenList.length > 0) {
    condExprs.push(expr);

    exprStr = tokenList.shift();
    expr    = condExpr(exprStr);
  }

  // if code is malformed so that this cond runs into another,
  // then this cond is a no-op and the next cond token should
  // be returned to the stream.
  if (exprStr === "cond") {
    tokenList.unshift(exprStr);
    return undefined;
  }

  // This token stream runs into a stop command without a body
  // so no point in evaluating the cond block.
  if (exprStr === "stop") {
    return undefined;
  }

  // This token stream hits a premature end. Push the end token
  // in case someone is interested in it then return a no-op.
  if (exprStr === "end") {
    tokenList.unshift(exprStr);
    return undefined;
  }

  // Ran out of tokens before we hit a terminating condition
  // so return undefined.
  if (exprStr !== "start" && tokenList.length === 0) {
    return undefined;
  }

  return function(state) {
    condExprs.forEach(function(expr) {
      expr(state);
    });
  };
};

var gene = function(tokenList) {
  var cond = condBlock(tokenList);

  while(cond === undefined && tokenList.length > 0 && tokenList[0] !== "end") {
    cond = condBlock(tokenList);
  }

  if (cond === undefined) {
    return undefined;
  }

  var body = bodyBlock(tokenList);
  if (body === undefined) {
    return undefined;
  }

  return function(state) {
    var execute = false;

    cond(state);

    execute = state.boolStack.stack.reduce(function(prev, cur) {
      return prev && cur;
    }, true);

    if (execute) {
      body(state);
    }
  };
};

module.exports = {
  literal     : literal,
  stackOp     : stackOp,
  body        : bodyBlock,
  createState : createState,
  boolOp      : boolOp,
  condExpr    : condExpr,
  condBlock   : condBlock,
  gene        : gene
};

<commit_msg>implemented dna parser<commit_after>var createStack = require('../util/stack.js');

/**
 * Adds the top two values of the stack and pushes the result.
 **/
var add = function(state) {
  var res = state.valStack.pop() + state.valStack.pop();
  state.valStack.push(res);
};

/**
 * Multiplies the top two values of the stack and pushes the result.
 **/
var mul = function(state) {
  var res = state.valStack.pop() * state.valStack.pop();
  state.valStack.push(res);
};

/**
 * Divides the top two values of the stack where given the stack: [a, b]
 * the result is a / b.
 * Divide-by-zero results in a value of 0.0.
 * Result is pushed to the stack.
 **/
var div = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  if ( b === 0 ) {
    state.valStack.push(0);
  }
  else {
    state.valStack.push(Math.round(a / b));
  }
};

/**
 * Subtracts the top two values of the stack where given the stack: [a, b]
 * the result is a - b.
 * Result is pushed to stack.
 **/
var sub = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.valStack.push(a - b);
};

/**
 * Compares top two values of the value stack [a, b] and pushes the result (a > b) to the
 * boolStack.
 **/
var greaterThan = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.boolStack.push(a > b);
};

/**
 * Compares top two values of the value stack [a, b] and pushes the result (a < b) to the
 * boolStack.
 **/
var lessThan = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.boolStack.push(a < b);
};

/**
 * Compares top two values of the value stack [a, b] and pushes the result (a === b) to the
 * boolStack.
 **/
var equalTo = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.boolStack.push(a === b);
};

/**
 * Compares top two values of the value stack [a, b] and pushes the result (a !== b) to the
 * boolStack.
 **/
var notEqualTo = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.boolStack.push(a !== b);
};

/**
 * Compares top two values of the value stack [a, b] and pushes the result (a >= b) to the
 * boolStack.
 **/
var greaterOrEqual = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.boolStack.push(a >= b);
};

/**
 * Compares top two values of the value stack [a, b] and pushes the result (a <= b) to the
 * boolStack.
 **/
var lessOrEqual = function(state) {
  var b = state.valStack.pop();
  var a = state.valStack.pop();

  state.boolStack.push(a <= b);
};

/**
 * PUBLIC API
 * All parser functions return either a function which accepts a stack (empty js array),
 * or undefined.
 **/

/**
 * Creates an instance of the bot state used by parser's output.
 **/
var createState = function() {
  return {
    valStack  : createStack(0, 20),
    boolStack : createStack(true, 20)
  };
};

/**
 * Parses the given string for a literal.
 * If the literal is valid then returns a function which pushes the literal unto the stack.
 * Otherwise returns undefined.
 **/
var literal = function(code) {
  var result = parseInt(code, 10);
  if (!isNaN(result)) {
    return function(state) {
      state.valStack.push(result);
    };
  }
  return undefined;
};

/**
 * Parses the given string as a StackOp and returns a function which
 * executes the operation.
 **/
var stackOp = function(code) {
  var lit = literal(code);
  if (lit !== undefined) {
    return lit;
  }

  if (code.match(/add/)) {
    return add;
  }

  if (code.match(/sub/)) {
    return sub;
  }

  if (code.match(/mul/)) {
    return mul;
  }

  if (code.match(/div/)) {
    return div;
  }

  return undefined;
};

/**
 * Parses the given stream of whitespace-stripped tokens and returns a function
 * which, when given a stack, executes the provided code.
 * Returns undefined if this is a invalid body segment (e.g. does not start with
 * the "start" string).
 **/
var bodyBlock = function(tokenList) {
  var ops   = [],
      op    = {},
      opStr = "";

  opStr = tokenList.shift();
  op    = stackOp(opStr);
  while(op !== undefined && tokenList.length > 0) {
    ops.push(op);

    opStr = tokenList.shift();
    op    = stackOp(opStr);
  }

  // If we hit a premature "cond" or "start" then push the token back into the stream
  // for consumption later.
  if (opStr === "cond" || opStr === "start") {
    tokenList.unshift(opStr);
  }

  return function(state) {
    ops.forEach(function(op) {
      op(state);
    });
  };
};

/**
 * Parses the code-point as a BoolOp. If parsing is successful then
 * returns a function which computes the bool op, else returns undefined.
 **/
var boolOp = function(code) {
  if (code.length > 2) { return undefined; } // quick check

  if (code === ">") {
    return greaterThan;
  }

  if (code === "<") {
    return lessThan;
  }

  if (code === "=") {
    return equalTo;
  }

  if (code === "!=") {
    return notEqualTo;
  }

  if (code === ">=") {
    return greaterOrEqual;
  }

  if (code === "<=") {
    return lessOrEqual;
  }

  return undefined;
};

var condExpr = function(code) {
  var op = boolOp(code);
  if (op === undefined) {
    return stackOp(code);
  }

  return op;
};

var condBlock = function(tokenList) {
  var exprStr   = "",
      expr      = {},
      condExprs = [];

  exprStr = tokenList.shift();

  if (exprStr !== "cond") {
    if (exprStr === "start") {
      return function() {
        /* do nothing, there are no conditions */
        return;
      };
    }
    return undefined;
  }

  exprStr = tokenList.shift();
  expr    = condExpr(exprStr);
  while(expr !== undefined && tokenList.length > 0) {
    condExprs.push(expr);

    exprStr = tokenList.shift();
    expr    = condExpr(exprStr);
  }

  // if code is malformed so that this cond runs into another,
  // then this cond is a no-op and the next cond token should
  // be returned to the stream.
  if (exprStr === "cond") {
    tokenList.unshift(exprStr);
    return undefined;
  }

  // This token stream runs into a stop command without a body
  // so no point in evaluating the cond block.
  if (exprStr === "stop") {
    return undefined;
  }

  // This token stream hits a premature end. Push the end token
  // in case someone is interested in it then return a no-op.
  if (exprStr === "end") {
    tokenList.unshift(exprStr);
    return undefined;
  }

  // Ran out of tokens before we hit a terminating condition
  // so return undefined.
  if (exprStr !== "start" && tokenList.length === 0) {
    return undefined;
  }

  return function(state) {
    condExprs.forEach(function(expr) {
      expr(state);
    });
  };
};

var gene = function(tokenList) {
  var cond = condBlock(tokenList);

  while(cond === undefined && tokenList.length > 0 && tokenList[0] !== "end") {
    cond = condBlock(tokenList);
  }

  if (cond === undefined) {
    return undefined;
  }

  var body = bodyBlock(tokenList);
  if (body === undefined) {
    return undefined;
  }

  return function(state) {
    var execute = false;

    cond(state);

    execute = state.boolStack.stack.reduce(function(prev, cur) {
      return prev && cur;
    }, true);

    if (execute) {
      body(state);
    }
  };
};

var parseDna = function(tokenList) {
  var geneBlock  = gene(tokenList),
      genes = [];

  while(geneBlock !== undefined) {
    genes.push(geneBlock);

    geneBlock = gene(tokenList);
  }

  return function(state) {
    genes.forEach(function(geneBlock) {
      // flush state before each gene is executed
      state.valStack.stack  = [];
      state.boolStack.stack = [];

      geneBlock(state);
    });
  };
};

module.exports = {
  literal     : literal,
  stackOp     : stackOp,
  body        : bodyBlock,
  createState : createState,
  boolOp      : boolOp,
  condExpr    : condExpr,
  condBlock   : condBlock,
  gene        : gene,
  parseDna    : parseDna
};

<|endoftext|>


<commit_before>'use strict'

const path = require('path')

const logger = require('../logging').logger
const util = require('../util')

function runTests (outputDir, version) {
  const versionDir = path.join(outputDir, String(version))

  function execLog (subprocess) {
    logger.debug('[%s] command: %s', version, subprocess.command)
    logger.debug('[%s] stdout:\n%s', version, subprocess.stdout)
    logger.debug('[%s] stderr:\n%s', version, subprocess.stderr)
  }

  return util.exists(versionDir)
    .then(
      function () {
        const branchNamePromise = util.exec('git rev-parse --abbrev-ref HEAD')
        branchNamePromise.then(execLog)
        const pullPromise = branchNamePromise.then(function (subprocess) {
          const branchName = subprocess.stdout.trimRight()
          return util.exec(`git fetch && git checkout --force ${branchName} && git reset --hard origin/${branchName} && git pull`, {shell: '/bin/bash', cwd: versionDir})
        })
        pullPromise.then(execLog)
        return pullPromise
      },
      function () {
        const dirPromise = util.mkdir(versionDir)
        dirPromise.then(function () {
          logger.debug('[%s] Directory created: %s', version, versionDir)
        })
        const clonePromise = dirPromise.then(function () {
          return util.exec(`git clone . ${versionDir}`)
        })
        clonePromise.then(execLog)
        return clonePromise
      }
    )
    .then(function () {
      const command = `source ${process.env.NVM_DIR}/nvm.sh && nvm use ${version} && npm prune && npm install && npm test`
      const testPromise = util.exec(command, {shell: '/bin/bash', cwd: versionDir})
      testPromise.then(execLog)
      return testPromise
    })
    .then(function () {
      logger.info('[%s] Test case execution success', version)
      return Promise.resolve({version, returnCode: 0})
    })
    .catch(function (err) {
      logger.error('[%s] %s', version, err.message)
      return Promise.resolve({version, returnCode: err.code || 1})
    })
}

module.exports = runTests
<commit_msg>Update run/one to es2015<commit_after>import path from 'path'

import {logger} from '../logging'
import util from '../util'

export default function runTests (outputDir, version) {
  const versionDir = path.join(outputDir, String(version))

  function execLog (subprocess) {
    logger.debug('[%s] command: %s', version, subprocess.command)
    logger.debug('[%s] stdout:\n%s', version, subprocess.stdout)
    logger.debug('[%s] stderr:\n%s', version, subprocess.stderr)
  }

  return util.exists(versionDir)
    .then(
      function () {
        const branchNamePromise = util.exec('git rev-parse --abbrev-ref HEAD')
        branchNamePromise.then(execLog)
        const pullPromise = branchNamePromise.then(function (subprocess) {
          const branchName = subprocess.stdout.trimRight()
          return util.exec(`git fetch && git checkout --force ${branchName} && git reset --hard origin/${branchName} && git pull`, {shell: '/bin/bash', cwd: versionDir})
        })
        pullPromise.then(execLog)
        return pullPromise
      },
      function () {
        const dirPromise = util.mkdir(versionDir)
        dirPromise.then(function () {
          logger.debug('[%s] Directory created: %s', version, versionDir)
        })
        const clonePromise = dirPromise.then(function () {
          return util.exec(`git clone . ${versionDir}`)
        })
        clonePromise.then(execLog)
        return clonePromise
      }
    )
    .then(function () {
      const command = `source ${process.env.NVM_DIR}/nvm.sh && nvm use ${version} && npm prune && npm install && npm test`
      const testPromise = util.exec(command, {shell: '/bin/bash', cwd: versionDir})
      testPromise.then(execLog)
      return testPromise
    })
    .then(function () {
      logger.info('[%s] Test case execution success', version)
      return Promise.resolve({version, returnCode: 0})
    })
    .catch(function (err) {
      logger.error('[%s] %s', version, err.message)
      return Promise.resolve({version, returnCode: err.code || 1})
    })
}
<|endoftext|>


<commit_before>import {
  RECEIVE_CHAT_MESSAGE,
  SEND_CHAT_MESSAGE
} from '../actions/messages';
import { LOGOUT } from '../actions/auth';

export default (state = [], action) => {
  if (action.type === RECEIVE_CHAT_MESSAGE) {
    let newMessage = [action.message];
    return state.concat(newMessage);
  }

  if (action.type === SEND_CHAT_MESSAGE) {
    let newMessage = [action.message];
    return state.concat(newMessage);
  }

  if (action.type === LOGOUT) {
    return [];
  }

  return state;
};
<commit_msg>fix(state): remove duplicate code<commit_after>import {
  RECEIVE_CHAT_MESSAGE,
  SEND_CHAT_MESSAGE
} from '../actions/messages';
import { LOGOUT } from '../actions/auth';

export default (state = [], action) => {
  if (action.type === RECEIVE_CHAT_MESSAGE ||
      action.type === SEND_CHAT_MESSAGE) {
    let newMessage = [action.message];
    return state.concat(newMessage);
  }

  if (action.type === LOGOUT) {
    return [];
  }

  return state;
};
<|endoftext|>