<commit_before>/*
    TinyMCE filebrowser implementation.
*/

(function($, tinyMCE) {

    // Get the important values from TinyMCE.
    var win = tinyMCEPopup.getWindowArg("window");
    var inputId = tinyMCEPopup.getWindowArg("input");
    // Get the input from the opening window.
    var input = $("#" + inputId, win.document);

    // Define the filebrowser plugin.
    $.filebrowser = {}

    // Closes the filebrowser and sends the information back to the TinyMCE
    // editor.
    $.filebrowser.complete = function(permalink, title) {
        input.attr("value", permalink);
        // Set the link dialogue values.
        $("#linktitle", win.document).attr("value", title);
        // Set the image dialogue values.
        if (typeof(win.ImageDialog) != "undefined") {
            if (win.ImageDialog.getImageData) {
                win.ImageDialog.getImageData();
            }
            if (win.ImageDialog.showPreviewImage) {
                win.ImageDialog.showPreviewImage(permalink);
            }
            $("#alt", win.document).attr("value", title);
            $("#title", win.document).attr("value", title);
        }
        // Close the dialogue.
        tinyMCEPopup.close();
        return false;
    }

    // Initializes the popup file browser.
    $.filebrowser.initBrowser = function() {
        // Make the changelist links clickable and remove the original inline click listener.
        $("div#changelist tr.row1 a, div#changelist tr.row2 a").attr("onclick", null).click(function() {
            var img = $("img", this);
            var title = img.attr("title");
            var permalink = img.attr("cms:permalink");
            $.filebrowser.complete(permalink, title)
        });
        // Make the add link clickable.
        $("a.addlink").click(function() {
            tinyMCE.activeEditor.windowManager.open({
                file: $(this).attr("href") + "&_tinymce=1",
                title: "Add file",
                width: 760,
                height: 400,
                resizable: "yes",
                inline: "yes",
                close_previous: "no",
                popup_css: false,
            }, {
                window: win,
                input: inputId
            });
            tinyMCEPopup.close();
            return false;
        });
    }

}(jQuery, tinyMCE));<commit_msg>Fixed another IE javascript bug.<commit_after>/*
    TinyMCE filebrowser implementation.
*/

(function($, tinyMCE) {

    // Get the important values from TinyMCE.
    var win = tinyMCEPopup.getWindowArg("window");
    var inputId = tinyMCEPopup.getWindowArg("input");
    // Get the input from the opening window.
    var input = $("#" + inputId, win.document);

    // Define the filebrowser plugin.
    $.filebrowser = {}

    // Closes the filebrowser and sends the information back to the TinyMCE
    // editor.
    $.filebrowser.complete = function(permalink, title) {
        input.attr("value", permalink);
        // Set the link dialogue values.
        $("#linktitle", win.document).attr("value", title);
        // Set the image dialogue values.
        if (typeof(win.ImageDialog) != "undefined") {
            if (win.ImageDialog.getImageData) {
                win.ImageDialog.getImageData();
            }
            if (win.ImageDialog.showPreviewImage) {
                win.ImageDialog.showPreviewImage(permalink);
            }
            $("#alt", win.document).attr("value", title);
            $("#title", win.document).attr("value", title);
        }
        // Close the dialogue.
        tinyMCEPopup.close();
        return false;
    }

    // Initializes the popup file browser.
    $.filebrowser.initBrowser = function() {
        // Make the changelist links clickable and remove the original inline click listener.
        $("div#changelist tr.row1 a, div#changelist tr.row2 a").attr("onclick", null).click(function() {
            var img = $("img", this);
            var title = img.attr("title");
            var permalink = img.attr("cms:permalink");
            $.filebrowser.complete(permalink, title)
        });
        // Make the add link clickable.
        $("a.addlink").click(function() {
            tinyMCE.activeEditor.windowManager.open({
                file: $(this).attr("href") + "&_tinymce=1",
                title: "Add file",
                width: 760,
                height: 400,
                resizable: "yes",
                inline: "yes",
                close_previous: "no",
                popup_css: false
            }, {
                window: win,
                input: inputId
            });
            tinyMCEPopup.close();
            return false;
        });
    }

}(jQuery, tinyMCE));<|endoftext|>


<commit_before>define("dijit/layout/StackController", ["dojo", "dijit", "dijit/_Widget", "dijit/_TemplatedMixin", "dijit/_Container", "dijit/form/ToggleButton", "i18n!dijit/nls/common"], function(dojo, dijit) {

dojo.declare(
		"dijit.layout.StackController",
		[dijit._Widget, dijit._TemplatedMixin, dijit._Container],
		{
			// summary:
			//		Set of buttons to select a page in a page list.
			// description:
			//		Monitors the specified StackContainer, and whenever a page is
			//		added, deleted, or selected, updates itself accordingly.

			templateString: "",

			// containerId: [const] String
			//		The id of the page container that I point to
			containerId: "",

			// buttonWidget: [const] String
			//		The name of the button widget to create to correspond to each page
			buttonWidget: "dijit.layout._StackButton",

			constructor: function(){
				this.pane2button = {};		// mapping from pane id to buttons
				this.pane2connects = {};	// mapping from pane id to this.connect() handles
				this.pane2watches = {};		// mapping from pane id to watch() handles
			},

			buildRendering: function(){
				this.inherited(arguments);
				dijit.setWaiRole(this.domNode, "tablist");	// TODO: unneeded?   it's in template above.
			},

			postCreate: function(){
				this.inherited(arguments);

				// Listen to notifications from StackContainer
				this.subscribe(this.containerId+"-startup", "onStartup");
				this.subscribe(this.containerId+"-addChild", "onAddChild");
				this.subscribe(this.containerId+"-removeChild", "onRemoveChild");
				this.subscribe(this.containerId+"-selectChild", "onSelectChild");
				this.subscribe(this.containerId+"-containerKeyPress", "onContainerKeyPress");
			},

			onStartup: function(/*Object*/ info){
				// summary:
				//		Called after StackContainer has finished initializing
				// tags:
				//		private
				dojo.forEach(info.children, this.onAddChild, this);
				if(info.selected){
					// Show button corresponding to selected pane (unless selected
					// is null because there are no panes)
					this.onSelectChild(info.selected);
				}
			},

			destroy: function(){
				for(var pane in this.pane2button){
					this.onRemoveChild(dijit.byId(pane));
				}
				this.inherited(arguments);
			},

			onAddChild: function(/*dijit._Widget*/ page, /*Integer?*/ insertIndex){
				// summary:
				//		Called whenever a page is added to the container.
				//		Create button corresponding to the page.
				// tags:
				//		private

				// create an instance of the button widget
				var cls = dojo.getObject(this.buttonWidget);
				var button = new cls({
					id: this.id + "_" + page.id,
					label: page.title,
					dir: page.dir,
					lang: page.lang,
					showLabel: page.showTitle,
					iconClass: page.iconClass,
					closeButton: page.closable,
					title: page.tooltip
				});
				dijit.setWaiState(button.focusNode,"selected", "false");

				// map from page attribute to corresponding tab button attribute
				var pageAttrList = ["title", "showTitle", "iconClass", "closable", "tooltip"],
					buttonAttrList = ["label", "showLabel", "iconClass", "closeButton", "title"];

				// watch() so events like page title changes are reflected in tab button
				this.pane2watches[page.id] = dojo.map(pageAttrList, function(pageAttr, idx){
					return page.watch(pageAttr, function(name, oldVal, newVal){
						button.set(buttonAttrList[idx], newVal);
					});
				});

				// connections so that clicking a tab button selects the corresponding page
				this.pane2connects[page.id] = [
					this.connect(button, 'onClick', dojo.hitch(this,"onButtonClick", page)),
					this.connect(button, 'onClickCloseButton', dojo.hitch(this,"onCloseButtonClick", page))
				];

				this.addChild(button, insertIndex);
				this.pane2button[page.id] = button;
				page.controlButton = button;	// this value might be overwritten if two tabs point to same container
				if(!this._currentChild){ // put the first child into the tab order
					button.focusNode.setAttribute("tabIndex", "0");
					dijit.setWaiState(button.focusNode, "selected", "true");
					this._currentChild = page;
				}
				// make sure all tabs have the same length
				if(!this.isLeftToRight() && dojo.isIE && this._rectifyRtlTabList){
					this._rectifyRtlTabList();
				}
			},

			onRemoveChild: function(/*dijit._Widget*/ page){
				// summary:
				//		Called whenever a page is removed from the container.
				//		Remove the button corresponding to the page.
				// tags:
				//		private

				if(this._currentChild === page){ this._currentChild = null; }

				// disconnect/unwatch connections/watches related to page being removed
				dojo.forEach(this.pane2connects[page.id], dojo.hitch(this, "disconnect"));
				delete this.pane2connects[page.id];
				dojo.forEach(this.pane2watches[page.id], function(w){ w.unwatch(); });
				delete this.pane2watches[page.id];

				var button = this.pane2button[page.id];
				if(button){
					this.removeChild(button);
					delete this.pane2button[page.id];
					button.destroy();
				}
				delete page.controlButton;
			},

			onSelectChild: function(/*dijit._Widget*/ page){
				// summary:
				//		Called when a page has been selected in the StackContainer, either by me or by another StackController
				// tags:
				//		private

				if(!page){ return; }

				if(this._currentChild){
					var oldButton=this.pane2button[this._currentChild.id];
					oldButton.set('checked', false);
					dijit.setWaiState(oldButton.focusNode, "selected", "false");
					oldButton.focusNode.setAttribute("tabIndex", "-1");
				}

				var newButton=this.pane2button[page.id];
				newButton.set('checked', true);
				dijit.setWaiState(newButton.focusNode, "selected", "true");
				this._currentChild = page;
				newButton.focusNode.setAttribute("tabIndex", "0");
				var container = dijit.byId(this.containerId);
				dijit.setWaiState(container.containerNode, "labelledby", newButton.id);
			},

			onButtonClick: function(/*dijit._Widget*/ page){
				// summary:
				//		Called whenever one of my child buttons is pressed in an attempt to select a page
				// tags:
				//		private

				var container = dijit.byId(this.containerId);
				container.selectChild(page);
			},

			onCloseButtonClick: function(/*dijit._Widget*/ page){
				// summary:
				//		Called whenever one of my child buttons [X] is pressed in an attempt to close a page
				// tags:
				//		private

				var container = dijit.byId(this.containerId);
				container.closeChild(page);
				if(this._currentChild){
					var b = this.pane2button[this._currentChild.id];
					if(b){
						dijit.focus(b.focusNode || b.domNode);
					}
				}
			},

			// TODO: this is a bit redundant with forward, back api in StackContainer
			adjacent: function(/*Boolean*/ forward){
				// summary:
				//		Helper for onkeypress to find next/previous button
				// tags:
				//		private

				if(!this.isLeftToRight() && (!this.tabPosition || /top|bottom/.test(this.tabPosition))){ forward = !forward; }
				// find currently focused button in children array
				var children = this.getChildren();
				var current = dojo.indexOf(children, this.pane2button[this._currentChild.id]);
				// pick next button to focus on
				var offset = forward ? 1 : children.length - 1;
				return children[ (current + offset) % children.length ]; // dijit._Widget
			},

			onkeypress: function(/*Event*/ e){
				// summary:
				//		Handle keystrokes on the page list, for advancing to next/previous button
				//		and closing the current page if the page is closable.
				// tags:
				//		private

				if(this.disabled || e.altKey ){ return; }
				var forward = null;
				if(e.ctrlKey || !e._djpage){
					var k = dojo.keys;
					switch(e.charOrCode){
						case k.LEFT_ARROW:
						case k.UP_ARROW:
							if(!e._djpage){ forward = false; }
							break;
						case k.PAGE_UP:
							if(e.ctrlKey){ forward = false; }
							break;
						case k.RIGHT_ARROW:
						case k.DOWN_ARROW:
							if(!e._djpage){ forward = true; }
							break;
						case k.PAGE_DOWN:
							if(e.ctrlKey){ forward = true; }
							break;
						case k.HOME:
						case k.END:
							var children = this.getChildren();
							if(children && children.length){
								children[e.charOrCode == k.HOME ? 0 : children.length-1].onClick();
							}
							dojo.stopEvent(e);
							break;
						case k.DELETE:
							if(this._currentChild.closable){
								this.onCloseButtonClick(this._currentChild);
							}
							dojo.stopEvent(e);
							break;
						default:
							if(e.ctrlKey){
								if(e.charOrCode === k.TAB){
									this.adjacent(!e.shiftKey).onClick();
									dojo.stopEvent(e);
								}else if(e.charOrCode == "w"){
									if(this._currentChild.closable){
										this.onCloseButtonClick(this._currentChild);
									}
									dojo.stopEvent(e); // avoid browser tab closing.
								}
							}
					}
					// handle next/previous page navigation (left/right arrow, etc.)
					if(forward !== null){
						this.adjacent(forward).onClick();
						dojo.stopEvent(e);
					}
				}
			},

			onContainerKeyPress: function(/*Object*/ info){
				// summary:
				//		Called when there was a keypress on the container
				// tags:
				//		private
				info.e._djpage = info.page;
				this.onkeypress(info.e);
			}
	});

dojo.declare("dijit.layout._StackButton",
		dijit.form.ToggleButton,
		{
		// summary:
		//		Internal widget used by StackContainer.
		// description:
		//		The button-like or tab-like object you click to select or delete a page
		// tags:
		//		private

		// Override _FormWidget.tabIndex.
		// StackContainer buttons are not in the tab order by default.
		// Probably we should be calling this.startupKeyNavChildren() instead.
		tabIndex: "-1",

		buildRendering: function(/*Event*/ evt){
			this.inherited(arguments);
			dijit.setWaiRole((this.focusNode || this.domNode), "tab");
		},

		onClick: function(/*Event*/ evt){
			// summary:
			//		This is for TabContainer where the tabs are  rather than button,
			//		so need to set focus explicitly (on some browsers)
			//		Note that you shouldn't override this method, but you can connect to it.
			dijit.focus(this.focusNode);

			// ... now let StackController catch the event and tell me what to do
		},

		onClickCloseButton: function(/*Event*/ evt){
			// summary:
			//		StackContainer connects to this function; if your widget contains a close button
			//		then clicking it should call this function.
			//		Note that you shouldn't override this method, but you can connect to it.
			evt.stopPropagation();
		}
	});

return dijit.layout.StackController;
});
<commit_msg>Need to declare "closeButton" parameter since there's a custom setter for in (albeit in !TabButton, not !StackButton).   Fixes right-click close menu for tab buttons.   Refs #12376 !strict.<commit_after>define("dijit/layout/StackController", ["dojo", "dijit", "dijit/_Widget", "dijit/_TemplatedMixin", "dijit/_Container", "dijit/form/ToggleButton", "i18n!dijit/nls/common"], function(dojo, dijit) {

dojo.declare(
		"dijit.layout.StackController",
		[dijit._Widget, dijit._TemplatedMixin, dijit._Container],
		{
			// summary:
			//		Set of buttons to select a page in a page list.
			// description:
			//		Monitors the specified StackContainer, and whenever a page is
			//		added, deleted, or selected, updates itself accordingly.

			templateString: "",

			// containerId: [const] String
			//		The id of the page container that I point to
			containerId: "",

			// buttonWidget: [const] String
			//		The name of the button widget to create to correspond to each page
			buttonWidget: "dijit.layout._StackButton",

			constructor: function(){
				this.pane2button = {};		// mapping from pane id to buttons
				this.pane2connects = {};	// mapping from pane id to this.connect() handles
				this.pane2watches = {};		// mapping from pane id to watch() handles
			},

			buildRendering: function(){
				this.inherited(arguments);
				dijit.setWaiRole(this.domNode, "tablist");	// TODO: unneeded?   it's in template above.
			},

			postCreate: function(){
				this.inherited(arguments);

				// Listen to notifications from StackContainer
				this.subscribe(this.containerId+"-startup", "onStartup");
				this.subscribe(this.containerId+"-addChild", "onAddChild");
				this.subscribe(this.containerId+"-removeChild", "onRemoveChild");
				this.subscribe(this.containerId+"-selectChild", "onSelectChild");
				this.subscribe(this.containerId+"-containerKeyPress", "onContainerKeyPress");
			},

			onStartup: function(/*Object*/ info){
				// summary:
				//		Called after StackContainer has finished initializing
				// tags:
				//		private
				dojo.forEach(info.children, this.onAddChild, this);
				if(info.selected){
					// Show button corresponding to selected pane (unless selected
					// is null because there are no panes)
					this.onSelectChild(info.selected);
				}
			},

			destroy: function(){
				for(var pane in this.pane2button){
					this.onRemoveChild(dijit.byId(pane));
				}
				this.inherited(arguments);
			},

			onAddChild: function(/*dijit._Widget*/ page, /*Integer?*/ insertIndex){
				// summary:
				//		Called whenever a page is added to the container.
				//		Create button corresponding to the page.
				// tags:
				//		private

				// create an instance of the button widget
				var cls = dojo.getObject(this.buttonWidget);
				var button = new cls({
					id: this.id + "_" + page.id,
					label: page.title,
					dir: page.dir,
					lang: page.lang,
					showLabel: page.showTitle,
					iconClass: page.iconClass,
					closeButton: page.closable,
					title: page.tooltip
				});
				dijit.setWaiState(button.focusNode,"selected", "false");

				// map from page attribute to corresponding tab button attribute
				var pageAttrList = ["title", "showTitle", "iconClass", "closable", "tooltip"],
					buttonAttrList = ["label", "showLabel", "iconClass", "closeButton", "title"];

				// watch() so events like page title changes are reflected in tab button
				this.pane2watches[page.id] = dojo.map(pageAttrList, function(pageAttr, idx){
					return page.watch(pageAttr, function(name, oldVal, newVal){
						button.set(buttonAttrList[idx], newVal);
					});
				});

				// connections so that clicking a tab button selects the corresponding page
				this.pane2connects[page.id] = [
					this.connect(button, 'onClick', dojo.hitch(this,"onButtonClick", page)),
					this.connect(button, 'onClickCloseButton', dojo.hitch(this,"onCloseButtonClick", page))
				];

				this.addChild(button, insertIndex);
				this.pane2button[page.id] = button;
				page.controlButton = button;	// this value might be overwritten if two tabs point to same container
				if(!this._currentChild){ // put the first child into the tab order
					button.focusNode.setAttribute("tabIndex", "0");
					dijit.setWaiState(button.focusNode, "selected", "true");
					this._currentChild = page;
				}
				// make sure all tabs have the same length
				if(!this.isLeftToRight() && dojo.isIE && this._rectifyRtlTabList){
					this._rectifyRtlTabList();
				}
			},

			onRemoveChild: function(/*dijit._Widget*/ page){
				// summary:
				//		Called whenever a page is removed from the container.
				//		Remove the button corresponding to the page.
				// tags:
				//		private

				if(this._currentChild === page){ this._currentChild = null; }

				// disconnect/unwatch connections/watches related to page being removed
				dojo.forEach(this.pane2connects[page.id], dojo.hitch(this, "disconnect"));
				delete this.pane2connects[page.id];
				dojo.forEach(this.pane2watches[page.id], function(w){ w.unwatch(); });
				delete this.pane2watches[page.id];

				var button = this.pane2button[page.id];
				if(button){
					this.removeChild(button);
					delete this.pane2button[page.id];
					button.destroy();
				}
				delete page.controlButton;
			},

			onSelectChild: function(/*dijit._Widget*/ page){
				// summary:
				//		Called when a page has been selected in the StackContainer, either by me or by another StackController
				// tags:
				//		private

				if(!page){ return; }

				if(this._currentChild){
					var oldButton=this.pane2button[this._currentChild.id];
					oldButton.set('checked', false);
					dijit.setWaiState(oldButton.focusNode, "selected", "false");
					oldButton.focusNode.setAttribute("tabIndex", "-1");
				}

				var newButton=this.pane2button[page.id];
				newButton.set('checked', true);
				dijit.setWaiState(newButton.focusNode, "selected", "true");
				this._currentChild = page;
				newButton.focusNode.setAttribute("tabIndex", "0");
				var container = dijit.byId(this.containerId);
				dijit.setWaiState(container.containerNode, "labelledby", newButton.id);
			},

			onButtonClick: function(/*dijit._Widget*/ page){
				// summary:
				//		Called whenever one of my child buttons is pressed in an attempt to select a page
				// tags:
				//		private

				var container = dijit.byId(this.containerId);
				container.selectChild(page);
			},

			onCloseButtonClick: function(/*dijit._Widget*/ page){
				// summary:
				//		Called whenever one of my child buttons [X] is pressed in an attempt to close a page
				// tags:
				//		private

				var container = dijit.byId(this.containerId);
				container.closeChild(page);
				if(this._currentChild){
					var b = this.pane2button[this._currentChild.id];
					if(b){
						dijit.focus(b.focusNode || b.domNode);
					}
				}
			},

			// TODO: this is a bit redundant with forward, back api in StackContainer
			adjacent: function(/*Boolean*/ forward){
				// summary:
				//		Helper for onkeypress to find next/previous button
				// tags:
				//		private

				if(!this.isLeftToRight() && (!this.tabPosition || /top|bottom/.test(this.tabPosition))){ forward = !forward; }
				// find currently focused button in children array
				var children = this.getChildren();
				var current = dojo.indexOf(children, this.pane2button[this._currentChild.id]);
				// pick next button to focus on
				var offset = forward ? 1 : children.length - 1;
				return children[ (current + offset) % children.length ]; // dijit._Widget
			},

			onkeypress: function(/*Event*/ e){
				// summary:
				//		Handle keystrokes on the page list, for advancing to next/previous button
				//		and closing the current page if the page is closable.
				// tags:
				//		private

				if(this.disabled || e.altKey ){ return; }
				var forward = null;
				if(e.ctrlKey || !e._djpage){
					var k = dojo.keys;
					switch(e.charOrCode){
						case k.LEFT_ARROW:
						case k.UP_ARROW:
							if(!e._djpage){ forward = false; }
							break;
						case k.PAGE_UP:
							if(e.ctrlKey){ forward = false; }
							break;
						case k.RIGHT_ARROW:
						case k.DOWN_ARROW:
							if(!e._djpage){ forward = true; }
							break;
						case k.PAGE_DOWN:
							if(e.ctrlKey){ forward = true; }
							break;
						case k.HOME:
						case k.END:
							var children = this.getChildren();
							if(children && children.length){
								children[e.charOrCode == k.HOME ? 0 : children.length-1].onClick();
							}
							dojo.stopEvent(e);
							break;
						case k.DELETE:
							if(this._currentChild.closable){
								this.onCloseButtonClick(this._currentChild);
							}
							dojo.stopEvent(e);
							break;
						default:
							if(e.ctrlKey){
								if(e.charOrCode === k.TAB){
									this.adjacent(!e.shiftKey).onClick();
									dojo.stopEvent(e);
								}else if(e.charOrCode == "w"){
									if(this._currentChild.closable){
										this.onCloseButtonClick(this._currentChild);
									}
									dojo.stopEvent(e); // avoid browser tab closing.
								}
							}
					}
					// handle next/previous page navigation (left/right arrow, etc.)
					if(forward !== null){
						this.adjacent(forward).onClick();
						dojo.stopEvent(e);
					}
				}
			},

			onContainerKeyPress: function(/*Object*/ info){
				// summary:
				//		Called when there was a keypress on the container
				// tags:
				//		private
				info.e._djpage = info.page;
				this.onkeypress(info.e);
			}
	});

dojo.declare("dijit.layout._StackButton",
		dijit.form.ToggleButton,
		{
		// summary:
		//		Internal widget used by StackContainer.
		// description:
		//		The button-like or tab-like object you click to select or delete a page
		// tags:
		//		private

		// Override _FormWidget.tabIndex.
		// StackContainer buttons are not in the tab order by default.
		// Probably we should be calling this.startupKeyNavChildren() instead.
		tabIndex: "-1",

		// closeButton: Boolean
		//		When true, display close button for this tab
		closeButton: false,

		buildRendering: function(/*Event*/ evt){
			this.inherited(arguments);
			dijit.setWaiRole((this.focusNode || this.domNode), "tab");
		},

		onClick: function(/*Event*/ evt){
			// summary:
			//		This is for TabContainer where the tabs are  rather than button,
			//		so need to set focus explicitly (on some browsers)
			//		Note that you shouldn't override this method, but you can connect to it.
			dijit.focus(this.focusNode);

			// ... now let StackController catch the event and tell me what to do
		},

		onClickCloseButton: function(/*Event*/ evt){
			// summary:
			//		StackContainer connects to this function; if your widget contains a close button
			//		then clicking it should call this function.
			//		Note that you shouldn't override this method, but you can connect to it.
			evt.stopPropagation();
		}
	});

return dijit.layout.StackController;
});
<|endoftext|>


<commit_before>/**
 * The UI Element for importing pedigrees from text representationin various formats
 *
 * @class ImportSelector
 */

define(["pedigree/view/familySelector"], function(Legend){
    var FamilySelector = Class.create( {

        initialize: function(options) {
            this.familyID = null;
            this.selected = null;

            var _this = this;

            this.probandID = editor.getGraph().getCurrentPatientId();
            this.familySearchUrl = editor.getExternalEndpoint().getFamilySearchURL();

            var mainDiv = new Element('div', {'class': 'family-selector'});

            // create radio buttons for selection
            var createLabel = new Element('label', {'class' : 'create-family-label'});
            var assignLabel = new Element('label', {'class' : 'assign-family-label'});

            var createFamily =  new Element('input', {'type' : 'radio', 'id': 'pedigreeInputCreateFamily', 'name' : 'select-family', 'value' : 'create'});
            var assignFamily =  new Element('input', {'type' : 'radio', 'id': 'pedigreeInputAssignFamily', 'name' : 'select-family', 'value' : 'assign'});
            createFamily.observe('click', this.selectOptions.bind(this) );
            assignFamily.observe('click', this.selectOptions.bind(this) );

            createLabel.insert(createFamily).insert("Create a new family");
            assignLabel.insert(assignFamily).insert("$services.localization.render('phenotips.UIXField.family_membership.add')");
            var ul = new Element('ul');
            ul.insert(createLabel.wrap('li', {'class' : 'left-aligned'})).insert(assignLabel.wrap('li', {'class' : 'left-aligned'}));
            mainDiv.insert(ul);

            /*
               //create family warning
               var block = new Element('div');
               block.update("The pedigree is shared by all members of this family. Patient records may have collaborators. Adding an existing patient to this family will grant all collaborators from that patient access to all family members' records. Also, all collaborators will be able to edit that patient's record.");
               mainDiv.insert(block.wrap('div', {'id' : 'new-family-warning', 'class' : 'box warningmessage'}));
            */

            // input field that will suggest families upon typing
            var searchBox = new Element('div', {'class': 'half-width'});
            this.searchInput = new Element('input', {'type': 'text', 'id' : 'family-search-input', 'class' : 'family-search-input', 'placeholder' : 'Enter a family name'});
            searchBox.insert(this.searchInput).insert(new Element('span', {'class' : 'clear'}).wrap('div', {'class': 'add-to-family-wrapper'}));
            mainDiv.insert(searchBox);

            this.searchInput._suggest = new PhenoTips.widgets.Suggest(this.searchInput, {
                script: this.familySearchUrl + "&json=true&",
                varname: "input",
                noresults: "No matching terms",
                resultsParameter: "matchedFamilies",
                json: true,
                resultId: "id",
                resultValue: "textSummary",
                enableHierarchy: false,
                fadeOnClear: false,
                timeout: 30000,
                parentContainer: $$('.pedigree-family-chooser')[0]
            });

            this.searchInput.addClassName('initialized');
            this.searchInput.observe("focus", function (event) {
                $('pedigreeInputAssignFamily').click();
            });

            this._onClickOutsideSuggest = this._onClickOutsideSuggest.bindAsEventListener(this);
            this._onSelectedFamily = this._onSelectedFamily.bindAsEventListener(this);

            document.observe("ms:suggest:containerCreated", function(event) {
                if (event.memo && event.memo.suggest === _this.searchInput._suggest) {
                    _this.searchInput._suggest.container.setStyle({'z-index': 100015});
                }
            });

            var buttons = new Element('div', {'class' : 'buttons', 'style' : 'margin-top: 10px;'});
            this.okButton = new Element('input', {'type': 'button', 'name' : 'ok', 'value' : ' OK ', 'class' : 'button'});
            this.okButton.setStyle({"min-width": "140px"});
            this.quitButton = new Element('input', {'type': 'button', 'name' : 'quit', 'value' : ' Close pedigree editor ', 'class' : 'button secondary'});
            this.quitButton.setStyle({"marginLeft": "10px"});
            buttons.insert(this.okButton.wrap('span', {'class' : 'buttonwrapper'}));
            buttons.insert(this.quitButton.wrap('span', {'class' : 'buttonwrapper'}));
            mainDiv.insert(buttons);

            this.okButton.disable();

            this.okButton.observe('click', this.onSelectOK.bind(this) );
            this.quitButton.observe('click', this.quit.bind(this) );

            this.dialog = new PhenoTips.widgets.ModalPopup(mainDiv, {'close': {'method': null, 'keys': []} }, {'extraClassName' : "pedigree-family-chooser", title: 'Assign patient to a family', 'displayCloseButton' : false});

            //$('new-family-warning').hide();
        },

        familySelected: function (event) {
            this.familyID = event.memo.id;
            console.log("select, ID: " + this.familyID);
            this.okButton.enable();
        },

        selectOptions: function() {
            this.selected = $$('input:checked[type=radio][name="select-family"]')[0].value;
            if (this.selected == "assign") {
                $('family-search-input').value = this.familyID;
                if (this.familyID == null || this.familyID == '') {
                    this.okButton.disable();
                } else {
                    this.okButton.enable();
                }
                //$('new-family-warning').show();
            } else {
                this.okButton.enable();
                $('family-search-input').value = "";
                //$('new-family-warning').hide();
            }
        },

        /**
         * Displays the family selector
         *
         * @method show
         */
        show: function() {
            this.dialog.show();
            document.observe('mousedown', this._onClickOutsideSuggest);
            document.observe("ms:suggest:selected", this._onSelectedFamily);
        },

        hide: function() {
            this.dialog.closeDialog();
            document.stopObserving("ms:suggest:selected", this._onSelectedFamily);
            document.stopObserving('mousedown', this._onClickOutsideSuggest);
        },

        _onClickOutsideSuggest: function (event) {
            if (!event.findElement('.suggestItems')) {
                this._hideSuggestPicker();
            }
        },

        _hideSuggestPicker: function() {
            this.searchInput._suggest.clearSuggestions();
        },

        _onSelectedFamily: function(event) {
            if (event.memo && event.memo.suggest === this.searchInput._suggest) {
                this.familySelected(event);
            }
        },

        /**
         * Closes pedigree editor
         */
        quit: function() {
            window.location = XWiki.currentDocument.getURL(XWiki.contextaction);
        },

        /**
         * Removes the family selector
         *
         * @method hide
         */
        onSelectOK: function() {

            this.familyID = $('family-search-input').value || this.familyID;

            if (this.selected == null || this.selected == 'assign' && (this.familyID == null || this.familyID == '')) {

                // warn user that he did not finish work ask if he really want to leave
                // if yes - close pedigree and redirect to the patient sheet form

                var continueFunc = function() {};
                editor.getOkCancelDialogue().showCustomized( "The patient has not been assigned to any family and can't contain a pedigree, do you want to close pedigree editor?", 'Quit pedigree editor?',
                                                             'Select a family', continueFunc,
                                                             'Close', this.quit);
            } else if (this.selected == 'create') {

                this.hide();

                editor.getPatientLegend().addCase(this.probandID, 'new');

                editor.__justCreateNewFamily = true;
                editor.getSaveLoadEngine().initializeNewPedigree();

            } else if (this.selected == 'assign' && this.familyID != null && this.familyID != '') {

                this.hide();

                var pedigreeEditorURL = editor.getExternalEndpoint().getPedigreeEditorURL(this.familyID, true);
                editor.getExternalEndpoint().redirectToURL(pedigreeEditorURL + '&new_patient_id=' + editor.getExternalEndpoint().getParentDocument().id);
          }
        }
    });
    return FamilySelector;
});<commit_msg>PT-1548: [misc] documentation correction<commit_after>/**
 * The UI Element for assigning patient to a new or existing family.
 *
 * @class FamilySelector
 */

define(["pedigree/view/familySelector"], function(Legend){
    var FamilySelector = Class.create( {

        initialize: function(options) {
            this.familyID = null;
            this.selected = null;

            var _this = this;

            this.probandID = editor.getGraph().getCurrentPatientId();
            this.familySearchUrl = editor.getExternalEndpoint().getFamilySearchURL();

            var mainDiv = new Element('div', {'class': 'family-selector'});

            // create radio buttons for selection
            var createLabel = new Element('label', {'class' : 'create-family-label'});
            var assignLabel = new Element('label', {'class' : 'assign-family-label'});

            var createFamily =  new Element('input', {'type' : 'radio', 'id': 'pedigreeInputCreateFamily', 'name' : 'select-family', 'value' : 'create'});
            var assignFamily =  new Element('input', {'type' : 'radio', 'id': 'pedigreeInputAssignFamily', 'name' : 'select-family', 'value' : 'assign'});
            createFamily.observe('click', this.selectOptions.bind(this) );
            assignFamily.observe('click', this.selectOptions.bind(this) );

            createLabel.insert(createFamily).insert("Create a new family");
            assignLabel.insert(assignFamily).insert("$services.localization.render('phenotips.UIXField.family_membership.add')");
            var ul = new Element('ul');
            ul.insert(createLabel.wrap('li', {'class' : 'left-aligned'})).insert(assignLabel.wrap('li', {'class' : 'left-aligned'}));
            mainDiv.insert(ul);

            /*
               //create family warning
               var block = new Element('div');
               block.update("The pedigree is shared by all members of this family. Patient records may have collaborators. Adding an existing patient to this family will grant all collaborators from that patient access to all family members' records. Also, all collaborators will be able to edit that patient's record.");
               mainDiv.insert(block.wrap('div', {'id' : 'new-family-warning', 'class' : 'box warningmessage'}));
            */

            // input field that will suggest families upon typing
            var searchBox = new Element('div', {'class': 'half-width'});
            this.searchInput = new Element('input', {'type': 'text', 'id' : 'family-search-input', 'class' : 'family-search-input', 'placeholder' : 'Enter a family name'});
            searchBox.insert(this.searchInput).insert(new Element('span', {'class' : 'clear'}).wrap('div', {'class': 'add-to-family-wrapper'}));
            mainDiv.insert(searchBox);

            this.searchInput._suggest = new PhenoTips.widgets.Suggest(this.searchInput, {
                script: this.familySearchUrl + "&json=true&",
                varname: "input",
                noresults: "No matching terms",
                resultsParameter: "matchedFamilies",
                json: true,
                resultId: "id",
                resultValue: "textSummary",
                enableHierarchy: false,
                fadeOnClear: false,
                timeout: 30000,
                parentContainer: $$('.pedigree-family-chooser')[0]
            });

            this.searchInput.addClassName('initialized');
            this.searchInput.observe("focus", function (event) {
                $('pedigreeInputAssignFamily').click();
            });

            this._onClickOutsideSuggest = this._onClickOutsideSuggest.bindAsEventListener(this);
            this._onSelectedFamily = this._onSelectedFamily.bindAsEventListener(this);

            document.observe("ms:suggest:containerCreated", function(event) {
                if (event.memo && event.memo.suggest === _this.searchInput._suggest) {
                    _this.searchInput._suggest.container.setStyle({'z-index': 100015});
                }
            });

            var buttons = new Element('div', {'class' : 'buttons', 'style' : 'margin-top: 10px;'});
            this.okButton = new Element('input', {'type': 'button', 'name' : 'ok', 'value' : ' OK ', 'class' : 'button'});
            this.okButton.setStyle({"min-width": "140px"});
            this.quitButton = new Element('input', {'type': 'button', 'name' : 'quit', 'value' : ' Close pedigree editor ', 'class' : 'button secondary'});
            this.quitButton.setStyle({"marginLeft": "10px"});
            buttons.insert(this.okButton.wrap('span', {'class' : 'buttonwrapper'}));
            buttons.insert(this.quitButton.wrap('span', {'class' : 'buttonwrapper'}));
            mainDiv.insert(buttons);

            this.okButton.disable();

            this.okButton.observe('click', this.onSelectOK.bind(this) );
            this.quitButton.observe('click', this.quit.bind(this) );

            this.dialog = new PhenoTips.widgets.ModalPopup(mainDiv, {'close': {'method': null, 'keys': []} }, {'extraClassName' : "pedigree-family-chooser", title: 'Assign patient to a family', 'displayCloseButton' : false});

            //$('new-family-warning').hide();
        },

        familySelected: function (event) {
            this.familyID = event.memo.id;
            console.log("select, ID: " + this.familyID);
            this.okButton.enable();
        },

        selectOptions: function() {
            this.selected = $$('input:checked[type=radio][name="select-family"]')[0].value;
            if (this.selected == "assign") {
                $('family-search-input').value = this.familyID;
                if (this.familyID == null || this.familyID == '') {
                    this.okButton.disable();
                } else {
                    this.okButton.enable();
                }
                //$('new-family-warning').show();
            } else {
                this.okButton.enable();
                $('family-search-input').value = "";
                //$('new-family-warning').hide();
            }
        },

        /**
         * Displays the family selector
         *
         * @method show
         */
        show: function() {
            this.dialog.show();
            document.observe('mousedown', this._onClickOutsideSuggest);
            document.observe("ms:suggest:selected", this._onSelectedFamily);
        },

        hide: function() {
            this.dialog.closeDialog();
            document.stopObserving("ms:suggest:selected", this._onSelectedFamily);
            document.stopObserving('mousedown', this._onClickOutsideSuggest);
        },

        _onClickOutsideSuggest: function (event) {
            if (!event.findElement('.suggestItems')) {
                this._hideSuggestPicker();
            }
        },

        _hideSuggestPicker: function() {
            this.searchInput._suggest.clearSuggestions();
        },

        _onSelectedFamily: function(event) {
            if (event.memo && event.memo.suggest === this.searchInput._suggest) {
                this.familySelected(event);
            }
        },

        /**
         * Closes pedigree editor
         */
        quit: function() {
            window.location = XWiki.currentDocument.getURL(XWiki.contextaction);
        },

        /**
         * Removes the family selector
         *
         * @method hide
         */
        onSelectOK: function() {

            this.familyID = $('family-search-input').value || this.familyID;

            if (this.selected == null || this.selected == 'assign' && (this.familyID == null || this.familyID == '')) {

                // warn user that he did not finish work ask if he really want to leave
                // if yes - close pedigree and redirect to the patient sheet form

                var continueFunc = function() {};
                editor.getOkCancelDialogue().showCustomized( "The patient has not been assigned to any family and can't contain a pedigree, do you want to close pedigree editor?", 'Quit pedigree editor?',
                                                             'Select a family', continueFunc,
                                                             'Close', this.quit);
            } else if (this.selected == 'create') {

                this.hide();

                editor.getPatientLegend().addCase(this.probandID, 'new');

                editor.__justCreateNewFamily = true;
                editor.getSaveLoadEngine().initializeNewPedigree();

            } else if (this.selected == 'assign' && this.familyID != null && this.familyID != '') {

                this.hide();

                var pedigreeEditorURL = editor.getExternalEndpoint().getPedigreeEditorURL(this.familyID, true);
                editor.getExternalEndpoint().redirectToURL(pedigreeEditorURL + '&new_patient_id=' + editor.getExternalEndpoint().getParentDocument().id);
          }
        }
    });
    return FamilySelector;
});
<|endoftext|>


<commit_before>var dat = require("dat.gui/build/dat.gui.min.js");

var FilterOverlay = module.exports = function (tags, filterFunction) {
    var scope = this;
    this.boolTags = [];
    this.tags = tags;
    this.gui = new dat.GUI();

    this.Init = function () {
        this.createBoolArray(this.tags);
        this.createGUI();

    }

    this.createBoolArray = function () {
        //1 because filenames are at zero
        for (var i = 1; i < this.tags.length; i++) {
            var boolObj = {
                key: this.tags[i].key,
                values: {}
            };

            for (var j = 0; j < this.tags[i].values.length; j++) {
                boolObj.values[this.tags[i].values[j].value] = false;
            }
            this.boolTags.push(boolObj);

        }
    }

    this.createGUI = function () {
        for (var i = 0; i < this.boolTags.length; i++) {
            var tag = this.boolTags[i];
            var folder = this.gui.addFolder(tag.key);
            for (var property in tag.values) {
                if (tag.values.hasOwnProperty(property)) {
                    folder.add(tag.values, property).listen();
                }

            }
        }
        var filter = this.filterButton;
        var clear = this.clearAllButton;
        this.gui.add(clear, 'ClearAll');
        this.gui.add(filter, 'Filter');
        var doc = document.getElementById('overlay');
        doc.appendChild(this.gui.domElement);
    }

    this.filterButton = {
        Filter: function () {
            filterFunction(scope.createFilterData());
        }
    };

    this.clearAllButton = {
        ClearAll: function () {
            for (var i = 0; i < scope.boolTags.length; i++) {
                var tag = scope.boolTags[i];
                for (var property in tag.values) {
                    if (tag.values.hasOwnProperty(property)) {
                        tag.values[property] = false;
                    }
                }
            }
            scope.update();
            filterFunction(null);
        }
    }

    this.createFilterData = function () {
        var data = [];
        for (var i = 0; i < this.boolTags.length; i++) {
            var isUsed = false;
            var tag = this.boolTags[i];
            var obj = {
                key: this.boolTags[i].key,
                values: []
            };
            for (var property in tag.values) {
                if (tag.values.hasOwnProperty(property) && tag.values[property]) {
                    obj.values.push(property);
                    isUsed = true;
                }

            }
            if (isUsed) {
                data.push(obj);
            }
        }
        if (data.length === 0) {
            return this.returnAll();
        }
        return data;
    }

    this.returnAll = function () {
        var data = [];
        for (var i = 0; i < this.boolTags.length; i++) {
            var tag = this.boolTags[i];
            var obj = {
                key: this.boolTags[i].key,
                values: []
            };
            for (var property in tag.values) {
                if(tag.values.hasOwnProperty(property)){
                    obj.values.push(property);
                }
            }
            data.push(obj);
        }
        return data;
    }

    this.update = function () {
        for (var i = 0; i < Object.keys(scope.gui.__folders).length; i++) {
            var key = Object.keys(scope.gui.__folders)[i];
            for (var j = 0; j < scope.gui.__folders[key].__controllers.length; j++) {
                scope.gui.__folders[key].__controllers[j].updateDisplay();
            }
        }
    }

    this.Init();
}
<commit_msg>see previous<commit_after>var dat = require("dat.gui/build/dat.gui.min.js");

var FilterOverlay = module.exports = function (tags, filterFunction) {
    var scope = this;
    this.boolTags = [];
    this.tags = tags;
    this.gui = new dat.GUI();

    this.Init = function () {
        this.createBoolArray(this.tags);
        this.createGUI();

    }

    this.createBoolArray = function () {
        //1 because filenames are at zero
        for (var i = 1; i < this.tags.length; i++) {
            var boolObj = {
                key: this.tags[i].key,
                values: {}
            };

            for (var j = 0; j < this.tags[i].values.length; j++) {
                boolObj.values[this.tags[i].values[j].value] = false;
            }
            this.boolTags.push(boolObj);

        }
    }

    this.createGUI = function () {
        for (var i = 0; i < this.boolTags.length; i++) {
            var tag = this.boolTags[i];
            var folder = this.gui.addFolder(tag.key);
            for (var property in tag.values) {
                if (tag.values.hasOwnProperty(property)) {
                    folder.add(tag.values, property).listen();
                }

            }
        }
        var filter = this.filterButton;
        var clear = this.clearAllButton;
        this.gui.add(clear, 'ClearAll');
        this.gui.add(filter, 'Filter');
        var doc = document.getElementById('overlay');
        doc.appendChild(this.gui.domElement);
    }

    this.filterButton = {
        Filter: function () {
            filterFunction(scope.createFilterData());
        }
    };

    this.clearAllButton = {
        ClearAll: function () {
            for (var i = 0; i < scope.boolTags.length; i++) {
                var tag = scope.boolTags[i];
                for (var property in tag.values) {
                    if (tag.values.hasOwnProperty(property)) {
                        tag.values[property] = false;
                    }
                }
            }
            scope.update();
            filterFunction(null);
        }
    }

    this.createFilterData = function () {
        var data = [];
        for (var i = 0; i < this.boolTags.length; i++) {
            var isUsed = false;
            var tag = this.boolTags[i];
            var obj = {
                key: this.boolTags[i].key,
                values: []
            };
            for (var property in tag.values) {
                if (tag.values.hasOwnProperty(property) && tag.values[property]) {
                    obj.values.push(property);
                    isUsed = true;
                }

            }
            if (isUsed) {
                data.push(obj);
            }
        }
        if (data.length === 0) {
            return null; //this.returnAll();

        }
        return data;
    }

    this.returnAll = function () {
        var data = [];
        for (var i = 0; i < this.boolTags.length; i++) {
            var tag = this.boolTags[i];
            var obj = {
                key: this.boolTags[i].key,
                values: []
            };
            for (var property in tag.values) {
                if(tag.values.hasOwnProperty(property)){
                    obj.values.push(property);
                }
            }
            data.push(obj);
        }
        return data;
    }

    this.update = function () {
        for (var i = 0; i < Object.keys(scope.gui.__folders).length; i++) {
            var key = Object.keys(scope.gui.__folders)[i];
            for (var j = 0; j < scope.gui.__folders[key].__controllers.length; j++) {
                scope.gui.__folders[key].__controllers[j].updateDisplay();
            }
        }
    }

    this.Init();
}
<|endoftext|>


<commit_before>L.Polyline.Measure = L.Draw.Polyline.extend({
    addHooks: function() {
        L.Draw.Polyline.prototype.addHooks.call(this);
        if (this._map) {
            this._markerGroup = new L.LayerGroup();
            this._map.addLayer(this._markerGroup);

            this._markers = [];
            this._map.on('click', this._onClick, this);
            this._startShape();
        }
    },

    removeHooks: function () {
        L.Draw.Polyline.prototype.removeHooks.call(this);

        this._clearHideErrorTimeout();

        //!\ Still useful when control is disabled before any drawing (refactor needed?)
        this._map.off('mousemove', this._onMouseMove);
        this._clearGuides();
        this._container.style.cursor = '';

        this._removeShape();

        this._map.off('click', this._onClick, this);
    },

    _startShape: function() {
        this._drawing = true;
        this._poly = new L.Polyline([], this.options.shapeOptions);
        //this is added as a placeholder, if leaflet doesn't recieve this when the tool is turned off all onclick events are removed
        this._poly._onClick = function() {};

        this._container.style.cursor = 'crosshair';

        this._updateTooltip();
        this._map.on('mousemove', this._onMouseMove, this);
    },

    _finishShape: function () {
        this._drawing = false;

        this._cleanUpShape();
        this._clearGuides();

        this._updateTooltip();

        this._map.off('mousemove', this._onMouseMove, this);
        this._container.style.cursor = '';
    },

    _removeShape: function() {
        if (!this._poly)
            return;
        this._map.removeLayer(this._poly);
        delete this._poly;
        this._markers.splice(0);
        this._markerGroup.clearLayers();
    },

    _onClick: function(e) {
        if (!this._drawing) {
            this._removeShape();
            this._startShape();
            return;
        }
    },

    _getTooltipText: function() {
        var labelText = L.Draw.Polyline.prototype._getTooltipText.call(this);
        if (!this._drawing) {
            labelText.text = '';
        }
        return labelText;
    }
});

L.Control.MeasureControl = L.Control.extend({

    statics: {
        TITLE: 'Measure distances'
    },
    options: {
        position: 'topleft',
        handler: {}
    },

    toggle: function() {
        if (this.handler.enabled()) {
            this.handler.disable.call(this.handler);
        } else {
            this.handler.enable.call(this.handler);
        }
    },

    onAdd: function(map) {
        var className = 'leaflet-control-draw';

        this._container = L.DomUtil.create('div', 'leaflet-bar');

        this.handler = new L.Polyline.Measure(map, this.options.handler);

        this.handler.on('enabled', function () {
            L.DomUtil.addClass(this._container, 'enabled');
        }, this);

        this.handler.on('disabled', function () {
            L.DomUtil.removeClass(this._container, 'enabled');
        }, this);

        var link = L.DomUtil.create('a', className+'-measure', this._container);
        link.href = '#';
        link.title = L.Control.MeasureControl.TITLE;

        L.DomEvent
            .addListener(link, 'click', L.DomEvent.stopPropagation)
            .addListener(link, 'click', L.DomEvent.preventDefault)
            .addListener(link, 'click', this.toggle, this);

        return this._container;
    }
});

L.Map.mergeOptions({
    measureControl: false
});

L.Map.addInitHook(function () {
    if (this.options.measureControl) {
        this.measureControl = L.Control.measureControl().addTo(this);
    }
});

L.Control.measureControl = function (options) {
    return new L.Control.MeasureControl(options);
};

<commit_msg>cleanup<commit_after>L.Polyline.Measure = L.Draw.Polyline.extend({
    addHooks: function() {
        L.Draw.Polyline.prototype.addHooks.call(this);
        if (this._map) {
            this._markerGroup = new L.LayerGroup();
            this._map.addLayer(this._markerGroup);

            this._markers = [];
            this._map.on('click', this._onClick, this);
            this._startShape();
        }
    },

    removeHooks: function () {
        L.Draw.Polyline.prototype.removeHooks.call(this);

        this._clearHideErrorTimeout();

        //!\ Still useful when control is disabled before any drawing (refactor needed?)
        this._map
            .off('pointermove', this._onMouseMove, this)
            .off('mousemove', this._onMouseMove, this)
            .off('click', this._onClick, this);

        this._clearGuides();
        this._container.style.cursor = '';

        this._removeShape();
    },

    _startShape: function() {
        this._drawing = true;
        this._poly = new L.Polyline([], this.options.shapeOptions);
        //this is added as a placeholder, if leaflet doesn't recieve this when the tool is turned off all onclick events are removed
        this._poly._onClick = function() {};

        this._container.style.cursor = 'crosshair';

        this._updateTooltip();
        this._map
            .on('pointermove', this._onMouseMove, this)
            .on('mousemove', this._onMouseMove, this);
    },

    _finishShape: function () {
        this._drawing = false;

        this._cleanUpShape();
        this._clearGuides();

        this._updateTooltip();

        this._map
            .off('pointermove', this._onMouseMove, this)
            .off('mousemove', this._onMouseMove, this);

        this._container.style.cursor = '';
    },

    _removeShape: function() {
        if (!this._poly)
            return;
        this._map.removeLayer(this._poly);
        delete this._poly;
        this._markers.splice(0);
        this._markerGroup.clearLayers();
    },

    _onClick: function(e) {
        if (!this._drawing) {
            this._removeShape();
            this._startShape();
            return;
        }
    },

    _getTooltipText: function() {
        var labelText = L.Draw.Polyline.prototype._getTooltipText.call(this);
        if (!this._drawing) {
            labelText.text = '';
        }
        return labelText;
    }
});

L.Control.MeasureControl = L.Control.extend({

    statics: {
        TITLE: 'Measure distances'
    },
    options: {
        position: 'topleft',
        handler: {}
    },

    toggle: function() {
        if (this.handler.enabled()) {
            this.handler.disable.call(this.handler);
        } else {
            this.handler.enable.call(this.handler);
        }
    },

    onAdd: function(map) {
        var className = 'leaflet-control-draw';

        this._container = L.DomUtil.create('div', 'leaflet-bar');

        this.handler = new L.Polyline.Measure(map, this.options.handler);

        this.handler.on('enabled', function () {
            L.DomUtil.addClass(this._container, 'enabled');
        }, this);

        this.handler.on('disabled', function () {
            L.DomUtil.removeClass(this._container, 'enabled');
        }, this);

        var link = L.DomUtil.create('a', className+'-measure', this._container);
        link.href = '#';
        link.title = L.Control.MeasureControl.TITLE;

        L.DomEvent
            .addListener(link, 'click', L.DomEvent.stopPropagation)
            .addListener(link, 'click', L.DomEvent.preventDefault)
            .addListener(link, 'click', this.toggle, this);

        return this._container;
    }
});

L.Map.mergeOptions({
    measureControl: false
});

L.Map.addInitHook(function () {
    if (this.options.measureControl) {
        this.measureControl = L.Control.measureControl().addTo(this);
    }
});

L.Control.measureControl = function (options) {
    return new L.Control.MeasureControl(options);
};

<|endoftext|>


<commit_before>var JapanPortfolio = (function() {

  var $portfolio;
  var isPortfolioActive = false;

  function init() {

    if (isActive()) {
      $('#tab_portfolio').removeClass('invisible');
    }

    var $container = $('#tab_portfolio-content');
    $portfolio = $portfolio || $('#portfolio');

    if ($portfolio &&
      (!$('#portfolio').parent().length ||
        $('#portfolio').parent().get(0).id !== 'tab_portfolio-content')) {
      $portfolio.detach();
      $container.append($portfolio);
    }
  }

  function show() {
    if (JPTradePage.isJapan() && !isPortfolioActive) {
      PortfolioWS.onLoad();
      isPortfolioActive = true;
    }

    return;
  }

  function isActive() {
    if (page.client.is_logged_in && JPTradePage.isJapan()) {
      return true;
    }
  }

  function hide() {
    if (JPTradePage.isJapan() && isPortfolioActive) {
      PortfolioWS.onUnload();
      isPortfolioActive = false;
    }

    return;
  }

  return {
    init: init,
    show: show,
    hide: hide,
    isActive: isActive,
  };
})();

module.exports = {
    JapanPortfolio: JapanPortfolio,
};
<commit_msg>Fix portfolio tab<commit_after>var JapanPortfolio = (function() {

  var $portfolio;
  var isPortfolioActive = false;

  function init() {

    if (isActive()) {
      $('#tab_portfolio').removeClass('invisible');
    }

    var $container = $('#tab_portfolio-content');
    $portfolio = $portfolio || $('#portfolio');

    if ($portfolio &&
      (!$('#portfolio').parent().length ||
        $('#portfolio').parent().get(0).id !== 'tab_portfolio-content')) {
      $portfolio.detach();
      $container.append($portfolio);
    }
  }

  function show() {
    if (isTradePage() && !isPortfolioActive) {
      PortfolioWS.onLoad();
      isPortfolioActive = true;
    }

    return;
  }

  function isActive() {
    if (page.client.is_logged_in && isTradePage()) {
      return true;
    }
  }

  function hide() {
    if (isTradePage() && isPortfolioActive) {
      PortfolioWS.onUnload();
      isPortfolioActive = false;
    }

    return;
  }

  function isTradePage() {
    return (JPTradePage.isJapan() || MBTradePage.is_trading_page());
  }

  return {
    init: init,
    show: show,
    hide: hide,
    isActive: isActive,
  };
})();

module.exports = {
    JapanPortfolio: JapanPortfolio,
};
<|endoftext|>


<commit_before>/**
 * PROJECT: jsTreeNodePicker
 * Version: 0.2
 * Note:    Recommended for Bootstrap >=3, JQuery >=1.11.3, JQuery UI >=1.11.4, tagit >=2.0, jsTree >=3.2.1
 * AUTHOR:  (Jason Steve Nguyen) Hau Nguyen Viet
 * Email:   nvconghau1995@gmail.com
 * (c) 2016 Hau Nguyen Viet.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

(function( $ ) {

    $.fn.jsTreeNodePicker = function(options ) {

        var opts = $.extend( {}, $.fn.jsTreeNodePicker.defaults, options);
        var modalSelector;
        var btnOpen;
        var treeControl;
        var tagitControl;
        var errorMessageContainer;

        var pickerObj = this.each(function() {
            modalSelector = $("#"+opts.dialogId);

            // Append open picker dialog button
            var btnOpenContainer = $('

');
            $(this).append(btnOpenContainer);
            btnOpen = $('<button id="btnOpen'+opts.dialogId+'" type="button" class="btn btn-default" '
                + ' data-toggle="modal" data-target="#'+opts.dialogId+'"> </button>');

            btnOpenContainer.append(btnOpen);

            var modalBody = modalSelector.children(".modal-dialog").children(".modal-content").children(".modal-body");
            modalBody.css(opts.sizeCSS);

            // Add place to show error message
            errorMessageContainer = $('

');
            modalBody.append(errorMessageContainer);

            var treeControlId = opts.dialogId + "_treeControl";
            var treeControlContainer = $('

');
            modalBody.append(treeControlContainer);
            treeControl = $('

');

            treeControlContainer.append(treeControl);

            treeControl.jstree({
                'core' : {
                    'data' : opts.data
                },
                "checkbox" : opts.jstreeOptions.checkbox,
                "plugins" : opts.jstreeOptions.plugins
            });

            treeControl.bind("loaded.jstree", function (event, data) {
                if (opts.expandAllNodes === true) {
                    $(this).jstree("open_all");
                } else {
                    $(this).jstree("close_all");
                }

            });

            // Append tagit control
            var tagitControlContainer = $('

');
            $(this).append(tagitControlContainer);

            tagitControl = $('

');
            tagitControlContainer.append(tagitControl);
            tagitControl.tagit({
                fieldName: opts.tagitOptions.fieldName,
                allowSpaces: opts.tagitOptions.allowSpaces,
                tagLimit: opts.tagLimit,
                showAutocompleteOnFocus:  opts.tagitOptions.showAutocompleteOnFocus,
                readOnly: opts.tagitOptions.readOnly
            });

            if (opts.selectedNodes.length > 0) {
                tagitControl.tagit("removeAll");
                for (x in opts.selectedNodes) {
                    tagitControl.tagit('createTag', opts.selectedNodes[x]);

                }
            }

        });

        pickerObj.modalSelector = modalSelector;
        pickerObj.btnOpen = btnOpen;
        pickerObj.treeControl = treeControl;
        pickerObj.tagitControl = tagitControl;
        pickerObj.errorMessageContainer = errorMessageContainer;

        pickerObj.opts = $.extend({}, opts);

        pickerObj.btnClearAll = pickerObj.modalSelector.children(".modal-dialog").children(".modal-content")
                                .children(".modal-footer").children(".btnTreeNodePickerClearAll");

        pickerObj.btnOK = pickerObj.modalSelector.children(".modal-dialog").children(".modal-content")
                                        .children(".modal-footer").children(".btnTreeNodePickerOK");
        pickerObj.btnCancel = pickerObj.modalSelector.children(".modal-dialog").children(".modal-content")
                                                .children(".modal-footer").children(".btnTreeNodePickerCancel");

        pickerObj.dialogTitle = pickerObj.modalSelector.children(".modal-dialog").children(".modal-content")
                                                .children(".modal-header").children(".modal-title");

        pickerObj.btnClearAll.text(pickerObj.opts.labels.buttons.btn_clear_all);
        pickerObj.btnOK.text(pickerObj.opts.labels.buttons.btn_ok);
        pickerObj.btnCancel.text(pickerObj.opts.labels.buttons.btn_cancel);
        pickerObj.btnCancel.text(pickerObj.opts.labels.buttons.btn_cancel);
        pickerObj.btnOpen.text(pickerObj.opts.labels.buttons.btn_open);
        pickerObj.dialogTitle.text(pickerObj.opts.labels.text.label_title);

        pickerObj.btnClearAll.click(function() {
             pickerObj.treeControl.jstree("deselect_all");
        });

        pickerObj.btnOK.click(function(){

            var selectedNodes = pickerObj.treeControl.jstree("get_selected");
            if (selectedNodes.length > pickerObj.opts.tagLimit) {
                return false;
            }
            pickerObj.tagitControl.tagit("removeAll");
            for (x in selectedNodes) {
                pickerObj.tagitControl.tagit('createTag', selectedNodes[x]);

            }

            pickerObj.modalSelector.modal("toggle");
            pickerObj.opts.selectedNodes = selectedNodes;
        });

        pickerObj.btnOpen.click(function () {
            pickerObj.treeControl.jstree(true).deselect_all();
            for (x in pickerObj.opts.selectedNodes) {
                treeControl.jstree(true).select_node(pickerObj.opts.selectedNodes[x]);
            }
            if (opts.expandAllNodes === true) {
               pickerObj.treeControl.jstree("open_all");
            } else {
               pickerObj.treeControl.jstree("close_all");
            }
        });

        pickerObj.treeControl.on("changed.jstree", function (e, data) {
            if (data.selected.length > pickerObj.opts.tagLimit) {
                pickerObj.errorMessageContainer.text(pickerObj.opts.errMessages.err_you_can_not_pick_more_than
                    + ' ' + pickerObj.opts.tagLimit + ' ' + pickerObj.opts.labels.text.label_node);
                pickerObj.errorMessageContainer.show();
            } else {
                pickerObj.errorMessageContainer.hide();
            }

        });

        if (pickerObj.opts.expandChildOnSingleClick === true) {
            pickerObj.treeControl.on("select_node.jstree", function (e, data) {
                if(data.node.state.opened == true) {
                    pickerObj.treeControl.jstree(true).close_node(data.node);
//                    node.state.opened = false;
               } else {
                    pickerObj.treeControl.jstree(true).open_node(data.node);
//                    node.state.opened = true;
               }
            });
            /* pickerObj.treeControl.on("click",function (e) {
              var li = $(e.target).closest("li");
              var node =  pickerObj.treeControl.jstree(true).get_node(li[0].id);

              console.log(node.state.opened);

               if(node.state.opened == true) {
                    pickerObj.treeControl.jstree(true).close_node(node);
                    node.state.opened = false;
               } else {
                    pickerObj.treeControl.jstree(true).open_node(node);
                    node.state.opened = true;
               }
            });*/
        }

        return pickerObj;

    }

    $.fn.jsTreeNodePicker.defaults = {
        "sizeCSS": {
            "min-height": "300px",
            "max-height": "300px",
            "height": "300px",
            "min-width": "600px",
            "max-width": "600px",
            "width": "600px",
        },
        "dialogId": "pickerDlg",
        "expandChildOnSingleClick": true,
        "tagLimit": 5,
        "expandAllNodes": true,
        "data": [],
        "selectedNodes": [],
        "tagitOptions": {
            "fieldName": "tagList",
            "allowSpaces": true,
            "showAutocompleteOnFocus": false,
            "readOnly": true
        },
        "jstreeOptions": {
            "checkbox" : {
                "keep_selected_style" : false,
                "three_state": false
            },
            "plugins" : [ "checkbox" ]
        },
        "labels": {
            "buttons": {
                "btn_ok": "OK",
                "btn_cancel": "Cancel",
                "btn_clear_all": "Clear All",
                "btn_open": "Click here to choose nodes"
            },
            "text": {
                "label_title": "Choose nodes",
                "label_node": "node"
            }

        },
        "errMessages": {
            "err_you_can_not_pick_more_than": "You cannot pick more than"
        }
    };

}( jQuery ));<commit_msg>new update<commit_after>/**
 * PROJECT: jsTreeNodePicker
 * Version: 0.2
 * Note:    Recommended for Bootstrap >=3, JQuery >=1.11.3, JQuery UI >=1.11.4, tagit >=2.0, jsTree >=3.2.1
 * AUTHOR:  (Jason Steve Nguyen) Hau Nguyen Viet
 * Email:   nvconghau1995@gmail.com
 * (c) 2016 Hau Nguyen Viet.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

(function( $ ) {

    $.fn.jsTreeNodePicker = function(options ) {

        var opts = $.extend( {}, $.fn.jsTreeNodePicker.defaults, options);
        var modalSelector;
        var btnOpen;
        var treeControl;
        var tagitControl;
        var errorMessageContainer;

        var pickerObj = this.each(function() {
            modalSelector = $("#"+opts.dialogId);

            // Append open picker dialog button
            var btnOpenContainer = $('

');
            $(this).append(btnOpenContainer);
            btnOpen = $('<button id="btnOpen'+opts.dialogId+'" type="button" class="btn btn-default" '
                + ' data-toggle="modal" data-target="#'+opts.dialogId+'"> </button>');

            btnOpenContainer.append(btnOpen);

            var modalBody = modalSelector.children(".modal-dialog").children(".modal-content").children(".modal-body");
            modalBody.css(opts.sizeCSS);

            // Add place to show error message
            errorMessageContainer = $('

');
            modalBody.append(errorMessageContainer);

            var treeControlId = opts.dialogId + "_treeControl";
            var treeControlContainer = $('

');
            modalBody.append(treeControlContainer);
            treeControl = $('

');

            treeControlContainer.append(treeControl);

            treeControl.jstree({
                'core' : {
                    'data' : opts.data
                },
                "checkbox" : opts.jstreeOptions.checkbox,
                "plugins" : opts.jstreeOptions.plugins
            });

            treeControl.bind("loaded.jstree", function (event, data) {
                if (opts.expandAllNodes === true) {
                    $(this).jstree("open_all");
                } else {
                    $(this).jstree("close_all");
                }

            });

            // Append tagit control
            var tagitControlContainer = $('

');
            $(this).append(tagitControlContainer);

            tagitControl = $('

');
            tagitControlContainer.append(tagitControl);
            tagitControl.tagit({
                fieldName: opts.tagitOptions.fieldName,
                allowSpaces: opts.tagitOptions.allowSpaces,
                tagLimit: opts.tagLimit,
                showAutocompleteOnFocus:  opts.tagitOptions.showAutocompleteOnFocus,
                readOnly: opts.tagitOptions.readOnly
            });

            if (opts.removeTagItBorder === true) {
                tagitControl.removeClass("ui-widget-content");
            }

            if (opts.selectedNodes.length > 0) {
                tagitControl.tagit("removeAll");
                for (x in opts.selectedNodes) {
                    tagitControl.tagit('createTag', opts.selectedNodes[x]);

                }
            }

        });

        pickerObj.modalSelector = modalSelector;
        pickerObj.btnOpen = btnOpen;
        pickerObj.treeControl = treeControl;
        pickerObj.tagitControl = tagitControl;
        pickerObj.errorMessageContainer = errorMessageContainer;

        pickerObj.opts = $.extend({}, opts);

        pickerObj.btnClearAll = pickerObj.modalSelector.children(".modal-dialog").children(".modal-content")
                                .children(".modal-footer").children(".btnTreeNodePickerClearAll");

        pickerObj.btnOK = pickerObj.modalSelector.children(".modal-dialog").children(".modal-content")
                                        .children(".modal-footer").children(".btnTreeNodePickerOK");
        pickerObj.btnCancel = pickerObj.modalSelector.children(".modal-dialog").children(".modal-content")
                                                .children(".modal-footer").children(".btnTreeNodePickerCancel");

        pickerObj.dialogTitle = pickerObj.modalSelector.children(".modal-dialog").children(".modal-content")
                                                .children(".modal-header").children(".modal-title");

        pickerObj.btnClearAll.text(pickerObj.opts.labels.buttons.btn_clear_all);
        pickerObj.btnOK.text(pickerObj.opts.labels.buttons.btn_ok);
        pickerObj.btnCancel.text(pickerObj.opts.labels.buttons.btn_cancel);
        pickerObj.btnCancel.text(pickerObj.opts.labels.buttons.btn_cancel);
        pickerObj.btnOpen.text(pickerObj.opts.labels.buttons.btn_open);
        pickerObj.dialogTitle.text(pickerObj.opts.labels.text.label_title);

        pickerObj.btnClearAll.click(function() {
             pickerObj.treeControl.jstree("deselect_all");
        });

        pickerObj.btnOK.click(function(){

            var selectedNodes = pickerObj.treeControl.jstree("get_selected");
            if (selectedNodes.length > pickerObj.opts.tagLimit) {
                return false;
            }
            pickerObj.tagitControl.tagit("removeAll");
            for (x in selectedNodes) {
                pickerObj.tagitControl.tagit('createTag', selectedNodes[x]);

            }

            pickerObj.modalSelector.modal("toggle");
            pickerObj.opts.selectedNodes = selectedNodes;
        });

        pickerObj.btnOpen.click(function () {
            pickerObj.treeControl.jstree(true).deselect_all();
            for (x in pickerObj.opts.selectedNodes) {
                treeControl.jstree(true).select_node(pickerObj.opts.selectedNodes[x]);
            }
            if (opts.expandAllNodes === true) {
               pickerObj.treeControl.jstree("open_all");
            } else {
               pickerObj.treeControl.jstree("close_all");
            }
        });

        pickerObj.treeControl.on("changed.jstree", function (e, data) {
            if (data.selected.length > pickerObj.opts.tagLimit) {
                pickerObj.errorMessageContainer.text(pickerObj.opts.errMessages.err_you_can_not_pick_more_than
                    + ' ' + pickerObj.opts.tagLimit + ' ' + pickerObj.opts.labels.text.label_node);
                pickerObj.errorMessageContainer.show();
            } else {
                pickerObj.errorMessageContainer.hide();
            }

        });

        if (pickerObj.opts.expandChildOnSingleClick === true) {
            pickerObj.treeControl.on("select_node.jstree", function (e, data) {
                if(data.node.state.opened == true) {
                    pickerObj.treeControl.jstree(true).close_node(data.node);
//                    node.state.opened = false;
               } else {
                    pickerObj.treeControl.jstree(true).open_node(data.node);
//                    node.state.opened = true;
               }
            });
            /* pickerObj.treeControl.on("click",function (e) {
              var li = $(e.target).closest("li");
              var node =  pickerObj.treeControl.jstree(true).get_node(li[0].id);

              console.log(node.state.opened);

               if(node.state.opened == true) {
                    pickerObj.treeControl.jstree(true).close_node(node);
                    node.state.opened = false;
               } else {
                    pickerObj.treeControl.jstree(true).open_node(node);
                    node.state.opened = true;
               }
            });*/
        }

        return pickerObj;

    }

    $.fn.jsTreeNodePicker.defaults = {
        "sizeCSS": {
            "min-height": "300px",
            "max-height": "300px",
            "height": "300px",
            "min-width": "600px",
            "max-width": "600px",
            "width": "600px",
        },
        "dialogId": "pickerDlg",
        "expandChildOnSingleClick": true,
        "tagLimit": 5,
        "expandAllNodes": true,
        "data": [],
        "selectedNodes": [],
        "removeTagItBorder": false,
        "tagitOptions": {
            "fieldName": "tagList",
            "allowSpaces": true,
            "showAutocompleteOnFocus": false,
            "readOnly": true
        },
        "jstreeOptions": {
            "checkbox" : {
                "keep_selected_style" : false,
                "three_state": false
            },
            "plugins" : [ "checkbox" ]
        },
        "labels": {
            "buttons": {
                "btn_ok": "OK",
                "btn_cancel": "Cancel",
                "btn_clear_all": "Clear All",
                "btn_open": "Click here to choose nodes"
            },
            "text": {
                "label_title": "Choose nodes",
                "label_node": "node"
            }

        },
        "errMessages": {
            "err_you_can_not_pick_more_than": "You cannot pick more than"
        }
    };

}( jQuery ));<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const nunjucks = require('nunjucks');
const dora = require('dora');
const webpack = require('atool-build/lib/webpack');
const getWebpackCommonConfig = require('atool-build/lib/getWebpackCommonConfig');
const ghPages = require('gh-pages');
const getConfig = require('./utils/get-config');
const markdownData = require('./utils/markdown-data');
const toCompletedRoutes = require('./utils/to-completed-routes');
const generateFilesPath = require('./utils/generate-files-path');
const updateWebpackConfig = require('./utils/update-webpack-config');

function generateQuery(config) {
  return Object.keys(config)
    .map((key) => `${key}=${config[key]}`)
    .join('&');
}

function transformPlugins(plugins) {
  return plugins.map((plugin) => {
    if (typeof plugin === 'string') {
      return plugin;
    }

    return `${plugin[0]}?${generateQuery(plugin[1])}`;
  });
}

exports.start = function start(program) {
  const configFile = path.join(process.cwd(), program.config || 'bisheng.config.js');
  const config = getConfig(configFile);

  const template = fs.readFileSync(config.htmlTemplate).toString();
  const indexPath = path.join(process.cwd(), config.output, 'index.html');
  mkdirp.sync(config.output);
  fs.writeFileSync(indexPath, nunjucks.renderString(template, { root: '/' }));

  const doraConfig = Object.assign({}, {
    cwd: path.join(process.cwd(), config.output),
    port: config.port,
  }, config.doraConfig);
  const usersDoraPlugin = config.doraConfig.plugins || [];
  doraConfig.plugins = [
    `${require.resolve('dora-plugin-webpack')}?disableNpmInstall`,
    `${path.join(__dirname, 'dora-plugin-bisheng')}?config=${configFile}`,
    require.resolve('dora-plugin-browser-history'),
  ];
  if (program.livereload) {
    doraConfig.plugins.push(require.resolve('dora-plugin-livereload'));
  }
  doraConfig.plugins = doraConfig.plugins.concat(transformPlugins(usersDoraPlugin));

  require('babel-polyfill');
  dora(doraConfig);
};

const noop = () => {};
exports.build = function build(program, callback) {
  const configFile = path.join(process.cwd(), program.config || 'bisheng.config.js');
  const config = getConfig(configFile);

  const themeConfig = require(path.join(process.cwd(), config.theme));
  themeConfig.completedRoutes = toCompletedRoutes(themeConfig.routes);

  const markdown = markdownData.generate(config.source);
  const filesNeedCreated = generateFilesPath(themeConfig.completedRoutes, markdown);

  const template = fs.readFileSync(config.htmlTemplate).toString();
  const fileContent = nunjucks.renderString(template, { root: config.root });

  filesNeedCreated.forEach((file) => {
    const output = path.join(config.output, file);
    mkdirp.sync(path.dirname(output));
    fs.writeFileSync(output, fileContent);
  });

  const webpackConfig =
          updateWebpackConfig(getWebpackCommonConfig({ cwd: process.cwd() }), configFile, true);
  webpackConfig.UglifyJsPluginConfig = {
    output: {
      ascii_only: true,
    },
    compress: {
      warnings: false,
    },
  };
  webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin(webpackConfig.UglifyJsPluginConfig));
  webpackConfig.plugins.push(new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production'),
  }));
  webpack(webpackConfig).run(callback || noop);
};

exports.deploy = function deploy(program) {
  exports.build(program, () => {
    const configFile = path.join(process.cwd(), program.config || 'bisheng.config.js');
    const config = getConfig(configFile);

    const options = {
      depth: 1,
      logger(message) {
        console.log(message);
      },
    };
    if (process.env.RUN_ENV_USER) {
      options.user = {
        name: process.env.RUN_ENV_USER,
        email: process.env.RUN_ENV_EMAIL,
      };
    }
    ghPages.publish(path.join(process.cwd(), config.output), options, (err) => {
      if (err) {
        throw err;
      }
      console.log('Site has been published!');
    });
  });
};
<commit_msg>fix: should resolve plugin<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const nunjucks = require('nunjucks');
const dora = require('dora');
const webpack = require('atool-build/lib/webpack');
const getWebpackCommonConfig = require('atool-build/lib/getWebpackCommonConfig');
const ghPages = require('gh-pages');
const getConfig = require('./utils/get-config');
const markdownData = require('./utils/markdown-data');
const toCompletedRoutes = require('./utils/to-completed-routes');
const generateFilesPath = require('./utils/generate-files-path');
const updateWebpackConfig = require('./utils/update-webpack-config');

function generateQuery(config) {
  return Object.keys(config)
    .map((key) => `${key}=${config[key]}`)
    .join('&');
}

function transformPlugins(plugins) {
  return plugins.map((plugin) => {
    if (typeof plugin === 'string') {
      return require.resolve(plugin);
    }

    return `${require.resolve(plugin[0])}?${generateQuery(plugin[1])}`;
  });
}

exports.start = function start(program) {
  const configFile = path.join(process.cwd(), program.config || 'bisheng.config.js');
  const config = getConfig(configFile);

  const template = fs.readFileSync(config.htmlTemplate).toString();
  const indexPath = path.join(process.cwd(), config.output, 'index.html');
  mkdirp.sync(config.output);
  fs.writeFileSync(indexPath, nunjucks.renderString(template, { root: '/' }));

  const doraConfig = Object.assign({}, {
    cwd: path.join(process.cwd(), config.output),
    port: config.port,
  }, config.doraConfig);
  const usersDoraPlugin = config.doraConfig.plugins || [];
  doraConfig.plugins = [
    `${require.resolve('dora-plugin-webpack')}?disableNpmInstall`,
    `${path.join(__dirname, 'dora-plugin-bisheng')}?config=${configFile}`,
    require.resolve('dora-plugin-browser-history'),
  ];
  doraConfig.plugins = doraConfig.plugins.concat(transformPlugins(usersDoraPlugin));
  if (program.livereload) {
    doraConfig.plugins.push(require.resolve('dora-plugin-livereload'));
  }

  require('babel-polyfill');
  dora(doraConfig);
};

const noop = () => {};
exports.build = function build(program, callback) {
  const configFile = path.join(process.cwd(), program.config || 'bisheng.config.js');
  const config = getConfig(configFile);

  const themeConfig = require(path.join(process.cwd(), config.theme));
  themeConfig.completedRoutes = toCompletedRoutes(themeConfig.routes);

  const markdown = markdownData.generate(config.source);
  const filesNeedCreated = generateFilesPath(themeConfig.completedRoutes, markdown);

  const template = fs.readFileSync(config.htmlTemplate).toString();
  const fileContent = nunjucks.renderString(template, { root: config.root });

  filesNeedCreated.forEach((file) => {
    const output = path.join(config.output, file);
    mkdirp.sync(path.dirname(output));
    fs.writeFileSync(output, fileContent);
  });

  const webpackConfig =
          updateWebpackConfig(getWebpackCommonConfig({ cwd: process.cwd() }), configFile, true);
  webpackConfig.UglifyJsPluginConfig = {
    output: {
      ascii_only: true,
    },
    compress: {
      warnings: false,
    },
  };
  webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin(webpackConfig.UglifyJsPluginConfig));
  webpackConfig.plugins.push(new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production'),
  }));
  webpack(webpackConfig).run(callback || noop);
};

exports.deploy = function deploy(program) {
  exports.build(program, () => {
    const configFile = path.join(process.cwd(), program.config || 'bisheng.config.js');
    const config = getConfig(configFile);

    const options = {
      depth: 1,
      logger(message) {
        console.log(message);
      },
    };
    if (process.env.RUN_ENV_USER) {
      options.user = {
        name: process.env.RUN_ENV_USER,
        email: process.env.RUN_ENV_EMAIL,
      };
    }
    ghPages.publish(path.join(process.cwd(), config.output), options, (err) => {
      if (err) {
        throw err;
      }
      console.log('Site has been published!');
    });
  });
};
<|endoftext|>


<commit_before>const request = require('request-promise')
const Command = require('../Command')

module.exports =
class CreateGroupRanksCommand extends Command {
  constructor (client) {
    super(client, {
      name: 'creategroupranks',
      properName: 'CreateGroupRanks',
      aliases: ['rovercreategroupranks'],
      description: 'Creates Discord roles from all of the roles in a given group, and then binds them to the group.',

      args: [
        {
          key: 'groupid',
          label: 'groupid',
          prompt: 'Group ID',
          type: 'integer'
        }
      ]
    })
  }

  async fn (msg, args) {
    try {
      const { Roles } = await request(`https://api.roblox.com/groups/${args.groupid}`, { json: true })

      let serverBindings = this.server.getSetting('groupRankBindings')
      Roles.reverse()
      for (let role of Roles) {
        const newRole = (await msg.guild.roles.find(guildRole => guildRole.name === role.Name)) || (await msg.guild.roles.create({
          data: {
            name: role.Name,
            permissions: []
          },
          reason: `${msg.member.displayName} ran CreateGroupRanks command`
        }))

        this.server.deleteGroupRankBinding(newRole.id)

        serverBindings.push({
          role: newRole.id,
          groups: [{
            id: args.groupid.toString(),
            ranks: [role.Rank]
          }]
        })
      }
      this.server.setSetting('groupRankBindings', serverBindings)

      msg.reply(`Created ${Roles.length} role bindings successfully (and created the roles if necessary).`)
    } catch (e) {
      msg.reply(`:no_entry_sign: RoVer does not have permission to create roles in this server.`)
    }
  }
}
<commit_msg>Update CreateGroupRanks error message<commit_after>const request = require('request-promise')
const Command = require('../Command')

module.exports =
class CreateGroupRanksCommand extends Command {
  constructor (client) {
    super(client, {
      name: 'creategroupranks',
      properName: 'CreateGroupRanks',
      aliases: ['rovercreategroupranks'],
      description: 'Creates Discord roles from all of the roles in a given group, and then binds them to the group.',

      args: [
        {
          key: 'groupid',
          label: 'groupid',
          prompt: 'Group ID',
          type: 'integer'
        }
      ]
    })
  }

  async fn (msg, args) {
    try {
      const { Roles } = await request(`https://api.roblox.com/groups/${args.groupid}`, { json: true })

      let serverBindings = this.server.getSetting('groupRankBindings')
      Roles.reverse()
      for (let role of Roles) {
        const newRole = (await msg.guild.roles.find(guildRole => guildRole.name === role.Name)) || (await msg.guild.roles.create({
          data: {
            name: role.Name,
            permissions: []
          },
          reason: `${msg.member.displayName} ran CreateGroupRanks command`
        }))

        this.server.deleteGroupRankBinding(newRole.id)

        serverBindings.push({
          role: newRole.id,
          groups: [{
            id: args.groupid.toString(),
            ranks: [role.Rank]
          }]
        })
      }
      this.server.setSetting('groupRankBindings', serverBindings)

      msg.reply(`Created ${Roles.length} role bindings successfully (and created the roles if necessary).`)
    } catch (e) {
      msg.reply(`:no_entry_sign: Something went wrong. Maybe the group doesn't exist, or maybe RoVer doesn't have permission to create roles in this server.`)
    }
  }
}
<|endoftext|>