<commit_before>/*
 * ! ${copyright}
 */
sap.ui.define([
	'sap/ui/core/Control',
	'sap/ui/model/base/ManagedObjectModel',
	'sap/m/Toolbar',
	'sap/m/ResponsivePopover',
	'sap/m/Button',
	'sap/m/ToggleButton',
	'sap/m/ToolbarSpacer',
	'sap/ui/model/Filter',
	'sap/ui/model/FilterOperator',
	'sap/ui/dom/containsOrEquals',
	'sap/m/ColumnPopoverItem',
	'sap/m/StandardListItem',
	'sap/m/List'
], function(
	Control,
	ManagedObjectModel,
	Toolbar,
	ResponsivePopover,
	Button,
	ToggleButton,
	ToolbarSpacer,
	Filter,
	FilterOperator,
	containsOrEquals,
	ColumnPopoverItem,
	StandardListItem,
	List
) {
	"use strict";

	/**
	 * Constructor for the control.
	 * @param {string} [sId] id for the new control.
	 * @param {string} [mSettings] initial settings for the new control.
	 *
	 * @class
	 * The ColumnHeaderPopover control provides the capabilities to perform sorting, filter and grouping on a table column.
	 * @extends sap.ui.core.Control
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @since 1.63
	 * @private
	 * @alias sap.m.ColumnHeaderPopover
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var ColumnHeaderPopover = Control.extend("sap.m.ColumnHeaderPopover", /** @lends sap.m.ColumnHeaderPopover.prototype */
	{
		library: "sap.m",
		metadata: {
			properties: {

			},
			aggregations: {
				items: {type : "sap.m.ColumnPopoverItem",  multiple : true, singularName : "item", bindable: true},
				_popover: {type : "sap.m.ResponsivePopover", multiple : false, visibility : "hidden"}
			},
			defaultAggregation: "items"
		}
	});

	ColumnHeaderPopover.prototype.init = function() {
		this._bPopoverCreated = false;
		this._oShownCustomContent = null;
	};

	ColumnHeaderPopover.prototype._createPopover = function() {
		var that = this;
		this._oShownCustomContent = null;
		var oBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m"),
			sCloseText = oBundle.getText("COLUMNHEADERPOPOVER_CLOSE_BUTTON");

		var oPopover = new ResponsivePopover({
			showArrow: false,
			showHeader: false,
			placement: "Bottom",
			verticalScrolling: true,
			horizontalScrolling: false,
			beforeClose: function(oEvent) {
				if (that._oShownCustomContent) {
					that._oShownCustomContent.setVisible(false);
					that._oShownCustomContent = null;
				}
				that._cleanSelection(this);
			}
		});

		this.setAggregation("_popover", oPopover);

		var oToolbar = new Toolbar();
		// enable the diff calculation on the toolbar control
		// this flag is required by the ManagedObject.prototype.updateAggregation
		// the diff calculation is needed to avoid destroying all buttons, which causes auto close of popover
		oToolbar.bUseExtendedChangeDetection = true;
		oPopover.addContent(oToolbar);

		var oFilter = new Filter({
			path: "visible",
			operator: FilterOperator.EQ,
			value1: true
		});

		var fnFactory = function(id, oContext) {
			var oItem = oContext.getObject();
			var oButton;
			if (oItem.isA("sap.m.ColumnPopoverActionItem")) {
				oButton = that._createActionItem(id, oItem);
			} else if (oItem.isA("sap.m.ColumnPopoverCustomItem")) {
				oButton = that._createCustomItem(id, oItem);
			} else if (oItem.isA("sap.m.ColumnPopoverSortItem")) {
				oButton = that._createSortItem(id, oItem);
			}

			oItem._sRelatedId = oButton.sId;
			oButton._sContentId = oItem._sContentId;

			oButton.destroy = function() {
				var oDomRef = this.getDomRef();
				if (oDomRef && containsOrEquals(oDomRef, document.activeElement)) {
					oPopover.focus();
					oPopover.removeContent(that._oShownCustomContent);

				}

				this.constructor.prototype.destroy.apply(this, arguments);
			};

			return oButton;
		};

		oToolbar.bindAggregation("content",{
			path: '/items',
			filters: [oFilter],
			length: 5,
			factory: fnFactory
		});

		oToolbar.updateAggregation = function(sAggregationName) {
				// clear _oShownCustomContent
				if (this._oShownCustomContent) {
					this._oShownCustomContent = null;
				}

				Toolbar.prototype.updateAggregation.apply(this, arguments);

				var aContent = this.getContent();
				if (aContent.length <= 2 || !(aContent[aContent.length - 2] instanceof ToolbarSpacer)) {
					this.addContent(new ToolbarSpacer());
					this.addContent(new Button({
						type: "Transparent",
						icon: "sap-icon://decline",
						tooltip: sCloseText,
						press: [
							oPopover.close, oPopover
						]
					}));
				}

		};

		var oModel = new ManagedObjectModel(this);

		oToolbar.setModel(oModel);

	};

	ColumnHeaderPopover.prototype._createActionItem = function(id, oItem) {
		var that = this;

		return new Button(id, {
			icon: "{icon}",
			tooltip: "{text}",
			type: "Transparent",
			press: function() {
				var oPopover = that.getAggregation("_popover");

				if (that._oShownCustomContent) {
					that._oShownCustomContent.setVisible(false);
					that._oShownCustomContent = null;

					// set other buttons unpressed
					that._cleanSelection(oPopover, this);
				}
				oItem.firePress();
			}
		});
	};

	ColumnHeaderPopover.prototype._createCustomItem = function(id, oItem) {
		var that = this;
		var oPopover = this.getAggregation("_popover");
		var oContent = oItem.getContent();
		if (oContent) {
			oContent.setVisible(false);
			oItem._sContentId = oContent.sId;
		}
		oPopover.addContent(oContent);

		return new ToggleButton(id, {
			icon: "{icon}",
			type: "Transparent",
			tooltip: "{text}",
			press: function() {
				// between two custom items
				if (that._oShownCustomContent) {
					that._oShownCustomContent.setVisible(false);
				}
				if (this.getPressed()) {
					// set other buttons unpressed
					that._cleanSelection(oPopover, this);

					oItem.fireBeforeShowContent();
					if (oContent) {
						oContent.setVisible(true);
						that._oShownCustomContent = oContent;
					}

				} else {
					if (oContent) {
						oContent.setVisible(false);
						that._oShownCustomContent = null;
					}
				}

			}
		});

	};

	ColumnHeaderPopover.prototype._createSortItem = function(id, oItem) {
		var that = this;
		var oBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m"),
			sSortText = oBundle.getText("COLUMNHEADERPOPOVER_SORT_BUTTON");
		var aSortChildren = oItem.getSortChildren();

		if (aSortChildren.length > 1) {
			var oPopover = this.getAggregation("_popover");
			var oList = new List();

			for (var i = 0; i < aSortChildren.length; i++) {
				var oListItem = new StandardListItem({
					title: aSortChildren[i].getText(),
					type: "Active"
				});

				oList.addItem(oListItem);
				oListItem.data("key", aSortChildren[i].getKey());
			}

			oList.attachEvent( "itemPress", function(oEvent) {
				// close the popover first to prevent focus lost
				oPopover.close();

				var oListItem = oEvent.getParameter("listItem");
				oItem.fireSort({
					property: oListItem.data("key")
				});
			});
			oList.setVisible(false);
			oPopover.addContent(oList);

			return new ToggleButton(id, {
				icon: "sap-icon://sort",
				type: "Transparent",
				tooltip: sSortText,
				press: function() {
					// between two custom items
					if (that._oShownCustomContent) {
						that._oShownCustomContent.setVisible(false);
					}
					if (this.getPressed()) {
						// set other buttons unpressed
						that._cleanSelection(oPopover, this);

						if (oList) {
							oList.setVisible(true);
							that._oShownCustomContent = oList;
						}

					} else {
						if (oList) {
							oList.setVisible(false);
							that._oShownCustomContent = null;
						}
					}

				}
			});

		} else {

			return new Button(id, {
				icon: "sap-icon://sort",
				type: "Transparent",
				tooltip: sSortText,
				press: function() {
					var oPopover = that.getAggregation("_popover");

					if (that._oShownCustomContent) {
						that._oShownCustomContent.setVisible(false);
						that._oShownCustomContent = null;

						// set other buttons unpressed
						that._cleanSelection(oPopover, this);
					}

					// close the popover first to prevent focus lost
					oPopover.close();
					oItem.fireSort({
						property: aSortChildren[0] ? aSortChildren[0].getKey() : null
					});
				}
			});
		}
	};

	ColumnHeaderPopover.prototype._cleanSelection = function(oPopover, oButton) {
		var oContent = oPopover.getContent()[0],
			aButtons;
		aButtons = oContent.getContent();

		if (aButtons) {

			aButtons.forEach(function(oBtn) {
				if ((!oButton || oBtn !== oButton)
						&& oBtn.getPressed
							&& oBtn.getPressed()) {
					oBtn.setPressed(false);
					}

			});

		}

	};

	ColumnHeaderPopover.prototype.openBy = function(oControl) {

		if (!this._bPopoverCreated) {
			this._createPopover();
			this._bPopoverCreated = true;
		}

		var oPopover = this.getAggregation("_popover");
		if (!this._bAppendedToUIArea && !this.getParent()) {
			var oStatic = sap.ui.getCore().getStaticAreaRef();
			oStatic = sap.ui.getCore().getUIArea(oStatic);
			oStatic.addContent(this, true);
			this._bAppendedToUIArea = true;
		}

		var oOpenerDomRef = oControl.getFocusDomRef();
		if (oOpenerDomRef) {
			oPopover.setOffsetY(-oOpenerDomRef.clientHeight);
		}
		oPopover.openBy(oControl);
	};

	ColumnHeaderPopover.prototype.invalidate = function(oOrigin) {
		var oPopover = this.getAggregation("_popover");

		// Pop the invalidate call up to the control tree only when the call
		// comes from the internal popover
		// If the call is triggered by this control itself, it does nothing to
		// prevent the renderer of this control to be called.
		if (oOrigin === oPopover) {
			Control.prototype.invalidate.apply(this, arguments);
		}

		return this;
	};

	return ColumnHeaderPopover;
});<commit_msg>[INTERNAL] m.ColumnHeaderPopover: set width of the popover<commit_after>/*
 * ! ${copyright}
 */
sap.ui.define([
	'sap/ui/core/Control',
	'sap/ui/model/base/ManagedObjectModel',
	'sap/m/Toolbar',
	'sap/m/ResponsivePopover',
	'sap/m/Button',
	'sap/m/ToggleButton',
	'sap/m/ToolbarSpacer',
	'sap/ui/model/Filter',
	'sap/ui/model/FilterOperator',
	'sap/ui/dom/containsOrEquals',
	'sap/m/ColumnPopoverItem',
	'sap/m/StandardListItem',
	'sap/m/List'
], function(
	Control,
	ManagedObjectModel,
	Toolbar,
	ResponsivePopover,
	Button,
	ToggleButton,
	ToolbarSpacer,
	Filter,
	FilterOperator,
	containsOrEquals,
	ColumnPopoverItem,
	StandardListItem,
	List
) {
	"use strict";

	/**
	 * Constructor for the control.
	 * @param {string} [sId] id for the new control.
	 * @param {string} [mSettings] initial settings for the new control.
	 *
	 * @class
	 * The ColumnHeaderPopover control provides the capabilities to perform sorting, filter and grouping on a table column.
	 * @extends sap.ui.core.Control
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @since 1.63
	 * @private
	 * @alias sap.m.ColumnHeaderPopover
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var ColumnHeaderPopover = Control.extend("sap.m.ColumnHeaderPopover", /** @lends sap.m.ColumnHeaderPopover.prototype */
	{
		library: "sap.m",
		metadata: {
			properties: {

			},
			aggregations: {
				items: {type : "sap.m.ColumnPopoverItem",  multiple : true, singularName : "item", bindable: true},
				_popover: {type : "sap.m.ResponsivePopover", multiple : false, visibility : "hidden"}
			},
			defaultAggregation: "items"
		}
	});

	ColumnHeaderPopover.prototype.init = function() {
		this._bPopoverCreated = false;
		this._oShownCustomContent = null;
	};

	ColumnHeaderPopover.prototype._createPopover = function() {
		var that = this;
		this._oShownCustomContent = null;
		var oBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m"),
			sCloseText = oBundle.getText("COLUMNHEADERPOPOVER_CLOSE_BUTTON");

		var oPopover = new ResponsivePopover({
			showArrow: false,
			showHeader: false,
			placement: "Bottom",
			verticalScrolling: true,
			horizontalScrolling: false,
			beforeClose: function(oEvent) {
				if (that._oShownCustomContent) {
					that._oShownCustomContent.setVisible(false);
					that._oShownCustomContent = null;
				}
				that._cleanSelection(this);
			}
		});

		this.setAggregation("_popover", oPopover);

		var oToolbar = new Toolbar();
		// enable the diff calculation on the toolbar control
		// this flag is required by the ManagedObject.prototype.updateAggregation
		// the diff calculation is needed to avoid destroying all buttons, which causes auto close of popover
		oToolbar.bUseExtendedChangeDetection = true;
		oPopover.addContent(oToolbar);

		var oFilter = new Filter({
			path: "visible",
			operator: FilterOperator.EQ,
			value1: true
		});

		var fnFactory = function(id, oContext) {
			var oItem = oContext.getObject();
			var oButton;
			if (oItem.isA("sap.m.ColumnPopoverActionItem")) {
				oButton = that._createActionItem(id, oItem);
			} else if (oItem.isA("sap.m.ColumnPopoverCustomItem")) {
				oButton = that._createCustomItem(id, oItem);
			} else if (oItem.isA("sap.m.ColumnPopoverSortItem")) {
				oButton = that._createSortItem(id, oItem);
			}

			oItem._sRelatedId = oButton.sId;
			oButton._sContentId = oItem._sContentId;

			oButton.destroy = function() {
				var oDomRef = this.getDomRef();
				if (oDomRef && containsOrEquals(oDomRef, document.activeElement)) {
					oPopover.focus();
					oPopover.removeContent(that._oShownCustomContent);

				}

				this.constructor.prototype.destroy.apply(this, arguments);
			};

			return oButton;
		};

		oToolbar.bindAggregation("content",{
			path: '/items',
			filters: [oFilter],
			length: 5,
			factory: fnFactory
		});

		oToolbar.updateAggregation = function(sAggregationName) {
				// clear _oShownCustomContent
				if (this._oShownCustomContent) {
					this._oShownCustomContent = null;
				}

				Toolbar.prototype.updateAggregation.apply(this, arguments);

				var aContent = this.getContent();
				if (aContent.length <= 2 || !(aContent[aContent.length - 2] instanceof ToolbarSpacer)) {
					this.addContent(new ToolbarSpacer());
					this.addContent(new Button({
						type: "Transparent",
						icon: "sap-icon://decline",
						tooltip: sCloseText,
						press: [
							oPopover.close, oPopover
						]
					}));
				}

		};

		var oModel = new ManagedObjectModel(this);

		oToolbar.setModel(oModel);

	};

	ColumnHeaderPopover.prototype._createActionItem = function(id, oItem) {
		var that = this;

		return new Button(id, {
			icon: "{icon}",
			tooltip: "{text}",
			type: "Transparent",
			press: function() {
				var oPopover = that.getAggregation("_popover");

				if (that._oShownCustomContent) {
					that._oShownCustomContent.setVisible(false);
					that._oShownCustomContent = null;

					// set other buttons unpressed
					that._cleanSelection(oPopover, this);
				}
				oItem.firePress();
			}
		});
	};

	ColumnHeaderPopover.prototype._createCustomItem = function(id, oItem) {
		var that = this;
		var oPopover = this.getAggregation("_popover");
		var oContent = oItem.getContent();
		if (oContent) {
			oContent.setVisible(false);
			oItem._sContentId = oContent.sId;
		}
		oPopover.addContent(oContent);

		return new ToggleButton(id, {
			icon: "{icon}",
			type: "Transparent",
			tooltip: "{text}",
			press: function() {
				// between two custom items
				if (that._oShownCustomContent) {
					that._oShownCustomContent.setVisible(false);
				}
				if (this.getPressed()) {
					// set other buttons unpressed
					that._cleanSelection(oPopover, this);

					oItem.fireBeforeShowContent();
					if (oContent) {
						oContent.setVisible(true);
						that._oShownCustomContent = oContent;
					}

				} else {
					if (oContent) {
						oContent.setVisible(false);
						that._oShownCustomContent = null;
					}
				}

			}
		});

	};

	ColumnHeaderPopover.prototype._createSortItem = function(id, oItem) {
		var that = this;
		var oBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m"),
			sSortText = oBundle.getText("COLUMNHEADERPOPOVER_SORT_BUTTON");
		var aSortChildren = oItem.getSortChildren();

		if (aSortChildren.length > 1) {
			var oPopover = this.getAggregation("_popover");
			var oList = new List();

			for (var i = 0; i < aSortChildren.length; i++) {
				var oListItem = new StandardListItem({
					title: aSortChildren[i].getText(),
					type: "Active"
				});

				oList.addItem(oListItem);
				oListItem.data("key", aSortChildren[i].getKey());
			}

			oList.attachEvent( "itemPress", function(oEvent) {
				// close the popover first to prevent focus lost
				oPopover.close();

				var oListItem = oEvent.getParameter("listItem");
				oItem.fireSort({
					property: oListItem.data("key")
				});
			});
			oList.setVisible(false);
			oPopover.addContent(oList);

			return new ToggleButton(id, {
				icon: "sap-icon://sort",
				type: "Transparent",
				tooltip: sSortText,
				press: function() {
					// between two custom items
					if (that._oShownCustomContent) {
						that._oShownCustomContent.setVisible(false);
					}
					if (this.getPressed()) {
						// set other buttons unpressed
						that._cleanSelection(oPopover, this);

						if (oList) {
							oList.setVisible(true);
							that._oShownCustomContent = oList;
						}

					} else {
						if (oList) {
							oList.setVisible(false);
							that._oShownCustomContent = null;
						}
					}

				}
			});

		} else {

			return new Button(id, {
				icon: "sap-icon://sort",
				type: "Transparent",
				tooltip: sSortText,
				press: function() {
					var oPopover = that.getAggregation("_popover");

					if (that._oShownCustomContent) {
						that._oShownCustomContent.setVisible(false);
						that._oShownCustomContent = null;

						// set other buttons unpressed
						that._cleanSelection(oPopover, this);
					}

					// close the popover first to prevent focus lost
					oPopover.close();
					oItem.fireSort({
						property: aSortChildren[0] ? aSortChildren[0].getKey() : null
					});
				}
			});
		}
	};

	ColumnHeaderPopover.prototype._cleanSelection = function(oPopover, oButton) {
		var oContent = oPopover.getContent()[0],
			aButtons;
		aButtons = oContent.getContent();

		if (aButtons) {

			aButtons.forEach(function(oBtn) {
				if ((!oButton || oBtn !== oButton)
						&& oBtn.getPressed
							&& oBtn.getPressed()) {
					oBtn.setPressed(false);
					}

			});

		}

	};

	ColumnHeaderPopover.prototype.openBy = function(oControl) {

		if (!this._bPopoverCreated) {
			this._createPopover();
			this._bPopoverCreated = true;
		}

		var oPopover = this.getAggregation("_popover");
		if (!this._bAppendedToUIArea && !this.getParent()) {
			var oStatic = sap.ui.getCore().getStaticAreaRef();
			oStatic = sap.ui.getCore().getUIArea(oStatic);
			oStatic.addContent(this, true);
			this._bAppendedToUIArea = true;
		}

		var oOpenerDomRef = oControl.getFocusDomRef();
		if (oOpenerDomRef) {
			oPopover.setOffsetY(-oOpenerDomRef.clientHeight);
		}
		if (oControl.$().width()) {
			oPopover.setContentWidth(oControl.$().width() + "px");
		}
		oPopover.openBy(oControl);
	};

	ColumnHeaderPopover.prototype.invalidate = function(oOrigin) {
		var oPopover = this.getAggregation("_popover");

		// Pop the invalidate call up to the control tree only when the call
		// comes from the internal popover
		// If the call is triggered by this control itself, it does nothing to
		// prevent the renderer of this control to be called.
		if (oOrigin === oPopover) {
			Control.prototype.invalidate.apply(this, arguments);
		}

		return this;
	};

	return ColumnHeaderPopover;
});<|endoftext|>


<commit_before>/*

*/

(function( $, undefined ) {

  'use strict';
    $.KBWidget({

		  name: "kbaseAuthenticatedWidget",

        version: "1.0.0",
        _accessors : [
            {name : 'auth', setter: 'setAuth'},
            'sessionId',
            'authToken',
            'user_id',
            'loggedInCallback',
            'loggedOutCallback',
            'loggedInQueryCallback'
        ],
        options: {
            auth : undefined
        },

        init: function(options) {

            this._super(options);

            // An authenticated widget needs to get the initial auth state
            // from the KBaseSessionSync jquery extension.
            var sessionObject = $.KBaseSessionSync.getKBaseSession();
            this.setAuth(sessionObject);
            if (this.loggedInQueryCallback && sessionObject && sessionObject.token) {
              this.callAfterInit(function () {
                 this.loggedInQueryCallback(sessionObject);
              }.bind(this));
            }

            postal.channel('session').subscribe('login.success', function (session) {
                this.setAuth(session);
                if (this.loggedInCallback) {
                    this.loggedInCallback(undefined, session);
                }
              }.bind(this));

            postal.channel('session').subscribe('logout.success', function (session) {
                this.setAuth(undefined);
                if (this.loggedOutCallback) {
                    this.loggedOutCallback();
                }
              }.bind(this));

            /*
            TODO:used anywhere?
            NB: used to initialize the session in this widget, but
            it relies on the SYNCHRONOUS nature of jquery events.
            IMHO this is not good, because it obscures the nature
            of what is going on here -- a simple method call of a
            global object which knows about session state.
            $(document).trigger(
                'loggedInQuery',
                $.proxy(function (auth) {
                //console.log("CALLS LIQ");
                    this.setAuth(auth);

                    if (auth.kbase_sessionid) {
                        this.callAfterInit(
                            $.proxy(function() {
                                if (this.loggedInQueryCallback) {
                                    this.loggedInQueryCallback(auth)
                                }
                            }, this)
                        );
                    }
                }, this)
            );
            */

            return this;

        },

        setAuth : function (newAuth) {
            if (!newAuth) {
              newAuth = {};
            }
            this.setValueForKey('auth', newAuth);

            this.sessionId(newAuth.kbase_sessionid);
            this.authToken(newAuth.token);
            this.user_id(newAuth.user_id);
            //console.log("SETS AUTH TO "); console.log(newAuth);
            //console.log(this);
        },

        loggedInQueryCallback : function(args) {
            if (this.loggedInCallback) {
                this.loggedInCallback(undefined,args);
            }
        },

    });

}( jQuery ) );
<commit_msg>Use the internal attribute value for auth, not the passed in value. The setAuth method will normalize the incoming value -- specifically set it to an empty object if it is falsy.<commit_after>/*

*/

(function( $, undefined ) {

  'use strict';
    $.KBWidget({

		  name: "kbaseAuthenticatedWidget",

        version: "1.0.0",
        _accessors : [
            {name : 'auth', setter: 'setAuth'},
            'sessionId',
            'authToken',
            'user_id',
            'loggedInCallback',
            'loggedOutCallback',
            'loggedInQueryCallback'
        ],
        options: {
            auth : undefined
        },

        init: function(options) {

            this._super(options);

            // An authenticated widget needs to get the initial auth state
            // from the KBaseSessionSync jquery extension.
            var sessionObject = $.KBaseSessionSync.getKBaseSession();
            this.setAuth(sessionObject);

            // This is how to pull the value out of the auth attribute.
            var auth = this.auth();
            if (this.loggedInQueryCallback && auth && auth.token) {
              this.callAfterInit(function () {
                // use the current auth attribute value, since this is run asynchronously, and who knows,
                // it may have changed.
                 this.loggedInQueryCallback(this.auth());
              }.bind(this));
            }

            postal.channel('session').subscribe('login.success', function (session) {
                this.setAuth(session);
                if (this.loggedInCallback) {
                    this.loggedInCallback(undefined, this.auth());
                }
              }.bind(this));

            postal.channel('session').subscribe('logout.success', function (session) {
                this.setAuth(undefined);
                if (this.loggedOutCallback) {
                    this.loggedOutCallback();
                }
              }.bind(this));

            /*
            TODO:used anywhere?
            NB: used to initialize the session in this widget, but
            it relies on the SYNCHRONOUS nature of jquery events.
            IMHO this is not good, because it obscures the nature
            of what is going on here -- a simple method call of a
            global object which knows about session state.
            $(document).trigger(
                'loggedInQuery',
                $.proxy(function (auth) {
                //console.log("CALLS LIQ");
                    this.setAuth(auth);

                    if (auth.kbase_sessionid) {
                        this.callAfterInit(
                            $.proxy(function() {
                                if (this.loggedInQueryCallback) {
                                    this.loggedInQueryCallback(auth)
                                }
                            }, this)
                        );
                    }
                }, this)
            );
            */

            return this;

        },

        setAuth : function (newAuth) {
            if (!newAuth) {
              newAuth = {};
            }
            this.setValueForKey('auth', newAuth);

            this.sessionId(newAuth.kbase_sessionid);
            this.authToken(newAuth.token);
            this.user_id(newAuth.user_id);
            //console.log("SETS AUTH TO "); console.log(newAuth);
            //console.log(this);
        },

        loggedInQueryCallback : function(args) {
            if (this.loggedInCallback) {
                this.loggedInCallback(undefined,args);
            }
        },

    });

}( jQuery ) );
<|endoftext|>


<commit_before>var Workspace = Backbone.View.extend({
    className: 'tab_container',

    events: {
        'click .sidebar_separator': 'toggle_sidebar',
        'change .cubes': 'new_query',
        'drop': 'remove_dimension'
    },

    template: function() {
        return Saiku.template.get('Workspace')({
            cube_navigation: Saiku.session.cube_navigation
        });
    },

    render: function() {
        // Load template
        $(this.el).html(this.template());

        // Generate toolbar
        this.toolbar.render();
        $(this.el).find('.workspace_toolbar').append($(this.toolbar.el));

        // Generate drop zones
        this.drop_zones.render();
        $(this.drop_zones.el)
            .insertAfter($(this.el).find('.workspace_toolbar'));

        // Activate sidebar for removing elements
        $(this.el).find('.sidebar')
            .droppable();

        return this;
    },

    clear: function() {
        // Prepare the workspace for a new query
        $(this.el).find('.workspace_results,.connectable')
            .html('');
    },

    initialize: function(args) {
        // Maintain `this` in jQuery event handlers
        _.bindAll(this, "adjust", "toggle_sidebar", "flash_cube_navigation");

        // Generate toolbar and append to workspace
        this.toolbar = new WorkspaceToolbar({ workspace: this });
        this.tab = args.tab;

        // Create drop zones
        this.drop_zones = new WorkspaceDropZone({ workspace: this });

        // Adjust tab when selected
        this.tab.bind('tab:select', this.adjust);
        $(window).resize(this.adjust);

        // Flash cube navigation when rendered
        this.tab.bind('tab_rendered', this.flash_cube_navigation);
    },

    adjust: function() {
        // Adjust the height of the separator
        $separator = $(this.el).find('.sidebar_separator');
        $separator.height($("body").height() - 87);
    },

    toggle_sidebar: function() {
        // Toggle sidebar
        $(this.el).find('.sidebar').toggleClass('hide');
        var new_margin = $(this.el).find('.sidebar').hasClass('hide') ?
                5 : 265;
        $(this.el).find('.workspace_inner').css({ 'margin-left': new_margin });
    },

    flash_cube_navigation: function() {
        // Draw user's attention to cube navigation
        $(this.el).find('.cubes')
            .parent()
            .animate({ backgroundColor: '#AC1614' }, 'fast')
            .animate({ backgroundColor: '#fff' }, 'fast');
    },

    new_query: function() {
        // Delete the existing query
        if (this.query) {
            this.query.destroy();
        }

        // Initialize the new query
        var selected_cube = $(this.el).find('.cubes').val();
        this.query = new Query({ cube: selected_cube });

        // Create new DimensionList and MeasureList
        this.dimension_list = new DimensionList({
            workspace: this,
            dimension: Saiku.session.dimensions[selected_cube]
        });
        $(this.el).find('.dimension_tree').html('').append($(this.dimension_list.el));

        this.measure_list = new DimensionList({
            workspace: this,
            dimension: Saiku.session.measures[selected_cube]
        });
        $(this.el).find('.measure_tree').html('').append($(this.measure_list.el));

        // Clear workspace
        this.clear();
    },

    remove_dimension: function(event, ui) {
        this.drop_zones.remove_dimension(event, ui);
    }
});<commit_msg>Enable the appropriate toolbar items<commit_after>var Workspace = Backbone.View.extend({
    className: 'tab_container',

    events: {
        'click .sidebar_separator': 'toggle_sidebar',
        'change .cubes': 'new_query',
        'drop': 'remove_dimension'
    },

    template: function() {
        return Saiku.template.get('Workspace')({
            cube_navigation: Saiku.session.cube_navigation
        });
    },

    render: function() {
        // Load template
        $(this.el).html(this.template());

        // Generate toolbar
        this.toolbar.render();
        $(this.el).find('.workspace_toolbar').append($(this.toolbar.el));

        // Generate drop zones
        this.drop_zones.render();
        $(this.drop_zones.el)
            .insertAfter($(this.el).find('.workspace_toolbar'));

        // Activate sidebar for removing elements
        $(this.el).find('.sidebar')
            .droppable();

        return this;
    },

    clear: function() {
        // Prepare the workspace for a new query
        $(this.el).find('.workspace_results,.connectable')
            .html('');
    },

    initialize: function(args) {
        // Maintain `this` in jQuery event handlers
        _.bindAll(this, "adjust", "toggle_sidebar", "flash_cube_navigation");

        // Generate toolbar and append to workspace
        this.toolbar = new WorkspaceToolbar({ workspace: this });
        this.tab = args.tab;

        // Create drop zones
        this.drop_zones = new WorkspaceDropZone({ workspace: this });

        // Adjust tab when selected
        this.tab.bind('tab:select', this.adjust);
        $(window).resize(this.adjust);

        // Flash cube navigation when rendered
        this.tab.bind('tab_rendered', this.flash_cube_navigation);
    },

    adjust: function() {
        // Adjust the height of the separator
        $separator = $(this.el).find('.sidebar_separator');
        $separator.height($("body").height() - 87);
    },

    toggle_sidebar: function() {
        // Toggle sidebar
        $(this.el).find('.sidebar').toggleClass('hide');
        var new_margin = $(this.el).find('.sidebar').hasClass('hide') ?
                5 : 265;
        $(this.el).find('.workspace_inner').css({ 'margin-left': new_margin });
    },

    flash_cube_navigation: function() {
        // Draw user's attention to cube navigation
        $(this.el).find('.cubes')
            .parent()
            .animate({ backgroundColor: '#AC1614' }, 'fast')
            .animate({ backgroundColor: '#fff' }, 'fast');
    },

    new_query: function() {
        // Delete the existing query
        if (this.query) {
            this.query.destroy();
        }

        // Initialize the new query
        var selected_cube = $(this.el).find('.cubes').val();
        this.query = new Query({ cube: selected_cube });

        // Create new DimensionList and MeasureList
        this.dimension_list = new DimensionList({
            workspace: this,
            dimension: Saiku.session.dimensions[selected_cube]
        });
        $(this.el).find('.dimension_tree').html('').append($(this.dimension_list.el));

        this.measure_list = new DimensionList({
            workspace: this,
            dimension: Saiku.session.measures[selected_cube]
        });
        $(this.el).find('.measure_tree').html('').append($(this.measure_list.el));

        // Clear workspace
        this.clear();

        // Make sure appropriate workspace buttons are enabled
        $(this.toolbar.el).find('.button').addClass('disabled_toolbar');
        $(this.toolbar.el).find('.auto,.non_empty')
            .removeClass('disabled_toolbar');
    },

    remove_dimension: function(event, ui) {
        this.drop_zones.remove_dimension(event, ui);
    }
});<|endoftext|>


<commit_before>/**
 * --------------------------------------------------------------------------
 * Bootstrap (v5.2.2): dom/event-handler.js
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
 * --------------------------------------------------------------------------
 */

import { getjQuery } from '../util/index.js'

/**
 * Constants
 */

const namespaceRegex = /[^.]*(?=\..*)\.|.*/
const stripNameRegex = /\..*/
const stripUidRegex = /::\d+$/
const eventRegistry = {} // Events storage
let uidEvent = 1
const customEvents = {
  mouseenter: 'mouseover',
  mouseleave: 'mouseout'
}

const nativeEvents = new Set([
  'click',
  'dblclick',
  'mouseup',
  'mousedown',
  'contextmenu',
  'mousewheel',
  'DOMMouseScroll',
  'mouseover',
  'mouseout',
  'mousemove',
  'selectstart',
  'selectend',
  'keydown',
  'keypress',
  'keyup',
  'orientationchange',
  'touchstart',
  'touchmove',
  'touchend',
  'touchcancel',
  'pointerdown',
  'pointermove',
  'pointerup',
  'pointerleave',
  'pointercancel',
  'gesturestart',
  'gesturechange',
  'gestureend',
  'focus',
  'blur',
  'change',
  'reset',
  'select',
  'submit',
  'focusin',
  'focusout',
  'load',
  'unload',
  'beforeunload',
  'resize',
  'move',
  'DOMContentLoaded',
  'readystatechange',
  'error',
  'abort',
  'scroll'
])

/**
 * Private methods
 */

function makeEventUid(element, uid) {
  return (uid && `${uid}::${uidEvent++}`) || element.uidEvent || uidEvent++
}

function getElementEvents(element) {
  const uid = makeEventUid(element)

  element.uidEvent = uid
  eventRegistry[uid] = eventRegistry[uid] || {}

  return eventRegistry[uid]
}

function bootstrapHandler(element, fn) {
  return function handler(event) {
    hydrateObj(event, { delegateTarget: element })

    if (handler.oneOff) {
      EventHandler.off(element, event.type, fn)
    }

    return fn.apply(element, [event])
  }
}

function bootstrapDelegationHandler(element, selector, fn) {
  return function handler(event) {
    const domElements = element.querySelectorAll(selector)

    for (let { target } = event; target && target !== this; target = target.parentNode) {
      for (const domElement of domElements) {
        if (domElement !== target) {
          continue
        }

        hydrateObj(event, { delegateTarget: target })

        if (handler.oneOff) {
          EventHandler.off(element, event.type, selector, fn)
        }

        return fn.apply(target, [event])
      }
    }
  }
}

function findHandler(events, callable, delegationSelector = null) {
  return Object.values(events)
    .find(event => event.callable === callable && event.delegationSelector === delegationSelector)
}

function normalizeParameters(originalTypeEvent, handler, delegationFunction) {
  const isDelegated = typeof handler === 'string'
  // todo: tooltip passes `false` instead of selector, so we need to check
  const callable = isDelegated ? delegationFunction : (handler || delegationFunction)
  let typeEvent = getTypeEvent(originalTypeEvent)

  if (!nativeEvents.has(typeEvent)) {
    typeEvent = originalTypeEvent
  }

  return [isDelegated, callable, typeEvent]
}

function addHandler(element, originalTypeEvent, handler, delegationFunction, oneOff) {
  if (typeof originalTypeEvent !== 'string' || !element) {
    return
  }

  let [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction)

  // in case of mouseenter or mouseleave wrap the handler within a function that checks for its DOM position
  // this prevents the handler from being dispatched the same way as mouseover or mouseout does
  if (originalTypeEvent in customEvents) {
    const wrapFunction = fn => {
      return function (event) {
        if (!event.relatedTarget || (event.relatedTarget !== event.delegateTarget && !event.delegateTarget.contains(event.relatedTarget))) {
          return fn.call(this, event)
        }
      }
    }

    callable = wrapFunction(callable)
  }

  const events = getElementEvents(element)
  const handlers = events[typeEvent] || (events[typeEvent] = {})
  const previousFunction = findHandler(handlers, callable, isDelegated ? handler : null)

  if (previousFunction) {
    previousFunction.oneOff = previousFunction.oneOff && oneOff

    return
  }

  const uid = makeEventUid(callable, originalTypeEvent.replace(namespaceRegex, ''))
  const fn = isDelegated ?
    bootstrapDelegationHandler(element, handler, callable) :
    bootstrapHandler(element, callable)

  fn.delegationSelector = isDelegated ? handler : null
  fn.callable = callable
  fn.oneOff = oneOff
  fn.uidEvent = uid
  handlers[uid] = fn

  element.addEventListener(typeEvent, fn, isDelegated)
}

function removeHandler(element, events, typeEvent, handler, delegationSelector) {
  const fn = findHandler(events[typeEvent], handler, delegationSelector)

  if (!fn) {
    return
  }

  element.removeEventListener(typeEvent, fn, Boolean(delegationSelector))
  delete events[typeEvent][fn.uidEvent]
}

function removeNamespacedHandlers(element, events, typeEvent, namespace) {
  const storeElementEvent = events[typeEvent] || {}

  for (const handlerKey of Object.keys(storeElementEvent)) {
    if (handlerKey.includes(namespace)) {
      const event = storeElementEvent[handlerKey]
      removeHandler(element, events, typeEvent, event.callable, event.delegationSelector)
    }
  }
}

function getTypeEvent(event) {
  // allow to get the native events from namespaced events ('click.bs.button' --> 'click')
  event = event.replace(stripNameRegex, '')
  return customEvents[event] || event
}

const EventHandler = {
  on(element, event, handler, delegationFunction) {
    addHandler(element, event, handler, delegationFunction, false)
  },

  one(element, event, handler, delegationFunction) {
    addHandler(element, event, handler, delegationFunction, true)
  },

  off(element, originalTypeEvent, handler, delegationFunction) {
    if (typeof originalTypeEvent !== 'string' || !element) {
      return
    }

    const [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction)
    const inNamespace = typeEvent !== originalTypeEvent
    const events = getElementEvents(element)
    const storeElementEvent = events[typeEvent] || {}
    const isNamespace = originalTypeEvent.startsWith('.')

    if (typeof callable !== 'undefined') {
      // Simplest case: handler is passed, remove that listener ONLY.
      if (!Object.keys(storeElementEvent).length) {
        return
      }

      removeHandler(element, events, typeEvent, callable, isDelegated ? handler : null)
      return
    }

    if (isNamespace) {
      for (const elementEvent of Object.keys(events)) {
        removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1))
      }
    }

    for (const keyHandlers of Object.keys(storeElementEvent)) {
      const handlerKey = keyHandlers.replace(stripUidRegex, '')

      if (!inNamespace || originalTypeEvent.includes(handlerKey)) {
        const event = storeElementEvent[keyHandlers]
        removeHandler(element, events, typeEvent, event.callable, event.delegationSelector)
      }
    }
  },

  trigger(element, event, args) {
    if (typeof event !== 'string' || !element) {
      return null
    }

    const $ = getjQuery()
    const typeEvent = getTypeEvent(event)
    const inNamespace = event !== typeEvent

    let jQueryEvent = null
    let bubbles = true
    let nativeDispatch = true
    let defaultPrevented = false

    if (inNamespace && $) {
      jQueryEvent = $.Event(event, args)

      $(element).trigger(jQueryEvent)
      bubbles = !jQueryEvent.isPropagationStopped()
      nativeDispatch = !jQueryEvent.isImmediatePropagationStopped()
      defaultPrevented = jQueryEvent.isDefaultPrevented()
    }

    let evt = new Event(event, { bubbles, cancelable: true })
    evt = hydrateObj(evt, args)

    if (defaultPrevented) {
      evt.preventDefault()
    }

    if (nativeDispatch) {
      element.dispatchEvent(evt)
    }

    if (evt.defaultPrevented && jQueryEvent) {
      jQueryEvent.preventDefault()
    }

    return evt
  }
}

function hydrateObj(obj, meta) {
  for (const [key, value] of Object.entries(meta || {})) {
    try {
      obj[key] = value
    } catch {
      Object.defineProperty(obj, key, {
        configurable: true,
        get() {
          return value
        }
      })
    }
  }

  return obj
}

export default EventHandler
<commit_msg>hydrateObj: use default param (#37483)<commit_after>/**
 * --------------------------------------------------------------------------
 * Bootstrap (v5.2.2): dom/event-handler.js
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
 * --------------------------------------------------------------------------
 */

import { getjQuery } from '../util/index.js'

/**
 * Constants
 */

const namespaceRegex = /[^.]*(?=\..*)\.|.*/
const stripNameRegex = /\..*/
const stripUidRegex = /::\d+$/
const eventRegistry = {} // Events storage
let uidEvent = 1
const customEvents = {
  mouseenter: 'mouseover',
  mouseleave: 'mouseout'
}

const nativeEvents = new Set([
  'click',
  'dblclick',
  'mouseup',
  'mousedown',
  'contextmenu',
  'mousewheel',
  'DOMMouseScroll',
  'mouseover',
  'mouseout',
  'mousemove',
  'selectstart',
  'selectend',
  'keydown',
  'keypress',
  'keyup',
  'orientationchange',
  'touchstart',
  'touchmove',
  'touchend',
  'touchcancel',
  'pointerdown',
  'pointermove',
  'pointerup',
  'pointerleave',
  'pointercancel',
  'gesturestart',
  'gesturechange',
  'gestureend',
  'focus',
  'blur',
  'change',
  'reset',
  'select',
  'submit',
  'focusin',
  'focusout',
  'load',
  'unload',
  'beforeunload',
  'resize',
  'move',
  'DOMContentLoaded',
  'readystatechange',
  'error',
  'abort',
  'scroll'
])

/**
 * Private methods
 */

function makeEventUid(element, uid) {
  return (uid && `${uid}::${uidEvent++}`) || element.uidEvent || uidEvent++
}

function getElementEvents(element) {
  const uid = makeEventUid(element)

  element.uidEvent = uid
  eventRegistry[uid] = eventRegistry[uid] || {}

  return eventRegistry[uid]
}

function bootstrapHandler(element, fn) {
  return function handler(event) {
    hydrateObj(event, { delegateTarget: element })

    if (handler.oneOff) {
      EventHandler.off(element, event.type, fn)
    }

    return fn.apply(element, [event])
  }
}

function bootstrapDelegationHandler(element, selector, fn) {
  return function handler(event) {
    const domElements = element.querySelectorAll(selector)

    for (let { target } = event; target && target !== this; target = target.parentNode) {
      for (const domElement of domElements) {
        if (domElement !== target) {
          continue
        }

        hydrateObj(event, { delegateTarget: target })

        if (handler.oneOff) {
          EventHandler.off(element, event.type, selector, fn)
        }

        return fn.apply(target, [event])
      }
    }
  }
}

function findHandler(events, callable, delegationSelector = null) {
  return Object.values(events)
    .find(event => event.callable === callable && event.delegationSelector === delegationSelector)
}

function normalizeParameters(originalTypeEvent, handler, delegationFunction) {
  const isDelegated = typeof handler === 'string'
  // todo: tooltip passes `false` instead of selector, so we need to check
  const callable = isDelegated ? delegationFunction : (handler || delegationFunction)
  let typeEvent = getTypeEvent(originalTypeEvent)

  if (!nativeEvents.has(typeEvent)) {
    typeEvent = originalTypeEvent
  }

  return [isDelegated, callable, typeEvent]
}

function addHandler(element, originalTypeEvent, handler, delegationFunction, oneOff) {
  if (typeof originalTypeEvent !== 'string' || !element) {
    return
  }

  let [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction)

  // in case of mouseenter or mouseleave wrap the handler within a function that checks for its DOM position
  // this prevents the handler from being dispatched the same way as mouseover or mouseout does
  if (originalTypeEvent in customEvents) {
    const wrapFunction = fn => {
      return function (event) {
        if (!event.relatedTarget || (event.relatedTarget !== event.delegateTarget && !event.delegateTarget.contains(event.relatedTarget))) {
          return fn.call(this, event)
        }
      }
    }

    callable = wrapFunction(callable)
  }

  const events = getElementEvents(element)
  const handlers = events[typeEvent] || (events[typeEvent] = {})
  const previousFunction = findHandler(handlers, callable, isDelegated ? handler : null)

  if (previousFunction) {
    previousFunction.oneOff = previousFunction.oneOff && oneOff

    return
  }

  const uid = makeEventUid(callable, originalTypeEvent.replace(namespaceRegex, ''))
  const fn = isDelegated ?
    bootstrapDelegationHandler(element, handler, callable) :
    bootstrapHandler(element, callable)

  fn.delegationSelector = isDelegated ? handler : null
  fn.callable = callable
  fn.oneOff = oneOff
  fn.uidEvent = uid
  handlers[uid] = fn

  element.addEventListener(typeEvent, fn, isDelegated)
}

function removeHandler(element, events, typeEvent, handler, delegationSelector) {
  const fn = findHandler(events[typeEvent], handler, delegationSelector)

  if (!fn) {
    return
  }

  element.removeEventListener(typeEvent, fn, Boolean(delegationSelector))
  delete events[typeEvent][fn.uidEvent]
}

function removeNamespacedHandlers(element, events, typeEvent, namespace) {
  const storeElementEvent = events[typeEvent] || {}

  for (const handlerKey of Object.keys(storeElementEvent)) {
    if (handlerKey.includes(namespace)) {
      const event = storeElementEvent[handlerKey]
      removeHandler(element, events, typeEvent, event.callable, event.delegationSelector)
    }
  }
}

function getTypeEvent(event) {
  // allow to get the native events from namespaced events ('click.bs.button' --> 'click')
  event = event.replace(stripNameRegex, '')
  return customEvents[event] || event
}

const EventHandler = {
  on(element, event, handler, delegationFunction) {
    addHandler(element, event, handler, delegationFunction, false)
  },

  one(element, event, handler, delegationFunction) {
    addHandler(element, event, handler, delegationFunction, true)
  },

  off(element, originalTypeEvent, handler, delegationFunction) {
    if (typeof originalTypeEvent !== 'string' || !element) {
      return
    }

    const [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction)
    const inNamespace = typeEvent !== originalTypeEvent
    const events = getElementEvents(element)
    const storeElementEvent = events[typeEvent] || {}
    const isNamespace = originalTypeEvent.startsWith('.')

    if (typeof callable !== 'undefined') {
      // Simplest case: handler is passed, remove that listener ONLY.
      if (!Object.keys(storeElementEvent).length) {
        return
      }

      removeHandler(element, events, typeEvent, callable, isDelegated ? handler : null)
      return
    }

    if (isNamespace) {
      for (const elementEvent of Object.keys(events)) {
        removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1))
      }
    }

    for (const keyHandlers of Object.keys(storeElementEvent)) {
      const handlerKey = keyHandlers.replace(stripUidRegex, '')

      if (!inNamespace || originalTypeEvent.includes(handlerKey)) {
        const event = storeElementEvent[keyHandlers]
        removeHandler(element, events, typeEvent, event.callable, event.delegationSelector)
      }
    }
  },

  trigger(element, event, args) {
    if (typeof event !== 'string' || !element) {
      return null
    }

    const $ = getjQuery()
    const typeEvent = getTypeEvent(event)
    const inNamespace = event !== typeEvent

    let jQueryEvent = null
    let bubbles = true
    let nativeDispatch = true
    let defaultPrevented = false

    if (inNamespace && $) {
      jQueryEvent = $.Event(event, args)

      $(element).trigger(jQueryEvent)
      bubbles = !jQueryEvent.isPropagationStopped()
      nativeDispatch = !jQueryEvent.isImmediatePropagationStopped()
      defaultPrevented = jQueryEvent.isDefaultPrevented()
    }

    let evt = new Event(event, { bubbles, cancelable: true })
    evt = hydrateObj(evt, args)

    if (defaultPrevented) {
      evt.preventDefault()
    }

    if (nativeDispatch) {
      element.dispatchEvent(evt)
    }

    if (evt.defaultPrevented && jQueryEvent) {
      jQueryEvent.preventDefault()
    }

    return evt
  }
}

function hydrateObj(obj, meta = {}) {
  for (const [key, value] of Object.entries(meta)) {
    try {
      obj[key] = value
    } catch {
      Object.defineProperty(obj, key, {
        configurable: true,
        get() {
          return value
        }
      })
    }
  }

  return obj
}

export default EventHandler
<|endoftext|>


<commit_before>/*
 * raygun4js
 * https://github.com/MindscapeHQ/raygun4js
 *
 * Copyright (c) 2013 MindscapeHQ
 * Licensed under the MIT license.
 */

(function (window, $, undefined) {
  // pull local copy of TraceKit to handle stack trace collection
  var _traceKit = TraceKit.noConflict(),
      _raygun = window.Raygun,
      _raygunApiKey,
      _debugMode = false,
      _allowInsecureSubmissions = false,
      _ignoreAjaxAbort = false,
      _enableOfflineSave = false,
      _ignore3rdPartyErrors = false,
      _customData = {},
      _tags = [],
      _user,
      _version,
      _filteredKeys,
      _beforeSendCallback,
      _raygunApiUrl = 'https://api.raygun.io',
      $document;

  if ($) {
    $document = $(document);
  }

  var Raygun =
  {
    noConflict: function () {
      window.Raygun = _raygun;
      return Raygun;
    },

    init: function(key, options, customdata) {
      _raygunApiKey = key;
      _traceKit.remoteFetching = false;
      _customData = customdata;

      if (options)
      {
        _allowInsecureSubmissions = options.allowInsecureSubmissions || false;
        _ignoreAjaxAbort = options.ignoreAjaxAbort || false;

        if (options.debugMode)
        {
          _debugMode = options.debugMode;
        }
        if(options.ignore3rdPartyErrors)
        {
          _ignore3rdPartyErrors = true;
        }
      }

      sendSavedErrors();

      return Raygun;
    },

    withCustomData: function (customdata) {
      _customData = customdata;
      return Raygun;
    },

    withTags: function (tags) {
      _tags = tags;
      return Raygun;
    },

    attach: function () {
      if (!isApiKeyConfigured()) {
        return Raygun;
      }
      _traceKit.report.subscribe(processUnhandledException);
      if ($document) {
        $document.ajaxError(processJQueryAjaxError);
      }
      return Raygun;
    },

    detach: function () {
      _traceKit.report.unsubscribe(processUnhandledException);
      if ($document) {
        $document.unbind('ajaxError', processJQueryAjaxError);
      }
      return Raygun;
    },

    send: function (ex, customData, tags) {
      try {
        processUnhandledException(_traceKit.computeStackTrace(ex), {
          customData: typeof _customData === 'function' ?
            merge(_customData(), customData) :
            merge(_customData, customData),
          tags: mergeArray(_tags, tags)
        });
      }
      catch (traceKitException) {
        if (ex !== traceKitException) {
          throw traceKitException;
        }
      }
      return Raygun;
    },

    setUser: function (user, isAnonymous, email, fullName, firstName, uuid) {
      _user = {
        'Identifier': user
      };
      if(isAnonymous) {
        _user['IsAnonymous'] = isAnonymous;
      }
      if(email) {
        _user['Email'] = email;
      }
      if(fullName) {
        _user['FullName'] = fullName;
      }
      if(firstName) {
        _user['FirstName'] = firstName;
      }
      if(uuid) {
        _user['UUID'] = uuid;
      }

      return Raygun;
    },

    setVersion: function (version) {
      _version = version;
      return Raygun;
    },

    saveIfOffline: function (enableOffline) {
      if (typeof enableOffline !== 'undefined' && typeof enableOffline === 'boolean') {
        _enableOfflineSave = enableOffline;
      }

      return Raygun;
    },

    filterSensitiveData: function (filteredKeys) {
      _filteredKeys = filteredKeys;
      return Raygun;
    },

    onBeforeSend: function (callback) {
      _beforeSendCallback = callback;

      return Raygun;
    }
  };

  /* internals */

  function truncateURL(url){
      // truncate after fourth /, or 24 characters, whichever is shorter
      // /api/1/diagrams/xyz/server becomes
      // /api/1/diagrams/...
      var truncated = url;
      var path = url.split('//')[1];

      if (path) {
        var queryStart = path.indexOf('?');
        var sanitizedPath = path.toString().substring(0, queryStart);
        var truncated_parts = sanitizedPath.split('/').slice(0, 4).join('/');
        var truncated_length = sanitizedPath.substring(0, 48);
        truncated = truncated_parts.length < truncated_length.length?
                        truncated_parts : truncated_length;
        if (truncated !== sanitizedPath) {
            truncated += '..';
        }
      }

      return truncated;
  }

  function processJQueryAjaxError(event, jqXHR, ajaxSettings, thrownError) {
    var message = 'AJAX Error: ' +
        (jqXHR.statusText || 'unknown') +' '+
        (ajaxSettings.type || 'unknown') + ' '+
        (truncateURL(ajaxSettings.url) || 'unknown');

    // ignore ajax abort if set in the options
    if (_ignoreAjaxAbort) {
      if (!jqXHR.getAllResponseHeaders()) {
         return;
       }
    }

    Raygun.send(thrownError || event.type, {
      status: jqXHR.status,
      statusText: jqXHR.statusText,
      type: ajaxSettings.type,
      url: ajaxSettings.url,
      ajaxErrorMessage: message,
      contentType: ajaxSettings.contentType,
      requestData: ajaxSettings.data && ajaxSettings.data.slice ? ajaxSettings.data.slice(0, 10240) : undefined,
      responseData: jqXHR.responseText && jqXHR.responseText.slice ? jqXHR.responseText.slice(0, 10240) : undefined });
  }

  function log(message, data) {
    if (window.console && window.console.log && _debugMode) {
      window.console.log(message);

      if (data) {
        window.console.log(data);
      }
    }
  }

  function isApiKeyConfigured() {
    if (_raygunApiKey && _raygunApiKey !== '') {
      return true;
    }
    log("Raygun API key has not been configured, make sure you call Raygun.init(yourApiKey)");
    return false;
  }

  function merge(o1, o2) {
    var a, o3 = {};
    for (a in o1) { o3[a] = o1[a]; }
    for (a in o2) { o3[a] = o2[a]; }
    return o3;
  }

  function mergeArray(t0, t1) {
    if (t1 != null) {
      return t0.concat(t1);
    }
    return t0;
  }

  function forEach(set, func) {
    for (var i = 0; i < set.length; i++) {
      func.call(null, i, set[i]);
    }
  }

  function isEmpty(o) {
    for (var p in o) {
      if (o.hasOwnProperty(p)) {
        return false;
      }
    }
    return true;
  }

  function getRandomInt() {
    return Math.floor(Math.random() * 9007199254740993);
  }

  function getViewPort() {
    var e = document.documentElement,
    g = document.getElementsByTagName('body')[0],
    x = window.innerWidth || e.clientWidth || g.clientWidth,
    y = window.innerHeight || e.clientHeight || g.clientHeight;
    return { width: x, height: y };
  }

  function offlineSave (data) {
    var dateTime = new Date().toJSON();

    try {
      var key = 'raygunjs=' + dateTime + '=' + getRandomInt();

      if (typeof localStorage[key] === 'undefined') {
        localStorage[key] = data;
      }
    } catch (e) {
      log('Raygun4JS: LocalStorage full, cannot save exception');
    }
  }

  function localStorageAvailable(){
    try {
      return ('localStorage' in window) && window['localStorage'] !== null;
    } catch(e){
      return false;
    }
  }

  function sendSavedErrors() {
    if (localStorageAvailable() && localStorage.length > 0) {
        for (var key in localStorage) {
        if (key.substring(0, 9) === 'raygunjs=') {
          sendToRaygun(JSON.parse(localStorage[key]));

          localStorage.removeItem(key);
        }
      }
    }
  }

  function filterValue(key, value) {
      if (_filteredKeys) {
          if (Array.prototype.indexOf && _filteredKeys.indexOf === Array.prototype.indexOf) {
              if (_filteredKeys.indexOf(key) !== -1) {
                  return '[removed by filter]';
              }
          } else {
              for (var i = 0; i < _filteredKeys.length; i++) {
                  if (_filteredKeys[i] === key) {
                      return '[removed by filter]';
                  }
              }
          }
      }

      return value;
  }

  function filterObject(reference) {
      if (reference == null) {
          return reference;
      }

      if (Object.prototype.toString.call(reference) !== '[object Object]') {
          return reference;
      }

      for (var propertyName in reference) {
          var propertyValue = reference[propertyName];

          if (propertyValue == null) {
              continue;
          }

          if (Object.prototype.toString.call(propertyValue) === '[object Object]') {
              reference[propertyName] = filterObject(propertyValue);
          } else {
              reference[propertyName] = filterValue(propertyName, propertyValue);
          }
      }

      return reference;
  }

  function processUnhandledException(stackTrace, options) {
    var stack = [],
        qs = {};

    if (_ignore3rdPartyErrors && (!stackTrace.stack || !stackTrace.stack.length)) {
      return;
    }

    if (stackTrace.stack && stackTrace.stack.length) {
      forEach(stackTrace.stack, function (i, frame) {
        stack.push({
          'LineNumber': frame.line,
          'ColumnNumber': frame.column,
          'ClassName': 'line ' + frame.line + ', column ' + frame.column,
          'FileName': frame.url,
          'MethodName': frame.func || '[anonymous]'
        });
      });
    }

    if (window.location.search && window.location.search.length > 1) {
      forEach(window.location.search.substring(1).split('&'), function (i, segment) {
        var parts = segment.split('=');
        if (parts && parts.length === 2) {
          var key = decodeURIComponent(parts[0]);
          var value = filterValue(key, parts[1]);

          qs[key] = value;
        }
      });
    }

    if (options === undefined) {
      options = {};
    }

    if (isEmpty(options.customData)) {
      if (typeof _customData === 'function') {
        options.customData = _customData();
      } else {
        options.customData = _customData;
      }
    }

    if (isEmpty(options.tags)) {
      if (typeof _tags === 'function') {
        options.tags = _tags();
      } else {
        options.tags = _tags;
      }
    }

    var screen = window.screen || { width: getViewPort().width, height: getViewPort().height, colorDepth: 8 };
    var custom_message = options.customData && options.customData.ajaxErrorMessage;
    var finalCustomData = filterObject(options.customData);

    try {
      JSON.stringify(finalCustomData);
    } catch (e) {
      var msg = 'Cannot add custom data; may contain circular reference';
      finalCustomData = { error: msg };
      log('Raygun4JS: ' + msg);
    }

    var payload = {
      'OccurredOn': new Date(),
      'Details': {
        'Error': {
          'ClassName': stackTrace.name,
          'Message': custom_message || stackTrace.message || options.status || 'Script error',
          'StackTrace': stack
        },
        'Environment': {
          'UtcOffset': new Date().getTimezoneOffset() / -60.0,
          'User-Language': navigator.userLanguage,
          'Document-Mode': document.documentMode,
          'Browser-Width': getViewPort().width,
          'Browser-Height': getViewPort().height,
          'Screen-Width': screen.width,
          'Screen-Height': screen.height,
          'Color-Depth': screen.colorDepth,
          'Browser': navigator.appCodeName,
          'Browser-Name': navigator.appName,
          'Browser-Version': navigator.appVersion,
          'Platform': navigator.platform
        },
        'Client': {
          'Name': 'raygun-js',
          'Version': '1.12.0'
        },
        'UserCustomData': finalCustomData,
        'Tags': options.tags,
        'Request': {
          'Url': [location.protocol, '//', location.host, location.pathname].join(''),
          'QueryString': qs,
          'Headers': {
            'User-Agent': navigator.userAgent,
            'Referer': document.referrer,
            'Host': document.domain
          }
        },
        'Version': _version || 'Not supplied'
      }
    };

    if (_user) {
      payload.Details.User = _user;
    }

    if (typeof _beforeSendCallback === 'function') {
      var mutatedPayload = _beforeSendCallback(payload);

      if (mutatedPayload) {
        sendToRaygun(mutatedPayload);
      }
    } else {
      sendToRaygun(payload);
    }
  }

  function sendToRaygun(data) {
    if (!isApiKeyConfigured()) {
      return;
    }

    log('Sending exception data to Raygun:', data);
    var url = _raygunApiUrl + '/entries?apikey=' + encodeURIComponent(_raygunApiKey);
    makePostCorsRequest(url, JSON.stringify(data));
  }

  // Create the XHR object.
  function createCORSRequest(method, url) {
    var xhr;

    xhr = new window.XMLHttpRequest();
    if ("withCredentials" in xhr) {
      // XHR for Chrome/Firefox/Opera/Safari.
      xhr.open(method, url, true);

    } else if (window.XDomainRequest) {
      // XDomainRequest for IE.
      if (_allowInsecureSubmissions) {
        // remove 'https:' and use relative protocol
        // this allows IE8 to post messages when running
        // on http
        url = url.slice(6);
      }

      xhr = new window.XDomainRequest();
      xhr.open(method, url);
    }

    xhr.timeout = 10000;

    return xhr;
  }

  // Make the actual CORS request.
  function makePostCorsRequest(url, data) {
    var xhr = createCORSRequest('POST', url, data);

    if ('withCredentials' in xhr) {

      xhr.onreadystatechange = function() {
        if (xhr.readyState !== 4) {
          return;
        }

        if (xhr.status === 202) {
          sendSavedErrors();
        } else if (_enableOfflineSave && xhr.status !== 403 && xhr.status !== 400) {
          offlineSave(data);
        }
      };

      xhr.onload = function () {
        log('logged error to Raygun');
      };

    } else if (window.XDomainRequest) {
      xhr.ontimeout = function () {
        if (_enableOfflineSave) {
          log('Raygun: saved error locally');
          offlineSave(data);
        }
      };

      xhr.onload = function () {
        log('logged error to Raygun');
        sendSavedErrors();
      };
    }

    xhr.onerror = function () {
      log('failed to log error to Raygun');
    };

    if (!xhr) {
      log('CORS not supported');
      return;
    }

    xhr.send(data);
  }

  window.Raygun = Raygun;
})(window, window.jQuery);

<commit_msg>Cancel third-party errors if msg starts with Script Error and line is 0<commit_after>/*
 * raygun4js
 * https://github.com/MindscapeHQ/raygun4js
 *
 * Copyright (c) 2013 MindscapeHQ
 * Licensed under the MIT license.
 */

(function (window, $, undefined) {
  // pull local copy of TraceKit to handle stack trace collection
  var _traceKit = TraceKit.noConflict(),
      _raygun = window.Raygun,
      _raygunApiKey,
      _debugMode = false,
      _allowInsecureSubmissions = false,
      _ignoreAjaxAbort = false,
      _enableOfflineSave = false,
      _ignore3rdPartyErrors = false,
      _customData = {},
      _tags = [],
      _user,
      _version,
      _filteredKeys,
      _beforeSendCallback,
      _raygunApiUrl = 'https://api.raygun.io',
      $document;

  if ($) {
    $document = $(document);
  }

  var Raygun =
  {
    noConflict: function () {
      window.Raygun = _raygun;
      return Raygun;
    },

    init: function(key, options, customdata) {
      _raygunApiKey = key;
      _traceKit.remoteFetching = false;
      _customData = customdata;

      if (options)
      {
        _allowInsecureSubmissions = options.allowInsecureSubmissions || false;
        _ignoreAjaxAbort = options.ignoreAjaxAbort || false;

        if (options.debugMode)
        {
          _debugMode = options.debugMode;
        }
        if(options.ignore3rdPartyErrors)
        {
          _ignore3rdPartyErrors = true;
        }
      }

      sendSavedErrors();

      return Raygun;
    },

    withCustomData: function (customdata) {
      _customData = customdata;
      return Raygun;
    },

    withTags: function (tags) {
      _tags = tags;
      return Raygun;
    },

    attach: function () {
      if (!isApiKeyConfigured()) {
        return Raygun;
      }
      _traceKit.report.subscribe(processUnhandledException);
      if ($document) {
        $document.ajaxError(processJQueryAjaxError);
      }
      return Raygun;
    },

    detach: function () {
      _traceKit.report.unsubscribe(processUnhandledException);
      if ($document) {
        $document.unbind('ajaxError', processJQueryAjaxError);
      }
      return Raygun;
    },

    send: function (ex, customData, tags) {
      try {
        processUnhandledException(_traceKit.computeStackTrace(ex), {
          customData: typeof _customData === 'function' ?
            merge(_customData(), customData) :
            merge(_customData, customData),
          tags: mergeArray(_tags, tags)
        });
      }
      catch (traceKitException) {
        if (ex !== traceKitException) {
          throw traceKitException;
        }
      }
      return Raygun;
    },

    setUser: function (user, isAnonymous, email, fullName, firstName, uuid) {
      _user = {
        'Identifier': user
      };
      if(isAnonymous) {
        _user['IsAnonymous'] = isAnonymous;
      }
      if(email) {
        _user['Email'] = email;
      }
      if(fullName) {
        _user['FullName'] = fullName;
      }
      if(firstName) {
        _user['FirstName'] = firstName;
      }
      if(uuid) {
        _user['UUID'] = uuid;
      }

      return Raygun;
    },

    setVersion: function (version) {
      _version = version;
      return Raygun;
    },

    saveIfOffline: function (enableOffline) {
      if (typeof enableOffline !== 'undefined' && typeof enableOffline === 'boolean') {
        _enableOfflineSave = enableOffline;
      }

      return Raygun;
    },

    filterSensitiveData: function (filteredKeys) {
      _filteredKeys = filteredKeys;
      return Raygun;
    },

    onBeforeSend: function (callback) {
      _beforeSendCallback = callback;

      return Raygun;
    }
  };

  /* internals */

  function truncateURL(url){
      // truncate after fourth /, or 24 characters, whichever is shorter
      // /api/1/diagrams/xyz/server becomes
      // /api/1/diagrams/...
      var truncated = url;
      var path = url.split('//')[1];

      if (path) {
        var queryStart = path.indexOf('?');
        var sanitizedPath = path.toString().substring(0, queryStart);
        var truncated_parts = sanitizedPath.split('/').slice(0, 4).join('/');
        var truncated_length = sanitizedPath.substring(0, 48);
        truncated = truncated_parts.length < truncated_length.length?
                        truncated_parts : truncated_length;
        if (truncated !== sanitizedPath) {
            truncated += '..';
        }
      }

      return truncated;
  }

  function processJQueryAjaxError(event, jqXHR, ajaxSettings, thrownError) {
    var message = 'AJAX Error: ' +
        (jqXHR.statusText || 'unknown') +' '+
        (ajaxSettings.type || 'unknown') + ' '+
        (truncateURL(ajaxSettings.url) || 'unknown');

    // ignore ajax abort if set in the options
    if (_ignoreAjaxAbort) {
      if (!jqXHR.getAllResponseHeaders()) {
         return;
       }
    }

    Raygun.send(thrownError || event.type, {
      status: jqXHR.status,
      statusText: jqXHR.statusText,
      type: ajaxSettings.type,
      url: ajaxSettings.url,
      ajaxErrorMessage: message,
      contentType: ajaxSettings.contentType,
      requestData: ajaxSettings.data && ajaxSettings.data.slice ? ajaxSettings.data.slice(0, 10240) : undefined,
      responseData: jqXHR.responseText && jqXHR.responseText.slice ? jqXHR.responseText.slice(0, 10240) : undefined });
  }

  function log(message, data) {
    if (window.console && window.console.log && _debugMode) {
      window.console.log(message);

      if (data) {
        window.console.log(data);
      }
    }
  }

  function isApiKeyConfigured() {
    if (_raygunApiKey && _raygunApiKey !== '') {
      return true;
    }
    log("Raygun API key has not been configured, make sure you call Raygun.init(yourApiKey)");
    return false;
  }

  function merge(o1, o2) {
    var a, o3 = {};
    for (a in o1) { o3[a] = o1[a]; }
    for (a in o2) { o3[a] = o2[a]; }
    return o3;
  }

  function mergeArray(t0, t1) {
    if (t1 != null) {
      return t0.concat(t1);
    }
    return t0;
  }

  function forEach(set, func) {
    for (var i = 0; i < set.length; i++) {
      func.call(null, i, set[i]);
    }
  }

  function isEmpty(o) {
    for (var p in o) {
      if (o.hasOwnProperty(p)) {
        return false;
      }
    }
    return true;
  }

  function getRandomInt() {
    return Math.floor(Math.random() * 9007199254740993);
  }

  function getViewPort() {
    var e = document.documentElement,
    g = document.getElementsByTagName('body')[0],
    x = window.innerWidth || e.clientWidth || g.clientWidth,
    y = window.innerHeight || e.clientHeight || g.clientHeight;
    return { width: x, height: y };
  }

  function offlineSave (data) {
    var dateTime = new Date().toJSON();

    try {
      var key = 'raygunjs=' + dateTime + '=' + getRandomInt();

      if (typeof localStorage[key] === 'undefined') {
        localStorage[key] = data;
      }
    } catch (e) {
      log('Raygun4JS: LocalStorage full, cannot save exception');
    }
  }

  function localStorageAvailable(){
    try {
      return ('localStorage' in window) && window['localStorage'] !== null;
    } catch(e){
      return false;
    }
  }

  function sendSavedErrors() {
    if (localStorageAvailable() && localStorage.length > 0) {
        for (var key in localStorage) {
        if (key.substring(0, 9) === 'raygunjs=') {
          sendToRaygun(JSON.parse(localStorage[key]));

          localStorage.removeItem(key);
        }
      }
    }
  }

  function filterValue(key, value) {
      if (_filteredKeys) {
          if (Array.prototype.indexOf && _filteredKeys.indexOf === Array.prototype.indexOf) {
              if (_filteredKeys.indexOf(key) !== -1) {
                  return '[removed by filter]';
              }
          } else {
              for (var i = 0; i < _filteredKeys.length; i++) {
                  if (_filteredKeys[i] === key) {
                      return '[removed by filter]';
                  }
              }
          }
      }

      return value;
  }

  function filterObject(reference) {
      if (reference == null) {
          return reference;
      }

      if (Object.prototype.toString.call(reference) !== '[object Object]') {
          return reference;
      }

      for (var propertyName in reference) {
          var propertyValue = reference[propertyName];

          if (propertyValue == null) {
              continue;
          }

          if (Object.prototype.toString.call(propertyValue) === '[object Object]') {
              reference[propertyName] = filterObject(propertyValue);
          } else {
              reference[propertyName] = filterValue(propertyName, propertyValue);
          }
      }

      return reference;
  }

  function processUnhandledException(stackTrace, options) {
    var stack = [],
        qs = {};

    if (_ignore3rdPartyErrors) {
      var cancelMsg = 'Third-party script error, cancelling send';
      if (!stackTrace.stack || !stackTrace.stack.length) {
        log('Raygun4JS: ' + cancelMsg);
        return;
      }

      var scriptError = 'Script error';
      var msg = stackTrace.message || options.status || scriptError;
      if (msg.substring(0, scriptError.length) === scriptError &&
        stackTrace.stack[0].line === 0 || stackTrace.stack[0].line === null) {
        log('Raygun4JS: ' + cancelMsg);
        return;
      }
    }

    if (stackTrace.stack && stackTrace.stack.length) {
      forEach(stackTrace.stack, function (i, frame) {
        stack.push({
          'LineNumber': frame.line,
          'ColumnNumber': frame.column,
          'ClassName': 'line ' + frame.line + ', column ' + frame.column,
          'FileName': frame.url,
          'MethodName': frame.func || '[anonymous]'
        });
      });
    }

    if (window.location.search && window.location.search.length > 1) {
      forEach(window.location.search.substring(1).split('&'), function (i, segment) {
        var parts = segment.split('=');
        if (parts && parts.length === 2) {
          var key = decodeURIComponent(parts[0]);
          var value = filterValue(key, parts[1]);

          qs[key] = value;
        }
      });
    }

    if (options === undefined) {
      options = {};
    }

    if (isEmpty(options.customData)) {
      if (typeof _customData === 'function') {
        options.customData = _customData();
      } else {
        options.customData = _customData;
      }
    }

    if (isEmpty(options.tags)) {
      if (typeof _tags === 'function') {
        options.tags = _tags();
      } else {
        options.tags = _tags;
      }
    }

    var screen = window.screen || { width: getViewPort().width, height: getViewPort().height, colorDepth: 8 };
    var custom_message = options.customData && options.customData.ajaxErrorMessage;
    var finalCustomData = filterObject(options.customData);

    try {
      JSON.stringify(finalCustomData);
    } catch (e) {
      var msg = 'Cannot add custom data; may contain circular reference';
      finalCustomData = { error: msg };
      log('Raygun4JS: ' + msg);
    }

    var payload = {
      'OccurredOn': new Date(),
      'Details': {
        'Error': {
          'ClassName': stackTrace.name,
          'Message': custom_message || stackTrace.message || options.status || 'Script error',
          'StackTrace': stack
        },
        'Environment': {
          'UtcOffset': new Date().getTimezoneOffset() / -60.0,
          'User-Language': navigator.userLanguage,
          'Document-Mode': document.documentMode,
          'Browser-Width': getViewPort().width,
          'Browser-Height': getViewPort().height,
          'Screen-Width': screen.width,
          'Screen-Height': screen.height,
          'Color-Depth': screen.colorDepth,
          'Browser': navigator.appCodeName,
          'Browser-Name': navigator.appName,
          'Browser-Version': navigator.appVersion,
          'Platform': navigator.platform
        },
        'Client': {
          'Name': 'raygun-js',
          'Version': '1.12.0'
        },
        'UserCustomData': finalCustomData,
        'Tags': options.tags,
        'Request': {
          'Url': [location.protocol, '//', location.host, location.pathname].join(''),
          'QueryString': qs,
          'Headers': {
            'User-Agent': navigator.userAgent,
            'Referer': document.referrer,
            'Host': document.domain
          }
        },
        'Version': _version || 'Not supplied'
      }
    };

    if (_user) {
      payload.Details.User = _user;
    }

    if (typeof _beforeSendCallback === 'function') {
      var mutatedPayload = _beforeSendCallback(payload);

      if (mutatedPayload) {
        sendToRaygun(mutatedPayload);
      }
    } else {
      sendToRaygun(payload);
    }
  }

  function sendToRaygun(data) {
    if (!isApiKeyConfigured()) {
      return;
    }

    log('Sending exception data to Raygun:', data);
    var url = _raygunApiUrl + '/entries?apikey=' + encodeURIComponent(_raygunApiKey);
    makePostCorsRequest(url, JSON.stringify(data));
  }

  // Create the XHR object.
  function createCORSRequest(method, url) {
    var xhr;

    xhr = new window.XMLHttpRequest();
    if ("withCredentials" in xhr) {
      // XHR for Chrome/Firefox/Opera/Safari.
      xhr.open(method, url, true);

    } else if (window.XDomainRequest) {
      // XDomainRequest for IE.
      if (_allowInsecureSubmissions) {
        // remove 'https:' and use relative protocol
        // this allows IE8 to post messages when running
        // on http
        url = url.slice(6);
      }

      xhr = new window.XDomainRequest();
      xhr.open(method, url);
    }

    xhr.timeout = 10000;

    return xhr;
  }

  // Make the actual CORS request.
  function makePostCorsRequest(url, data) {
    var xhr = createCORSRequest('POST', url, data);

    if ('withCredentials' in xhr) {

      xhr.onreadystatechange = function() {
        if (xhr.readyState !== 4) {
          return;
        }

        if (xhr.status === 202) {
          sendSavedErrors();
        } else if (_enableOfflineSave && xhr.status !== 403 && xhr.status !== 400) {
          offlineSave(data);
        }
      };

      xhr.onload = function () {
        log('logged error to Raygun');
      };

    } else if (window.XDomainRequest) {
      xhr.ontimeout = function () {
        if (_enableOfflineSave) {
          log('Raygun: saved error locally');
          offlineSave(data);
        }
      };

      xhr.onload = function () {
        log('logged error to Raygun');
        sendSavedErrors();
      };
    }

    xhr.onerror = function () {
      log('failed to log error to Raygun');
    };

    if (!xhr) {
      log('CORS not supported');
      return;
    }

    xhr.send(data);
  }

  window.Raygun = Raygun;
})(window, window.jQuery);

<|endoftext|>


<commit_before>/**
 * Created by user on 01-12-2016.
 */
var technicalCommitteeData={
    "tech":[
        {
            "dept":"maths",
            "content":[
                {"name":"Prof(Dr.) D C Vakaskar",
                "des":"Professor Head, MSU"
                },
                {"name":"Prof.R.K.George ",
                "des":"Professor,Dept.of Mathematics, IIST Trivandrum"
                },
                {"name":"Prof. N. Sukavanam",
                "des":"Professor, Dept of Mathematics, IIT Roorkee"
                }
            ]
        },
        {
            "dept":"it",
            "content":[
                {"name":"Prof(Dr.) D C Vakaskar",
                    "des":"Professor Head, MSU"
                },
                {"name":"Prof.R.K.George ",
                    "des":"Professor,Dept.of Mathematics, IIST Trivandrum"
                },
                {"name":"Prof. N. Sukavanam",
                    "des":"Professor, Dept of Mathematics, IIT Roorkee"
                }
            ]
        }
    ]

};
<commit_msg>Maths & EE Data<commit_after>/**
 * Created by user on 01-12-2016.
 */
var technicalCommitteeData={
    "tech":[
        {
            "dept":"MATHS/HS",
            "content":[
                {"name":"Prof(Dr.) D C Vakaskar",
                "des":"Professor Head, MSU"
                },
                {"name":"Prof.R.K.George ",
                "des":"Professor,Dept.of Mathematics, IIST Trivandrum"
                },
                {"name":"Prof. N. Sukavanam",
                "des":"Professor, Dept of Mathematics, IIT Roorkee"
                },
                {
                    "name":"Dr G M Deheri Rader ",
                    "des":"Dept. of Mathematics, SPU, VV Nagar"
                },
                {
                    "name":"Dr V D Pathak Director ",
                    "des":"Academy of creativity and Excellence, Vadodara"
                },
                {
                    "name":"Dr V.N.Mishra ",
                    "des":"Assi. Prof SVNIT, SURAT"
                },
                {
                    "name":"Dr. R. D. Mehta Professor ",
                    "des":"Dept. of Mathematics, SPU"
                },
                {
                    "name":"Dr A H Hasmani ",
                    "des":"Professor & Head, SPU"
                },
                {
                    "name":"Dr A K Shukla ",
                    "des":"Associate Professor, SVNIT, SURAT"
                },
                {
                    "name":"Prof K A Thaker ",
                    "des":"Associate Professor, GU"
                },
                {
                    "name":"Dr. Sulabha Natraj ",
                    "des":"Principal, Waymade College of Education"
                },
                {
                    "name":"Dr P K Priyan  ",
                    "des":"Professor, Institute of Mgt , SPU"
                },
                {
                    "name":"Dr K S Prasad ",
                    "des":"Asso Prof, Institute of Mgt , SPU"
                },
                {
                    "name":"Dr. Shailesh N Hadli ",
                    "des":"Principal; R N P I School of Law & Justice, VVN"
                }

            ]
        },
        {
            "dept":"EE",
            "content":[
                {"name":"Dr. S. K. Joshi",
                    "des":"MSU, Vadodara"
                },
                {"name":"Dr. H. R. Jariwala ",
                    "des":"SVNIT,SURAT"
                },
                {"name":"Dr. Sanjay R. Joshi",
                    "des":"GEC, Valsad"
                },
                {
                    "name":"Dr. Vivek Pandya ",
                    "des":"School of Technology, PDPU, Gandhinagar"
                },
                {
                    "name":"Dr. P. N. Tekwani  ",
                    "des":"Institute of Technology, Nirma University"
                },
                {
                    "name":"Dr. B. R. Parekh  ",
                    "des":"B.V.M. Engineering College"
                },
                {
                    "name":"Dr. N. G. Mishra  ",
                    "des":"B.V.M. Engineering College"
                },
                {
                    "name":"Dr. Akshay A. Pandya  ",
                    "des":"B.V.M. Engineering College"
                },
                {
                    "name":"Dr. Gopal Gajjar" ,
                    "des":"PowerAnser Lab,IIT, Bombay"
                },
                {
                    "name":"Dr. Yogesh Bichpuriya  ",
                    "des":"Tata Consultancy Services,Pune"
                },
                {
                    "name":"Dr. Anandita Chaudhary  ",
                    "des":"SVNIT, Surat"
                },
                {
                    "name":"Dr. A. K. Panchal   ",
                    "des":"SVNIT, Surat"
                },
                {
                    "name":"Dr. Hiren Patel  ",
                    "des":"SCET, Surat"
                },
                {
                    "name":"Dr. Ketan P. Badgujar",
                    "des":"SSGEC, Bhavnagar"
                },
                {
                    "name":"Dr. Bhavik N. Suthar  ",
                    "des":"GEC, Modasa"
                },
                {
                    "name":"Dr. Mahipalsinh Chudasama  ",
                    "des":"LDCE, Ahmedabad"
                },
                {
                    "name":"Dr. Axay J. Mehta",
                    "des":"IITRAM, Ahmedabad"
                },
                {
                    "name":" Dr. Ritesh R. Patel",
                    "des":"GCET, V. V. Nagar"
                },
                {
                    "name":"Dr. Vijay H. Makwana",
                    "des":"GCET, V. V. Nagar"
                },
                {
                    "name":"Dr. Pragnesh H. Shah",
                    "des":"ADIT, V. V. Nagar"
                },
                {
                    "name":"Dr. Pragnesh Bhatt",
                    "des":"CSPIT, Charusat University, Changa"
                },
                {
                    "name":"Dr. Kartik S. Pandya",
                    "des":"CSPIT, Charusat University, Changa"
                }

            ]
        }
    ]

};
<|endoftext|>