<commit_before>var injected = injected || (function() {

    var user = prompt("Enter Your Username", "Harry Potter");
    var data, jsonArray, url;
    var lis = [],
        jsonlist = [];
    var i = 0;

    var Inspector = function() {
        this.highlight = this.highlight.bind(this);
        this.log = this.log.bind(this);
        this.codeOutput = this.codeOutput.bind(this);
        this.layout = this.layout.bind(this);
        this.handleResize = this.handleResize.bind(this);

        this.$target = document.body;
        this.$cacheEl = document.body;
        this.$cacheElMain = document.body;

        this.serializer = new XMLSerializer();
        this.forbidden = [this.$cacheEl, document.body, document.documentElement];
    };

    Inspector.prototype = {

        getNodes: function() {
            var path = chrome.extension.getURL("static/template.html");

            var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                    this.template = xmlhttp.responseText;
                    this.createNodes();
                    this.registerEvents();
                }
            }.bind(this);

            xmlhttp.open("GET", path, true);
            xmlhttp.send();
        },

        createNodes: function() {

            this.$host = document.createElement('div');
            this.$host.className = 'tl-host';
            this.$host.style.cssText = 'all: initial;';

            var shadow = this.$host.createShadowRoot();
            document.body.appendChild(this.$host);

            var templateMarkup = document.createElement("div");
            templateMarkup.innerHTML = this.template;
            shadow.innerHTML = templateMarkup.querySelector('template').innerHTML;

            this.$wrap = shadow.querySelector('.tl-wrap');
            this.$code = shadow.querySelector('.tl-code');

            this.$canvas = shadow.querySelector('#tl-canvas');
            this.c = this.$canvas.getContext('2d');
            this.width = this.$canvas.width = window.innerWidth;
            this.height = this.$canvas.height = window.innerHeight;

            this.highlight();
        },

        registerEvents: function() {
            document.addEventListener('mousemove', this.log);
            document.addEventListener('scroll', this.layout);

            window.addEventListener('resize', function() {
                this.handleResize();
                this.layout();
            }.bind(this));
        },

        log: function(e) {
            this.$target = e.target;

            // check if element cached
            if (this.forbidden.indexOf(this.$target) !== -1) return;

            this.stringified = this.serializer.serializeToString(this.$target);

            data = this.$target;
            this.codeOutput();

            this.$cacheEl = this.$target;
            this.layout();

        },

        codeOutput: function() {
            if (this.$cacheElMain === this.$target) return;
            this.$cacheElMain = this.$target;
            var fullCode = this.stringified
                .slice(0, this.stringified.indexOf('>') + 1)
                .replace(/ xmlns="[^"]*"/, '');

            document.addEventListener('click', handle);

            function handle() {
                handler1();
                handler2();
            }

            function handler1(e) {
                //if($(this).)
                if (event.handled !== true) {
                    lis.push(data);
                    //document.getElementById('absSlide').cssText="right:0";
                    if (i == 0) {
                        url = lis[0].baseURI;
                    }
                    jsonlist.push(lis[i].innerText);
                    i++;
                    //alert('Exec!');
                    jsonArray = JSON.parse(JSON.stringify(jsonlist));
                    // console.log(Date());
                    // console.log(url);
                    // console.log(user);
                    // console.log(jsonArray);

                    event.handled = true;

                }
                return false;
            }

            function handler2(e) {
                console.log(url);
                $.ajax({
                    type: 'POST',
                    url: 'https://192.168.43.106:5000/api/post/', //+ JSON.stringify({ "userid": user, "url": url, "data": jsonArray }),
                    data: JSON.stringify({ "userid": user, "url": url, "data": jsonArray }), // or JSON.stringify ({name: 'jonas'}),
                    contentType: "application/json",
                    dataType: 'json'
                });
            }

            this.$code.innerText = fullCode; // set full element code
            this.highlight(); // highlight element

        },

        // redraw overlay
        layout: function() {
            var box, computedStyle, rect;
            var c = this.c;

            rect = this.$target.getBoundingClientRect();
            computedStyle = window.getComputedStyle(this.$target);
            box = {
                width: rect.width,
                height: rect.height,
                top: rect.top,
                left: rect.left,
                margin: {
                    top: computedStyle.marginTop,
                    right: computedStyle.marginRight,
                    bottom: computedStyle.marginBottom,
                    left: computedStyle.marginLeft
                },
                padding: {
                    top: computedStyle.paddingTop,
                    right: computedStyle.paddingRight,
                    bottom: computedStyle.paddingBottom,
                    left: computedStyle.paddingLeft
                }
            };

            // pluck negatives
            ['margin', 'padding'].forEach(function(property) {
                for (var el in box[property]) {
                    var val = parseInt(box[property][el], 10);
                    box[property][el] = Math.max(0, val);
                }
            });

            c.clearRect(0, 0, this.width, this.height);

            box.left = Math.floor(box.left) + 1.5;
            box.width = Math.floor(box.width) - 1;

            var x, y, width, height;

            //margin
            // x = box.left + box.margin.left;
            // y = box.top + box.margin.top;
            // width = box.width + box.margin.left + box.margin.right + 50;
            // height = box.height + box.margin.top + box.margin.bottom + 50;

            // c.fillStyle = 'rgba(255, 220, 232, 0.5)';
            // c.fillRect(x, y, width, height);

            // padding
            x = box.left + 2;
            y = box.top + 3;
            width = box.width + 3;
            height = box.height + 3;

            c.fillStyle = 'rgba(0, 77, 64, 0.8)';
            //c.clearRect(x, y, width, height);
            c.fillRect(x, y, width, height);

            // content
            x = box.left;
            y = box.top + 2;
            width = box.width + 2;
            height = box.height + 2;

            c.fillStyle = 'rgba(0, 150, 136, 0.4)';
            c.clearRect(x, y, width, height);
            c.fillRect(x, y, width, height);

        },

        handleResize: function() {
            this.width = this.$canvas.width = window.innerWidth;
            this.height = this.$canvas.height = window.innerHeight;
        },

        // code highlighting
        highlight: function() {
            Prism.highlightElement(this.$code);

        },

        activate: function() {
            this.getNodes();

        },

        deactivate: function() {

            this.$wrap.classList.add('-out');
            document.removeEventListener('mousemove', this.log);
            setTimeout(function() {
                document.body.removeChild(this.$host);
            }.bind(this), 600);
        }

    };

    var hi = new Inspector();

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        if (request.action === 'activate') {
            return hi.activate();
        } else {
            lis = [];
            jsonlist = [];
            return hi.deactivate();
        }
    });

    return true;
})();
<commit_msg>Fixes<commit_after>var injected = injected || (function() {

    var user = prompt("Enter Your Username", "Harry Potter");
    var data, jsonArray, url;
    var lis = [],
        jsonlist = [];
    var i = 0;

    var Inspector = function() {
        this.highlight = this.highlight.bind(this);
        this.log = this.log.bind(this);
        this.codeOutput = this.codeOutput.bind(this);
        this.layout = this.layout.bind(this);
        this.handleResize = this.handleResize.bind(this);

        this.$target = document.body;
        this.$cacheEl = document.body;
        this.$cacheElMain = document.body;

        this.serializer = new XMLSerializer();
        this.forbidden = [this.$cacheEl, document.body, document.documentElement];
    };

    Inspector.prototype = {

        getNodes: function() {
            var path = chrome.extension.getURL("static/template.html");

            var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                    this.template = xmlhttp.responseText;
                    this.createNodes();
                    this.registerEvents();
                }
            }.bind(this);

            xmlhttp.open("GET", path, true);
            xmlhttp.send();
        },

        createNodes: function() {

            this.$host = document.createElement('div');
            this.$host.className = 'tl-host';
            this.$host.style.cssText = 'all: initial;';

            var shadow = this.$host.createShadowRoot();
            document.body.appendChild(this.$host);

            var templateMarkup = document.createElement("div");
            templateMarkup.innerHTML = this.template;
            shadow.innerHTML = templateMarkup.querySelector('template').innerHTML;

            this.$wrap = shadow.querySelector('.tl-wrap');
            this.$code = shadow.querySelector('.tl-code');

            this.$canvas = shadow.querySelector('#tl-canvas');
            this.c = this.$canvas.getContext('2d');
            this.width = this.$canvas.width = window.innerWidth;
            this.height = this.$canvas.height = window.innerHeight;

            this.highlight();
        },

        registerEvents: function() {
            document.addEventListener('mousemove', this.log);
            document.addEventListener('scroll', this.layout);

            window.addEventListener('resize', function() {
                this.handleResize();
                this.layout();
            }.bind(this));
        },

        log: function(e) {
            this.$target = e.target;

            // check if element cached
            if (this.forbidden.indexOf(this.$target) !== -1) return;

            this.stringified = this.serializer.serializeToString(this.$target);

            data = this.$target;
            this.codeOutput();

            this.$cacheEl = this.$target;
            this.layout();

        },

        codeOutput: function() {
            if (this.$cacheElMain === this.$target) return;
            this.$cacheElMain = this.$target;
            var fullCode = this.stringified
                .slice(0, this.stringified.indexOf('>') + 1)
                .replace(/ xmlns="[^"]*"/, '');

            document.addEventListener('click', handle);

            function handle() {
                handler1();
            }

            function handler1(e) {
                //if($(this).)
                if (event.handled !== true) {
                    lis.push(data);
                    //document.getElementById('absSlide').cssText="right:0";
                    if (i == 0) {
                        url = lis[0].baseURI;
                    }
                    jsonlist.push(lis[i].innerText);
                    i++;
                    //alert('Exec!');
                    jsonArray = JSON.parse(JSON.stringify(jsonlist));
                    // console.log(Date());
                    // console.log(url);
                    // console.log(user);
                    // console.log(jsonArray);

                    event.handled = true;

                }
                return false;
            }

            function handler2(e) {
                console.log(url);
                $.ajax({
                    type: 'POST',
                    url: 'https://192.168.43.106:5000/api/post/', //+ JSON.stringify({ "userid": user, "url": url, "data": jsonArray }),
                    data: JSON.stringify({ "userid": user, "url": url, "data": jsonArray }), // or JSON.stringify ({name: 'jonas'}),
                    contentType: "application/json",
                    dataType: 'json'
                });
            }

            this.$code.innerText = fullCode; // set full element code
            this.highlight(); // highlight element

        },

        // redraw overlay
        layout: function() {
            var box, computedStyle, rect;
            var c = this.c;

            rect = this.$target.getBoundingClientRect();
            computedStyle = window.getComputedStyle(this.$target);
            box = {
                width: rect.width,
                height: rect.height,
                top: rect.top,
                left: rect.left,
                margin: {
                    top: computedStyle.marginTop,
                    right: computedStyle.marginRight,
                    bottom: computedStyle.marginBottom,
                    left: computedStyle.marginLeft
                },
                padding: {
                    top: computedStyle.paddingTop,
                    right: computedStyle.paddingRight,
                    bottom: computedStyle.paddingBottom,
                    left: computedStyle.paddingLeft
                }
            };

            // pluck negatives
            ['margin', 'padding'].forEach(function(property) {
                for (var el in box[property]) {
                    var val = parseInt(box[property][el], 10);
                    box[property][el] = Math.max(0, val);
                }
            });

            c.clearRect(0, 0, this.width, this.height);

            box.left = Math.floor(box.left) + 1.5;
            box.width = Math.floor(box.width) - 1;

            var x, y, width, height;

            //margin
            // x = box.left + box.margin.left;
            // y = box.top + box.margin.top;
            // width = box.width + box.margin.left + box.margin.right + 50;
            // height = box.height + box.margin.top + box.margin.bottom + 50;

            // c.fillStyle = 'rgba(255, 220, 232, 0.5)';
            // c.fillRect(x, y, width, height);

            // padding
            x = box.left + 2;
            y = box.top + 3;
            width = box.width + 3;
            height = box.height + 3;

            c.fillStyle = 'rgba(0, 77, 64, 0.8)';
            //c.clearRect(x, y, width, height);
            c.fillRect(x, y, width, height);

            // content
            x = box.left;
            y = box.top + 2;
            width = box.width + 2;
            height = box.height + 2;

            c.fillStyle = 'rgba(0, 150, 136, 0.4)';
            c.clearRect(x, y, width, height);
            c.fillRect(x, y, width, height);

        },

        handleResize: function() {
            this.width = this.$canvas.width = window.innerWidth;
            this.height = this.$canvas.height = window.innerHeight;
        },

        // code highlighting
        highlight: function() {
            Prism.highlightElement(this.$code);

        },

        activate: function() {
            this.getNodes();

        },

        deactivate: function() {

            this.$wrap.classList.add('-out');
            document.removeEventListener('mousemove', this.log);
            setTimeout(function() {
                document.body.removeChild(this.$host);
            }.bind(this), 600);
        }

    };

    var hi = new Inspector();

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        if (request.action === 'activate') {
            return hi.activate();
        } else {
            lis = [];
            jsonlist = [];
            return hi.deactivate();
        }
    });

    return true;
})();
<|endoftext|>


<commit_before>export default Base => class extends Base {
    static get displayName() {
        return 'core: fieldset';
    }

    render() {
        return {
            block: 'fieldset',
            content: [
                {
                    elem: 'label',
                    tag: 'label',
                    props: {
                        htmlFor: this.props.parentID,
                        key: 'label'
                    },
                    content: this.props.labelText
                },
                {
                    elem: 'control',
                    props: {
                        key: 'control'
                    },
                    content: this.props.children
                }
            ]
        };
    }
};
<commit_msg>:wrench: fieldset component: parentID and labelText props -> _parentID and _labelText<commit_after>export default Base => class extends Base {
    static get displayName() {
        return 'core: fieldset';
    }

    render() {
        return {
            block: 'fieldset',
            content: [
                {
                    elem: 'label',
                    tag: 'label',
                    props: {
                        htmlFor: this.props._parentID,
                        key: 'label'
                    },
                    content: this.props._labelText
                },
                {
                    elem: 'control',
                    props: {
                        key: 'control'
                    },
                    content: this.props.children
                }
            ]
        };
    }
};
<|endoftext|>


<commit_before>m.postgrest.init('http://localhost:3004', {});
<commit_msg>use api address<commit_after>m.postgrest.init('https://api.catarse.me/', {});
<|endoftext|>


<commit_before>dojo.provide("dijit.form.Select");

dojo.require("dijit.form._FormSelectWidget");
dojo.require("dijit._HasDropDown");
dojo.require("dijit.Menu");

dojo.requireLocalization("dijit.form", "validate");

dojo.declare("dijit.form._SelectMenu", dijit.Menu, {
	// summary:
	//		An internally-used menu for dropdown that allows us a vertical scrollbar
	buildRendering: function(){
		// summary:
		//		Stub in our own changes, so that our domNode is not a table
		//		otherwise, we won't respond correctly to heights/overflows
		this.inherited(arguments);
		var o = (this.menuTableNode = this.domNode);
		var n = (this.domNode = dojo.create("div", {style: {overflowX: "hidden", overflowY: "scroll"}}));
		if(o.parentNode){
			o.parentNode.replaceChild(n, o);
		}
		dojo.removeClass(o, "dijitMenuTable");
		n.className = o.className + " dijitSelectMenu";
		o.className = "dijitReset dijitMenuTable";
		dijit.setWaiRole(o,"listbox");
		dijit.setWaiRole(n,"presentation");
		n.appendChild(o);
	},
	resize: function(/*Object*/ mb){
		// summary:
		//		Overridden so that we are able to handle resizing our
		//		internal widget.  Note that this is not a "full" resize
		//		implementation - it only works correctly if you pass it a
		//		marginBox.
		//
		// mb: Object
		//		The margin box to set this dropdown to.
		if(mb){
			dojo.marginBox(this.domNode, mb);
			if("w" in mb){
				// We've explicitly set the wrapper
's width, so set
 width to match.
				// 100% is safer than a pixel value because there may be a scroll bar with
				// browser/OS specific width.
				this.menuTableNode.style.width = "100%";
			}
		}
	}
});

dojo.declare("dijit.form.Select", [dijit.form._FormSelectWidget, dijit._HasDropDown], {
	// summary:
	//		This is a "styleable" select box - it is basically a DropDownButton which
	//		can take a <select> as its input.

	baseClass: "dijitSelect",

	templateString: dojo.cache("dijit.form", "templates/Select.html"),

	// attributeMap: Object
	//		Add in our style to be applied to the focus node
	attributeMap: dojo.mixin(dojo.clone(dijit.form._FormSelectWidget.prototype.attributeMap),{style:"tableNode"}),

	// required: Boolean
	//		Can be true or false, default is false.
	required: false,

	// state: String
	//		Shows current state (ie, validation result) of input (Normal, Warning, or Error)
	state: "",

	//	tooltipPosition: String[]
	//		See description of dijit.Tooltip.defaultPosition for details on this parameter.
	tooltipPosition: [],

	// emptyLabel: string
	//		What to display in an "empty" dropdown
	emptyLabel: "",

	// _isLoaded: Boolean
	//		Whether or not we have been loaded
	_isLoaded: false,

	// _childrenLoaded: Boolean
	//		Whether or not our children have been loaded
	_childrenLoaded: false,

	_fillContent: function(){
		// summary:
		//		Set the value to be the first, or the selected index
		this.inherited(arguments);
		if(this.options.length && !this.value && this.srcNodeRef){
			var si = this.srcNodeRef.selectedIndex;
			this.value = this.options[si != -1 ? si : 0].value;
		}

		// Create the dropDown widget
		this.dropDown = new dijit.form._SelectMenu();
		dojo.addClass(this.dropDown.domNode, this.baseClass + "Menu");
	},

	_getMenuItemForOption: function(/*dijit.form.__SelectOption*/ option){
		// summary:
		//		For the given option, return the menu item that should be
		//		used to display it.  This can be overridden as needed
		if(!option.value){
			// We are a separator (no label set for it)
			return new dijit.MenuSeparator();
		}else{
			// Just a regular menu option
			var click = dojo.hitch(this, "_setValueAttr", option);
			var item = new dijit.MenuItem({
				option: option,
				label: option.label,
				onClick: click,
				disabled: option.disabled || false
			});
			dijit.setWaiRole(item.focusNode, "listitem");
			return item;
		}
	},

	_addOptionItem: function(/*dijit.form.__SelectOption*/ option){
		// summary:
		//		For the given option, add an option to our dropdown.
		//		If the option doesn't have a value, then a separator is added
		//		in that place.
		if(this.dropDown){
			this.dropDown.addChild(this._getMenuItemForOption(option));
		}
	},

	_getChildren: function(){
		if(!this.dropDown){
			return [];
		}
		return this.dropDown.getChildren();
	},

	_loadChildren: function(/*Boolean*/ loadMenuItems){
		// summary:
		//		Resets the menu and the length attribute of the button - and
		//		ensures that the label is appropriately set.
		//	loadMenuItems: Boolean
		//		actually loads the child menu items - we only do this when we are
		//		populating for showing the dropdown.

		if(loadMenuItems === true){
			// this.inherited destroys this.dropDown's child widgets (MenuItems).
			// Avoid this.dropDown (Menu widget) having a pointer to a destroyed widget (which will cause
			// issues later in _setSelected). (see #10296)
			if(this.dropDown){
				delete this.dropDown.focusedChild;
			}
			if(this.options.length){
				this.inherited(arguments);
			}else{
				// Drop down menu is blank but add one blank entry just so something appears on the screen
				// to let users know that they are no choices (mimicing native select behavior)
				dojo.forEach(this._getChildren(), function(child){ child.destroyRecursive(); });
				var item = new dijit.MenuItem({label: " "});
				this.dropDown.addChild(item);
			}
		}else{
			this._updateSelection();
		}

		var len = this.options.length;
		this._isLoaded = false;
		this._childrenLoaded = true;

		if(!this._loadingStore){
			// Don't call this if we are loading - since we will handle it later
			this._setValueAttr(this.value);
		}
	},

	_setValueAttr: function(value){
		this.inherited(arguments);
		dojo.attr(this.valueNode, "value", this.get("value"));
	},

	_setDisplay: function(/*String*/ newDisplay){
		// summary:
		//		sets the display for the given value (or values)
		this.containerNode.innerHTML = '' +
					(newDisplay || this.emptyLabel || " ") +
					'';
		dijit.setWaiState(this.focusNode, "valuetext", (newDisplay || this.emptyLabel || " ") );
	},

	validate: function(/*Boolean*/ isFocused){
		// summary:
		//		Called by oninit, onblur, and onkeypress.
		// description:
		//		Show missing or invalid messages if appropriate, and highlight textbox field.
		//		Used when a select is initially set to no value and the user is required to
		//		set the value.

		var isValid = this.isValid(isFocused);
		this.state = isValid ? "" : "Error";
		this._setStateClass();
		dijit.setWaiState(this.focusNode, "invalid", isValid ? "false" : "true");
		var message = isValid ? "" : this._missingMsg;
		if(this._message !== message){
			this._message = message;
			dijit.hideTooltip(this.domNode);
			if(message){
				dijit.showTooltip(message, this.domNode, this.tooltipPosition);
			}
		}
		return isValid;
	},

	isValid: function(/*Boolean*/ isFocused){
		// summary:
		//		Whether or not this is a valid value.   The only way a Select
		//		can be invalid is when it's required but nothing is selected.
		return (!this.required || !(/^\s*$/.test(this.value)));
	},

	reset: function(){
		// summary:
		//		Overridden so that the state will be cleared.
		this.inherited(arguments);
		dijit.hideTooltip(this.domNode);
		this.state = "";
		this._setStateClass();
		delete this._message;
	},

	postMixInProperties: function(){
		// summary:
		//		set the missing message
		this.inherited(arguments);
		this._missingMsg = dojo.i18n.getLocalization("dijit.form", "validate",
									this.lang).missingMessage;
	},

	postCreate: function(){
		this.inherited(arguments);
		if(this.tableNode.style.width){
			dojo.addClass(this.domNode, this.baseClass + "FixedWidth");
		}
	},

	isLoaded: function(){
		return this._isLoaded;
	},

	loadDropDown: function(/*Function*/ loadCallback){
		// summary:
		//		populates the menu
		this._loadChildren(true);
		this._isLoaded = true;
		loadCallback();
	},

	closeDropDown: function(){
		// overriding _HasDropDown.closeDropDown()
		this.inherited(arguments);

		if(this.dropDown && this.dropDown.menuTableNode){
			// Erase possible width: 100% setting from _SelectMenu.resize().
			// Leaving it would interfere with the next openDropDown() call, which
			// queries the natural size of the drop down.
			this.dropDown.menuTableNode.style.width = "";
		}
	},

	uninitialize: function(preserveDom){
		if(this.dropDown && !this.dropDown._destroyed){
			this.dropDown.destroyRecursive(preserveDom);
			delete this.dropDown;
		}
		this.inherited(arguments);
	}
});
<commit_msg>missing require, fixes #11001<commit_after>dojo.provide("dijit.form.Select");

dojo.require("dijit.form._FormSelectWidget");
dojo.require("dijit._HasDropDown");
dojo.require("dijit.Menu");
dojo.require("dijit.Tooltip");

dojo.requireLocalization("dijit.form", "validate");

dojo.declare("dijit.form._SelectMenu", dijit.Menu, {
	// summary:
	//		An internally-used menu for dropdown that allows us a vertical scrollbar
	buildRendering: function(){
		// summary:
		//		Stub in our own changes, so that our domNode is not a table
		//		otherwise, we won't respond correctly to heights/overflows
		this.inherited(arguments);
		var o = (this.menuTableNode = this.domNode);
		var n = (this.domNode = dojo.create("div", {style: {overflowX: "hidden", overflowY: "scroll"}}));
		if(o.parentNode){
			o.parentNode.replaceChild(n, o);
		}
		dojo.removeClass(o, "dijitMenuTable");
		n.className = o.className + " dijitSelectMenu";
		o.className = "dijitReset dijitMenuTable";
		dijit.setWaiRole(o,"listbox");
		dijit.setWaiRole(n,"presentation");
		n.appendChild(o);
	},
	resize: function(/*Object*/ mb){
		// summary:
		//		Overridden so that we are able to handle resizing our
		//		internal widget.  Note that this is not a "full" resize
		//		implementation - it only works correctly if you pass it a
		//		marginBox.
		//
		// mb: Object
		//		The margin box to set this dropdown to.
		if(mb){
			dojo.marginBox(this.domNode, mb);
			if("w" in mb){
				// We've explicitly set the wrapper
's width, so set
 width to match.
				// 100% is safer than a pixel value because there may be a scroll bar with
				// browser/OS specific width.
				this.menuTableNode.style.width = "100%";
			}
		}
	}
});

dojo.declare("dijit.form.Select", [dijit.form._FormSelectWidget, dijit._HasDropDown], {
	// summary:
	//		This is a "styleable" select box - it is basically a DropDownButton which
	//		can take a <select> as its input.

	baseClass: "dijitSelect",

	templateString: dojo.cache("dijit.form", "templates/Select.html"),

	// attributeMap: Object
	//		Add in our style to be applied to the focus node
	attributeMap: dojo.mixin(dojo.clone(dijit.form._FormSelectWidget.prototype.attributeMap),{style:"tableNode"}),

	// required: Boolean
	//		Can be true or false, default is false.
	required: false,

	// state: String
	//		Shows current state (ie, validation result) of input (Normal, Warning, or Error)
	state: "",

	//	tooltipPosition: String[]
	//		See description of dijit.Tooltip.defaultPosition for details on this parameter.
	tooltipPosition: [],

	// emptyLabel: string
	//		What to display in an "empty" dropdown
	emptyLabel: "",

	// _isLoaded: Boolean
	//		Whether or not we have been loaded
	_isLoaded: false,

	// _childrenLoaded: Boolean
	//		Whether or not our children have been loaded
	_childrenLoaded: false,

	_fillContent: function(){
		// summary:
		//		Set the value to be the first, or the selected index
		this.inherited(arguments);
		if(this.options.length && !this.value && this.srcNodeRef){
			var si = this.srcNodeRef.selectedIndex;
			this.value = this.options[si != -1 ? si : 0].value;
		}

		// Create the dropDown widget
		this.dropDown = new dijit.form._SelectMenu();
		dojo.addClass(this.dropDown.domNode, this.baseClass + "Menu");
	},

	_getMenuItemForOption: function(/*dijit.form.__SelectOption*/ option){
		// summary:
		//		For the given option, return the menu item that should be
		//		used to display it.  This can be overridden as needed
		if(!option.value){
			// We are a separator (no label set for it)
			return new dijit.MenuSeparator();
		}else{
			// Just a regular menu option
			var click = dojo.hitch(this, "_setValueAttr", option);
			var item = new dijit.MenuItem({
				option: option,
				label: option.label,
				onClick: click,
				disabled: option.disabled || false
			});
			dijit.setWaiRole(item.focusNode, "listitem");
			return item;
		}
	},

	_addOptionItem: function(/*dijit.form.__SelectOption*/ option){
		// summary:
		//		For the given option, add an option to our dropdown.
		//		If the option doesn't have a value, then a separator is added
		//		in that place.
		if(this.dropDown){
			this.dropDown.addChild(this._getMenuItemForOption(option));
		}
	},

	_getChildren: function(){
		if(!this.dropDown){
			return [];
		}
		return this.dropDown.getChildren();
	},

	_loadChildren: function(/*Boolean*/ loadMenuItems){
		// summary:
		//		Resets the menu and the length attribute of the button - and
		//		ensures that the label is appropriately set.
		//	loadMenuItems: Boolean
		//		actually loads the child menu items - we only do this when we are
		//		populating for showing the dropdown.

		if(loadMenuItems === true){
			// this.inherited destroys this.dropDown's child widgets (MenuItems).
			// Avoid this.dropDown (Menu widget) having a pointer to a destroyed widget (which will cause
			// issues later in _setSelected). (see #10296)
			if(this.dropDown){
				delete this.dropDown.focusedChild;
			}
			if(this.options.length){
				this.inherited(arguments);
			}else{
				// Drop down menu is blank but add one blank entry just so something appears on the screen
				// to let users know that they are no choices (mimicing native select behavior)
				dojo.forEach(this._getChildren(), function(child){ child.destroyRecursive(); });
				var item = new dijit.MenuItem({label: " "});
				this.dropDown.addChild(item);
			}
		}else{
			this._updateSelection();
		}

		var len = this.options.length;
		this._isLoaded = false;
		this._childrenLoaded = true;

		if(!this._loadingStore){
			// Don't call this if we are loading - since we will handle it later
			this._setValueAttr(this.value);
		}
	},

	_setValueAttr: function(value){
		this.inherited(arguments);
		dojo.attr(this.valueNode, "value", this.get("value"));
	},

	_setDisplay: function(/*String*/ newDisplay){
		// summary:
		//		sets the display for the given value (or values)
		this.containerNode.innerHTML = '' +
					(newDisplay || this.emptyLabel || " ") +
					'';
		dijit.setWaiState(this.focusNode, "valuetext", (newDisplay || this.emptyLabel || " ") );
	},

	validate: function(/*Boolean*/ isFocused){
		// summary:
		//		Called by oninit, onblur, and onkeypress.
		// description:
		//		Show missing or invalid messages if appropriate, and highlight textbox field.
		//		Used when a select is initially set to no value and the user is required to
		//		set the value.

		var isValid = this.isValid(isFocused);
		this.state = isValid ? "" : "Error";
		this._setStateClass();
		dijit.setWaiState(this.focusNode, "invalid", isValid ? "false" : "true");
		var message = isValid ? "" : this._missingMsg;
		if(this._message !== message){
			this._message = message;
			dijit.hideTooltip(this.domNode);
			if(message){
				dijit.showTooltip(message, this.domNode, this.tooltipPosition);
			}
		}
		return isValid;
	},

	isValid: function(/*Boolean*/ isFocused){
		// summary:
		//		Whether or not this is a valid value.   The only way a Select
		//		can be invalid is when it's required but nothing is selected.
		return (!this.required || !(/^\s*$/.test(this.value)));
	},

	reset: function(){
		// summary:
		//		Overridden so that the state will be cleared.
		this.inherited(arguments);
		dijit.hideTooltip(this.domNode);
		this.state = "";
		this._setStateClass();
		delete this._message;
	},

	postMixInProperties: function(){
		// summary:
		//		set the missing message
		this.inherited(arguments);
		this._missingMsg = dojo.i18n.getLocalization("dijit.form", "validate",
									this.lang).missingMessage;
	},

	postCreate: function(){
		this.inherited(arguments);
		if(this.tableNode.style.width){
			dojo.addClass(this.domNode, this.baseClass + "FixedWidth");
		}
	},

	isLoaded: function(){
		return this._isLoaded;
	},

	loadDropDown: function(/*Function*/ loadCallback){
		// summary:
		//		populates the menu
		this._loadChildren(true);
		this._isLoaded = true;
		loadCallback();
	},

	closeDropDown: function(){
		// overriding _HasDropDown.closeDropDown()
		this.inherited(arguments);

		if(this.dropDown && this.dropDown.menuTableNode){
			// Erase possible width: 100% setting from _SelectMenu.resize().
			// Leaving it would interfere with the next openDropDown() call, which
			// queries the natural size of the drop down.
			this.dropDown.menuTableNode.style.width = "";
		}
	},

	uninitialize: function(preserveDom){
		if(this.dropDown && !this.dropDown._destroyed){
			this.dropDown.destroyRecursive(preserveDom);
			delete this.dropDown;
		}
		this.inherited(arguments);
	}
});
<|endoftext|>


<commit_before>angular.module('ontrack.extension.notifications', [
    'ot.service.core',
    'ot.service.form',
    'ot.service.graphql'
])
    .config(function ($stateProvider) {
        $stateProvider.state('entity-subscriptions', {
            url: '/extension/notifications/entity-subscriptions/{type}/{id}',
            templateUrl: 'extension/notifications/entity-subscriptions.tpl.html',
            controller: 'EntitySubscriptionsCtrl'
        });
    })
    .controller('EntitySubscriptionsCtrl', function ($q, $scope, $stateParams, $http, ot, otAlertService, otFormService, otGraphqlService) {
        const view = ot.view();
        const type = $stateParams.type;
        const id = $stateParams.id;

        let viewInitialized = false;

        const queryVariables = {
            type: type,
            id: id
        };
        const query = `query(
            $type: ProjectEntityType!,
            $id: Int!,
        ) {
            entity(type: $type, id: $id) {
                entityName
                entity {
                    ... on Project {
                        links {
                            _page
                        }
                    }
                    ... on Branch {
                        links {
                            _page
                        }
                    }
                    ... on PromotionLevel {
                        links {
                            _page
                        }
                    }
                    ... on ValidationStamp {
                        links {
                            _page
                        }
                    }
                }
            }
            eventSubscriptions(filter: {
                entity: {
                    type: $type,
                    id: $id
                }
            }) {
                writeSubscriptionGranted
                pageItems {
                    id
                    channel
                    channelConfig
                    channelConfigText
                    events
                    keywords
                    disabled
                }
            }
        }`;

        const deleteSubscriptionQuery = `
            mutation(
                $entityType: ProjectEntityType!,
                $entityId: Int!,
                $id: String!,
            ) {
                deleteSubscription(input: {
                    projectEntity: {
                        type: $entityType,
                        id: $entityId
                    },
                    id: $id
                }) {
                    errors {
                        message
                    }
                }
            }
        `;

        const enableSubscriptionQuery = `
            mutation(
                $entityType: ProjectEntityType!,
                $entityId: Int!,
                $id: String!,
            ) {
                enableSubscription(input: {
                    projectEntity: {
                        type: $entityType,
                        id: $entityId
                    },
                    id: $id
                }) {
                    errors {
                        message
                    }
                }
            }
        `;

        const disableSubscriptionQuery = `
            mutation(
                $entityType: ProjectEntityType!,
                $entityId: Int!,
                $id: String!,
            ) {
                disableSubscription(input: {
                    projectEntity: {
                        type: $entityType,
                        id: $entityId
                    },
                    id: $id
                }) {
                    errors {
                        message
                    }
                }
            }
        `;

        const newSubscriptionQuery = `
            mutation(
                $type: ProjectEntityType!,
                $id: Int!,
                $channel: String!,
                $channelConfig: JSON!,
                $events: [String!]!,
                $keywords: String,
            ) {
              subscribeToEvents(input: {
                projectEntity: {
                    type: $type,
                    id: $id
                },
                channel: $channel,
                channelConfig: $channelConfig,
                events: $events,
                keywords: $keywords,
              }) {
                errors {
                  message
                }
                subscription {
                  id
                  channel
                  channelConfig
                  channelConfigText
                  events
                  keywords
                  disabled
                }
              }
            }
        `;

        $scope.deleteSubscription = (subscription) => {
            otAlertService.confirm({
                title: "Subscription deletion",
                message: "Do you really want to delete this subscription?"
            }).then(() => {
                otGraphqlService.pageGraphQLCallWithPayloadErrors(deleteSubscriptionQuery, {
                    entityType: type,
                    entityId: id,
                    id: subscription.id
                }, "deleteSubscription").finally(loadSubscriptions);
            });
        };

        $scope.enableSubscription = (subscription) => {
            otGraphqlService.pageGraphQLCallWithPayloadErrors(enableSubscriptionQuery, {
                entityType: type,
                entityId: id,
                id: subscription.id
            }, "enableSubscription").finally(loadSubscriptions);
        };

        $scope.disableSubscription = (subscription) => {
            otGraphqlService.pageGraphQLCallWithPayloadErrors(disableSubscriptionQuery, {
                entityType: type,
                entityId: id,
                id: subscription.id
            }, "disableSubscription").finally(loadSubscriptions);
        };

        const newSubscription = (form) => {
            const newSubscriptionQueryVariables = {
                type: type,
                id: id,
                channel: form.channel.id,
                channelConfig: form.channel.data,
                events: form.events,
                keywords: form.keywords
            };
            const d = $q.defer();
            otGraphqlService.graphQLCall(newSubscriptionQuery, newSubscriptionQueryVariables).then(data => {
                if (data.subscribeToEvents.errors && data.subscribeToEvents.errors.messages) {
                    d.reject(messages[0]);
                } else {
                    $scope.subscriptions.splice(0, 0, data.subscribeToEvents.subscription);
                    d.resolve(true);
                }
            }, messages => {
                d.reject(messages[0]);
            });
            return d.promise;
        };

        const newSubscriptionDialog = () => {
            otFormService.display({
                uri: '/extension/notifications/subscription/create',
                title: "New subscription",
                submit: (data) => {
                    return newSubscription(data);
                }
            });
        };

        $scope.loadingSubscriptions = false;
        const loadSubscriptions = () => {
            $scope.loadingSubscriptions = true;
            otGraphqlService.pageGraphQLCall(query, queryVariables).then((data) => {
                $scope.entityInfo = data.entity;
                $scope.subscriptions = data.eventSubscriptions.pageItems;
                $scope.writeSubscriptionGranted = data.eventSubscriptions.writeSubscriptionGranted;
                if (!viewInitialized) {
                    view.title = `Subscriptions for ${data.entity.entityName}`;
                    const page = data.entity.entity.links._page;
                    // Breadcrumbs to the entity
                    let bc = ot.homeBreadcrumbs();
                    bc.push([data.entity.entityName, data.entity.entity.links._page]);
                    view.breadcrumbs = bc;
                    // Close command to the entity
                    view.commands = [];
                    if ($scope.writeSubscriptionGranted) {
                        view.commands.push({
                            id: 'notifications-subscription-create',
                            name: "New subscription",
                            cls: 'ot-command-new',
                            action: newSubscriptionDialog
                        });
                    }
                    view.commands.push(ot.viewCloseCommand(page.substring(2)));
                    viewInitialized = true;
                }
            }).finally(() => {
                $scope.loadingSubscriptions = false;
            });
        };

        loadSubscriptions();

    })
    .config(function ($stateProvider) {
        $stateProvider.state('notification-recordings', {
            url: '/extension/notifications/notification-recordings',
            templateUrl: 'extension/notifications/notification-recordings.tpl.html',
            controller: 'NotificationRecordingsCtrl'
        });
    })
    .controller('NotificationRecordingsCtrl', function ($scope, ot, otAlertService, otGraphqlService) {
        const view = ot.view();
        view.title = "Notification recordings";
        view.breadcrumbs = ot.homeBreadcrumbs();
        view.commands = [
            ot.viewCloseCommand('/home')
        ];

        const query = `
            query NotificationRecordings(
                $offset: Int!,
                $size: Int!,
                $resultType: NotificationResultType,
            ) {
                notificationResultType: __type(name: "NotificationResultType") {
                  enumValues {
                    name
                  }
                }
                notificationRecords(
                    offset: $offset,
                    size: $size,
                    resultType: $resultType,
                ) {
                    pageInfo {
                      totalSize
                      nextPage {
                        offset
                        size
                      }
                      previousPage {
                        offset
                        size
                      }
                    }
                    pageItems {
                        timestamp
                        channel
                        channelConfig
                        event
                        result {
                            type
                            id
                            message
                        }
                    }
                }
            }
        `;

        const pageSize = 10;
        const queryVars = {
            offset: 0,
            size: pageSize,
            resultType: null,
        };

        const clearRecordsQuery = `
            mutation {
                deleteNotificationRecords(input: {}) {
                    errors {
                        message
                    }
                }
            }
        `;

        $scope.notificationResultTypeValues = [];

        $scope.filter = {
            notificationResultType: null
        };

        $scope.loadingRecords = false;
        const loadRecords = () => {
            $scope.loadingRecords = true;
            if ($scope.filter.notificationResultType) {
                queryVars.resultType = $scope.filter.notificationResultType;
            } else {
                queryVars.resultType = null;
            }
            otGraphqlService.pageGraphQLCall(query, queryVars).then(data => {
                $scope.navigation = data.notificationRecords.pageInfo;
                $scope.records = data.notificationRecords.pageItems;
                if ($scope.notificationResultTypeValues.length === 0) {
                    data.notificationResultType.enumValues.forEach(value => {
                        $scope.notificationResultTypeValues.push(value.name);
                    });
                }
            }).finally(() => {
                $scope.loadingRecords = false;
            });
        };

        loadRecords();

        $scope.refresh = loadRecords;

        $scope.switchPage = (pageRequest) => {
            queryVars.offset = pageRequest.offset;
            queryVars.size = pageSize;
            loadRecords();
        };

        $scope.deleteRecords = () => {
              otAlertService.confirm({
                  title: "Record deletion",
                  message: "Are you sure to delete ALL notification records?"
              }).then(() => {
                    otGraphqlService.pageGraphQLCall(clearRecordsQuery);
              }).then(loadRecords);
        };
    })
;<commit_msg>#951 Global subscriptions ~> UI<commit_after>angular.module('ontrack.extension.notifications', [
    'ot.service.core',
    'ot.service.form',
    'ot.service.graphql'
])
    .config(function ($stateProvider) {
        $stateProvider.state('entity-subscriptions', {
            url: '/extension/notifications/entity-subscriptions/{type}/{id}',
            templateUrl: 'extension/notifications/entity-subscriptions.tpl.html',
            controller: 'EntitySubscriptionsCtrl'
        });
    })
    .controller('EntitySubscriptionsCtrl', function ($q, $scope, $stateParams, $http, ot, otAlertService, otFormService, otGraphqlService) {
        const view = ot.view();
        const type = $stateParams.type;
        const id = $stateParams.id;

        let viewInitialized = false;

        const queryVariables = {
            type: type,
            id: id
        };
        const query = `query(
            $type: ProjectEntityType!,
            $id: Int!,
        ) {
            entity(type: $type, id: $id) {
                entityName
                entity {
                    ... on Project {
                        links {
                            _page
                        }
                    }
                    ... on Branch {
                        links {
                            _page
                        }
                    }
                    ... on PromotionLevel {
                        links {
                            _page
                        }
                    }
                    ... on ValidationStamp {
                        links {
                            _page
                        }
                    }
                }
            }
            eventSubscriptions(filter: {
                entity: {
                    type: $type,
                    id: $id
                }
            }) {
                writeSubscriptionGranted
                pageItems {
                    id
                    channel
                    channelConfig
                    channelConfigText
                    events
                    keywords
                    disabled
                }
            }
        }`;

        const deleteSubscriptionQuery = `
            mutation(
                $entityType: ProjectEntityType!,
                $entityId: Int!,
                $id: String!,
            ) {
                deleteSubscription(input: {
                    projectEntity: {
                        type: $entityType,
                        id: $entityId
                    },
                    id: $id
                }) {
                    errors {
                        message
                    }
                }
            }
        `;

        const enableSubscriptionQuery = `
            mutation(
                $entityType: ProjectEntityType!,
                $entityId: Int!,
                $id: String!,
            ) {
                enableSubscription(input: {
                    projectEntity: {
                        type: $entityType,
                        id: $entityId
                    },
                    id: $id
                }) {
                    errors {
                        message
                    }
                }
            }
        `;

        const disableSubscriptionQuery = `
            mutation(
                $entityType: ProjectEntityType!,
                $entityId: Int!,
                $id: String!,
            ) {
                disableSubscription(input: {
                    projectEntity: {
                        type: $entityType,
                        id: $entityId
                    },
                    id: $id
                }) {
                    errors {
                        message
                    }
                }
            }
        `;

        const newSubscriptionQuery = `
            mutation(
                $type: ProjectEntityType!,
                $id: Int!,
                $channel: String!,
                $channelConfig: JSON!,
                $events: [String!]!,
                $keywords: String,
            ) {
              subscribeToEvents(input: {
                projectEntity: {
                    type: $type,
                    id: $id
                },
                channel: $channel,
                channelConfig: $channelConfig,
                events: $events,
                keywords: $keywords,
              }) {
                errors {
                  message
                }
                subscription {
                  id
                  channel
                  channelConfig
                  channelConfigText
                  events
                  keywords
                  disabled
                }
              }
            }
        `;

        $scope.deleteSubscription = (subscription) => {
            otAlertService.confirm({
                title: "Subscription deletion",
                message: "Do you really want to delete this subscription?"
            }).then(() => {
                otGraphqlService.pageGraphQLCallWithPayloadErrors(deleteSubscriptionQuery, {
                    entityType: type,
                    entityId: id,
                    id: subscription.id
                }, "deleteSubscription").finally(loadSubscriptions);
            });
        };

        $scope.enableSubscription = (subscription) => {
            otGraphqlService.pageGraphQLCallWithPayloadErrors(enableSubscriptionQuery, {
                entityType: type,
                entityId: id,
                id: subscription.id
            }, "enableSubscription").finally(loadSubscriptions);
        };

        $scope.disableSubscription = (subscription) => {
            otGraphqlService.pageGraphQLCallWithPayloadErrors(disableSubscriptionQuery, {
                entityType: type,
                entityId: id,
                id: subscription.id
            }, "disableSubscription").finally(loadSubscriptions);
        };

        const newSubscription = (form) => {
            const newSubscriptionQueryVariables = {
                type: type,
                id: id,
                channel: form.channel.id,
                channelConfig: form.channel.data,
                events: form.events,
                keywords: form.keywords
            };
            const d = $q.defer();
            otGraphqlService.graphQLCall(newSubscriptionQuery, newSubscriptionQueryVariables).then(data => {
                if (data.subscribeToEvents.errors && data.subscribeToEvents.errors.messages) {
                    d.reject(messages[0]);
                } else {
                    $scope.subscriptions.splice(0, 0, data.subscribeToEvents.subscription);
                    d.resolve(true);
                }
            }, messages => {
                d.reject(messages[0]);
            });
            return d.promise;
        };

        const newSubscriptionDialog = () => {
            otFormService.display({
                uri: '/extension/notifications/subscription/create',
                title: "New subscription",
                submit: (data) => {
                    return newSubscription(data);
                }
            });
        };

        $scope.loadingSubscriptions = false;
        const loadSubscriptions = () => {
            $scope.loadingSubscriptions = true;
            otGraphqlService.pageGraphQLCall(query, queryVariables).then((data) => {
                $scope.entityInfo = data.entity;
                $scope.subscriptions = data.eventSubscriptions.pageItems;
                $scope.writeSubscriptionGranted = data.eventSubscriptions.writeSubscriptionGranted;
                if (!viewInitialized) {
                    view.title = `Subscriptions for ${data.entity.entityName}`;
                    const page = data.entity.entity.links._page;
                    // Breadcrumbs to the entity
                    let bc = ot.homeBreadcrumbs();
                    bc.push([data.entity.entityName, data.entity.entity.links._page]);
                    view.breadcrumbs = bc;
                    // Close command to the entity
                    view.commands = [];
                    if ($scope.writeSubscriptionGranted) {
                        view.commands.push({
                            id: 'notifications-subscription-create',
                            name: "New subscription",
                            cls: 'ot-command-new',
                            action: newSubscriptionDialog
                        });
                    }
                    view.commands.push(ot.viewCloseCommand(page.substring(2)));
                    viewInitialized = true;
                }
            }).finally(() => {
                $scope.loadingSubscriptions = false;
            });
        };

        loadSubscriptions();

    })
    .config(function ($stateProvider) {
        $stateProvider.state('global-subscriptions', {
            url: '/extension/notifications/global-subscriptions',
            templateUrl: 'extension/notifications/entity-subscriptions.tpl.html',
            controller: 'GlobalSubscriptionsCtrl'
        });
    })
    .controller('GlobalSubscriptionsCtrl', function ($q, $scope, $http, ot, otAlertService, otFormService, otGraphqlService) {
        const view = ot.view();
        view.title = "Global subscriptions";
        view.breadcrumbs = ot.homeBreadcrumbs();
        view.commands = [
            ot.viewCloseCommand('/home')
        ];
        let viewInitialized = false;

        const queryVariables = {};
        const query = `query GlobalSubscriptions {
            eventSubscriptions(filter: {}) {
                writeSubscriptionGranted
                pageItems {
                    id
                    channel
                    channelConfig
                    channelConfigText
                    events
                    keywords
                    disabled
                }
            }
        }`;

        const deleteSubscriptionQuery = `
            mutation(
                $id: String!,
            ) {
                deleteSubscription(input: {
                    id: $id
                }) {
                    errors {
                        message
                    }
                }
            }
        `;

        const enableSubscriptionQuery = `
            mutation(
                $id: String!,
            ) {
                enableSubscription(input: {
                    id: $id
                }) {
                    errors {
                        message
                    }
                }
            }
        `;

        const disableSubscriptionQuery = `
            mutation(
                $id: String!,
            ) {
                disableSubscription(input: {
                    id: $id
                }) {
                    errors {
                        message
                    }
                }
            }
        `;

        const newSubscriptionQuery = `
            mutation(
                $channel: String!,
                $channelConfig: JSON!,
                $events: [String!]!,
                $keywords: String,
            ) {
              subscribeToEvents(input: {
                channel: $channel,
                channelConfig: $channelConfig,
                events: $events,
                keywords: $keywords,
              }) {
                errors {
                  message
                }
                subscription {
                  id
                  channel
                  channelConfig
                  channelConfigText
                  events
                  keywords
                  disabled
                }
              }
            }
        `;

        $scope.deleteSubscription = (subscription) => {
            otAlertService.confirm({
                title: "Subscription deletion",
                message: "Do you really want to delete this subscription?"
            }).then(() => {
                otGraphqlService.pageGraphQLCallWithPayloadErrors(deleteSubscriptionQuery, {
                    id: subscription.id
                }, "deleteSubscription").finally(loadSubscriptions);
            });
        };

        $scope.enableSubscription = (subscription) => {
            otGraphqlService.pageGraphQLCallWithPayloadErrors(enableSubscriptionQuery, {
                id: subscription.id
            }, "enableSubscription").finally(loadSubscriptions);
        };

        $scope.disableSubscription = (subscription) => {
            otGraphqlService.pageGraphQLCallWithPayloadErrors(disableSubscriptionQuery, {
                id: subscription.id
            }, "disableSubscription").finally(loadSubscriptions);
        };

        const newSubscription = (form) => {
            const newSubscriptionQueryVariables = {
                channel: form.channel.id,
                channelConfig: form.channel.data,
                events: form.events,
                keywords: form.keywords
            };
            const d = $q.defer();
            otGraphqlService.graphQLCall(newSubscriptionQuery, newSubscriptionQueryVariables).then(data => {
                if (data.subscribeToEvents.errors && data.subscribeToEvents.errors.messages) {
                    d.reject(messages[0]);
                } else {
                    $scope.subscriptions.splice(0, 0, data.subscribeToEvents.subscription);
                    d.resolve(true);
                }
            }, messages => {
                d.reject(messages[0]);
            });
            return d.promise;
        };

        const newSubscriptionDialog = () => {
            otFormService.display({
                uri: '/extension/notifications/subscription/create',
                title: "New subscription",
                submit: (data) => {
                    return newSubscription(data);
                }
            });
        };

        $scope.loadingSubscriptions = false;
        const loadSubscriptions = () => {
            $scope.loadingSubscriptions = true;
            otGraphqlService.pageGraphQLCall(query, queryVariables).then((data) => {
                $scope.subscriptions = data.eventSubscriptions.pageItems;
                $scope.writeSubscriptionGranted = data.eventSubscriptions.writeSubscriptionGranted;
                if (!viewInitialized) {
                    if ($scope.writeSubscriptionGranted) {
                        view.commands.splice(0, 0, {
                            id: 'notifications-subscription-create',
                            name: "New subscription",
                            cls: 'ot-command-new',
                            action: newSubscriptionDialog
                        });
                    }
                    viewInitialized = true;
                }
            }).finally(() => {
                $scope.loadingSubscriptions = false;
            });
        };

        loadSubscriptions();

    })
    .config(function ($stateProvider) {
        $stateProvider.state('notification-recordings', {
            url: '/extension/notifications/notification-recordings',
            templateUrl: 'extension/notifications/notification-recordings.tpl.html',
            controller: 'NotificationRecordingsCtrl'
        });
    })
    .controller('NotificationRecordingsCtrl', function ($scope, ot, otAlertService, otGraphqlService) {
        const view = ot.view();
        view.title = "Notification recordings";
        view.breadcrumbs = ot.homeBreadcrumbs();
        view.commands = [
            ot.viewCloseCommand('/home')
        ];

        const query = `
            query NotificationRecordings(
                $offset: Int!,
                $size: Int!,
                $resultType: NotificationResultType,
            ) {
                notificationResultType: __type(name: "NotificationResultType") {
                  enumValues {
                    name
                  }
                }
                notificationRecords(
                    offset: $offset,
                    size: $size,
                    resultType: $resultType,
                ) {
                    pageInfo {
                      totalSize
                      nextPage {
                        offset
                        size
                      }
                      previousPage {
                        offset
                        size
                      }
                    }
                    pageItems {
                        timestamp
                        channel
                        channelConfig
                        event
                        result {
                            type
                            id
                            message
                        }
                    }
                }
            }
        `;

        const pageSize = 10;
        const queryVars = {
            offset: 0,
            size: pageSize,
            resultType: null,
        };

        const clearRecordsQuery = `
            mutation {
                deleteNotificationRecords(input: {}) {
                    errors {
                        message
                    }
                }
            }
        `;

        $scope.notificationResultTypeValues = [];

        $scope.filter = {
            notificationResultType: null
        };

        $scope.loadingRecords = false;
        const loadRecords = () => {
            $scope.loadingRecords = true;
            if ($scope.filter.notificationResultType) {
                queryVars.resultType = $scope.filter.notificationResultType;
            } else {
                queryVars.resultType = null;
            }
            otGraphqlService.pageGraphQLCall(query, queryVars).then(data => {
                $scope.navigation = data.notificationRecords.pageInfo;
                $scope.records = data.notificationRecords.pageItems;
                if ($scope.notificationResultTypeValues.length === 0) {
                    data.notificationResultType.enumValues.forEach(value => {
                        $scope.notificationResultTypeValues.push(value.name);
                    });
                }
            }).finally(() => {
                $scope.loadingRecords = false;
            });
        };

        loadRecords();

        $scope.refresh = loadRecords;

        $scope.switchPage = (pageRequest) => {
            queryVars.offset = pageRequest.offset;
            queryVars.size = pageSize;
            loadRecords();
        };

        $scope.deleteRecords = () => {
              otAlertService.confirm({
                  title: "Record deletion",
                  message: "Are you sure to delete ALL notification records?"
              }).then(() => {
                    otGraphqlService.pageGraphQLCall(clearRecordsQuery);
              }).then(loadRecords);
        };
    })
;<|endoftext|>


<commit_before>/**
 * Created by guntupv on 12/24/15.
 */

var mongoClient = require('mongodb').MongoClient;

var mongoDbUrl =  'mongodb://localhost:27017/log-guru';
var collectionName = 'epicenter';

module.exports.doesValueExistInDb = function (parameter) {
    mongoClient.connect(mongoDbUrl, function (err, db) {
        if (!err) {
            var collection = db.collection(collectionName);
            var obj = {};
            obj[parameter] = {$exists: true, $ne: null};
            collection.find(obj, function(data, err){
                if(!err && (data != null)){
                    return true;
                }
                else {
                    return false;
                }
            });
        }
    });
}

module.exports.insertIntoDB = function(parameter) {
    mongoClient.connect(mongoDbUrl, function (err, db) {
        if (!err) {
            var collection = db.collection(collectionName);
            return collection.insert(parameter);
        }
    });
}

<commit_msg>- Fixing the mongoDb find callback.<commit_after>/**
 * Created by guntupv on 12/24/15.
 */

var mongoClient = require('mongodb').MongoClient;

var mongoDbUrl =  'mongodb://localhost:27017/log-guru';
var collectionName = 'epicenter';

module.exports.doesValueExistInDb = function (parameter) {
    mongoClient.connect(mongoDbUrl, function (err, db) {
        if (!err) {
            var collection = db.collection(collectionName);
            var obj = {};
            obj[parameter] = {$exists: true, $ne: null};
            collection.find(obj, function(err, data){
                if(!err && (data != null)){
                    return true;
                }
                else {
                    return false;
                }
            });
        }
    });
}

module.exports.insertIntoDB = function(parameter) {
    mongoClient.connect(mongoDbUrl, function (err, db) {
        if (!err) {
            var collection = db.collection(collectionName);
            return collection.insert(parameter);
        }
    });
}

<|endoftext|>


<commit_before>/**
 * alphabetizes css declarations
 * @author: Mark McCann <www.markmccann.me>
 * @license: MIT
 */

var cssAlphabetize = (function(){

    /**
     * extends object
     */
    var extend = function () {
        var a = arguments;
        for( var i = 1; i < a.length; i++ )
            for( var key in a[i] )
                if(a[i].hasOwnProperty(key))
                    a[0][key] = a[i][key];
        return a[0];
    }

    /**
     * splits a declaration into separate parts and
     * determines if is any special case
     */
    var Declaration = function(line) {
        this.line = line.trim();
        this.property = this.line.replace( /^[_\*]?(?:-\w*-(?:(?:osx)-)?)?([^:]*):.*/, '$1' );
        this.original = this.line.replace( /^[_\*]?((?:-\w*-(?:(?:osx)-)?)?[^:]*):.*/, '$1' );
        this.value = this.line.replace( /[^:]*: *([^;'"(]*([("']["']?[^'")]*['"]?['")])?[^;'"(]*);.*/, '$1' );
        this.comment = /^\/\*((?!\*\/)(.|\n))*\*\/$/.test(this.line);
        this.hacked = /^[_\*]|(\\9|\\0)+;/.test(this.line);
        this.vendor = /^-\w*-/.test(this.line);
        return this;
    }

    /**
     * default settings for alphabetizer
     */
    var defaults = {
        delimeter: '```',
        ascending: true
    }

    /**
     * return the alphabetize function
     */
    return function( styles, options ) {
        // set alphabetizer settings
        var settings = extend( defaults, options || {} );
        var direction = settings.ascending ? 1 : -1;
        // the contents of each set of brackets that does
        // not contain a set of brackets
        return styles.replace(/{([^{}]*)}/g, function( match, contents ) {
            return '{' + contents
                // make sure there is a final semicolon
                .replace(/([)'"%\w])((?:\s*\/\*((?!\*\/)(.|\n))*\*\/)*\s*)$/, '$1;$2')
                // add a unique delimeter after every declaration and comment
                .replace(/([^:\/]*:([^;'"(])*([("']["']?[^'")]*['"]?['")])?([^;])*;( *\/\*((?!\*\/)(.|\n))*\*\/)?|\s*\/\*((?!\*\/)(.|\n))*\*\/)/g, '$1'+settings.delimeter )
                // remove final delimeter to avoid creating empty element in array
                .replace(new RegExp(settings.delimeter+'\\s*$'), '')
                // split string into array by the unique delimeter
                .split(settings.delimeter)
                // sort the array alphabetically
                .sort(function( a, b ){
                    // initialize declartions to compare values
                    a = new Declaration(a); b = new Declaration(b);
                    console.log(a);
                    console.log(b);
                    // comment -vs- comment
                    if( a.comment && b.comment ) return 0;
                    // comment -vs- non-comment
                    if((!a.comment && b.comment)
                    || (a.comment && !b.comment)) return 1;
                    // if the properties match
                    if( a.property == b.property ) {
                        // standard -vs- hack (width:100% -> _width:100%)
                        if(!a.hacked && b.hacked) return -1;
                        if(!b.hacked && a.hacked) return 1;
                        // standard -vs- vendor (border-radius -> -webkit-border-radius)
                        if(!a.vendor && b.vendor) return 1;
                        if(!b.vendor && a.vendor) return -1;
                        // standard -vs- identical (background -> background)
                        if(a.value > b.value) return 1 * direction;
                        if(b.value > a.value) return -1 * direction;
                        // vendor -vs- vendor (-webkit-border-radius -> -webkit-border-radius)
                        if(a.original > b.original) return 1 * direction;
                        if(b.original > a.original) return -1 * direction;
                    }
                    // standard -vs- standard
                    if( a.property < b.property ) return -1 * direction;
                    if( a.property > b.property ) return 1 * direction;
                    // they are equivalent
                    return 0;
                })
                // rejoin the array back into a string
                .join('')
                // add ending space if content present
                + ( /\w|\//.test(contents) ? /(\s*)$/.exec(contents)[0] : '' )
                // add the closing bracket back
                + '}';
        });

    }

})();<commit_msg>minor bug fixes in regex<commit_after>/**
 * alphabetizes css declarations
 * @author: Mark McCann <www.markmccann.me>
 * @license: MIT
 */

var cssAlphabetize = (function(){

    /**
     * extends object
     */
    var extend = function () {
        var a = arguments;
        for( var i = 1; i < a.length; i++ )
            for( var key in a[i] )
                if(a[i].hasOwnProperty(key))
                    a[0][key] = a[i][key];
        return a[0];
    }

    /**
     * splits a declaration into separate parts and
     * determines if is any special case
     */
    var Declaration = function(line) {
        this.line = line.trim();
        this.property = this.line.replace( /^[_\*]?(?:-\w*-(?:(?:osx)-)?)?([^:]*):.*/, '$1' );
        this.original = this.line.replace( /^[_\*]?((?:-\w*-(?:(?:osx)-)?)?[^:]*):.*/, '$1' );
        this.value = this.line.replace( /[^:]*: *([^;'"(]*(\(["']?[^'")]*['"]?\)|["'][^'"]*['"])?[^;'"(]*);.*/, '$1' );
        this.comment = /^\/\*((?!\*\/)(.|\n))*\*\/$/.test(this.line);
        this.hacked = /^[_\*]|(\\9|\\0)+;/.test(this.line);
        this.vendor = /^-\w*-/.test(this.line);
        return this;
    }

    /**
     * default settings for alphabetizer
     */
    var defaults = {
        delimeter: '```',
        ascending: true
    }

    /**
     * return the alphabetize function
     */
    return function( styles, options ) {
        // set alphabetizer settings
        var settings = extend( defaults, options || {} );
        var direction = settings.ascending ? 1 : -1;
        // the contents of each set of brackets that does
        // not contain a set of brackets
        return styles.replace(/{([^{}]*)}/g, function( match, contents ) {
            return '{' + contents
                // make sure there is a final semicolon
                .replace(/([)'"%\w\d])((?:\s*\/\*((?!\*\/)(.|\n))*\*\/)*\s*)$/, '$1;$2')
                // add a unique delimeter after every declaration and comment
                .replace(/([\w\s-]*:([^;'"(])*(\(["']?[^'")]*['"]?\)|["'][^'"]*['"])?([^;])*;( *\/\*((?!\*\/)(.|\n))*\*\/)*|\s*\/\*((?!\*\/)(.|\n))*\*\/)/g, '$1'+settings.delimeter )
                // remove final delimeter to avoid creating empty element in array
                .replace(new RegExp(settings.delimeter+'\\s*$'), '')
                // split string into array by the unique delimeter
                .split(settings.delimeter)
                // sort the array alphabetically
                .sort(function( a, b ){
                    // initialize declartions to compare values
                    a = new Declaration(a); b = new Declaration(b);
                    // comment -vs- comment
                    if( a.comment && b.comment ) return 0;
                    // comment -vs- non-comment
                    if((!a.comment && b.comment)
                    || (a.comment && !b.comment)) return 1;
                    // if the properties match
                    if( a.property == b.property ) {
                        // standard -vs- hack (width:100% -> _width:100%)
                        if(!a.hacked && b.hacked) return -1;
                        if(!b.hacked && a.hacked) return 1;
                        // standard -vs- vendor (border-radius -> -webkit-border-radius)
                        if(!a.vendor && b.vendor) return 1;
                        if(!b.vendor && a.vendor) return -1;
                        // standard -vs- identical (background -> background)
                        if(a.value > b.value) return 1 * direction;
                        if(b.value > a.value) return -1 * direction;
                        // vendor -vs- vendor (-webkit-border-radius -> -webkit-border-radius)
                        if(a.original > b.original) return 1 * direction;
                        if(b.original > a.original) return -1 * direction;
                    }
                    // standard -vs- standard
                    if( a.property < b.property ) return -1 * direction;
                    if( a.property > b.property ) return 1 * direction;
                    // they are equivalent
                    return 0;
                })
                // rejoin the array back into a string
                .join('')
                // add ending space if content present
                + ( /\w|\//.test(contents) ? /(\s*)$/.exec(contents)[0] : '' )
                // add the closing bracket back
                + '}';
        });

    }

})();<|endoftext|>


<commit_before><commit_msg>[DE PE SSE] Fix bug 58378<commit_after><|endoftext|>