<commit_before>define(["./_default-component"], function (BootstrapComponent) {
	var BootstrapRow = BootstrapRow || BootstrapComponent.extend({
		init: function (options) {
			this._super(options);
			return this;
		},
		render: function (container, descriptor) {
			var $this = this,
				parent = $("

").appendTo(container).addClass("bootstrap-row-adorner")
				.css("padding", 10), el = descriptor.element, w = "150px";
			$(".adorner-events-list").hide();
			// don't hardcode the default number of columns but take it from the running config
			var currentVal, session = descriptor.editorSession;
			if (el.hasClass("row")) {
				currentVal = el.children().length;
			} else {
				currentVal = el.find(".row").children().length;
			}
			/*
			$("

").appendTo(parent).text("Number of columns: " + currentVal).css("color", "white").css("padding-bottom", 10);
			$("

").appendTo(parent).attr("id", "slider");
			$("#slider").css("width", "80%").slider({
				value: currentVal,
				min: 1,
				max: 12,
				step: 1,
				slide: function( event, ui ) {
					container.find("h5").text("Number of columns: " + ui.value);
					// update code
					// what about columns that already have contents in them - do we just delete that?
				}
			});
			*/
			$("Id: <input type=\"text\" class=\"id form-control\"></input>").appendTo(parent).css("width", w);
			$("Classes: <input type=\"text\" class=\"classes form-control\"></input>").appendTo(parent).css("width", w);
			$("

").appendTo(parent).text("Grid Layout").addClass("label adorner-label").css({
				"padding-bottom": 10,
				"display": "block",
				"float": "left"
			});
			// append dropdown with list of layouts
			var dd = $("

").appendTo(parent).addClass("btn-group");
			var button = $("<button></button").appendTo(dd).attr("type", "button")
				.addClass("btn btn-primary dropdown-toggle").attr("data-toggle", "dropdown");
			button.css("width", w);
			$("").appendTo(button).addClass("label").text("Choose Layout ");
			$("").appendTo(button);
			var list = $("

").appendTo(dd).addClass("dropdown-menu")
				.attr("id", "grid-layout-dd").attr("role", "menu").css("width", w);
			// add list items
			$("

").appendTo(list).append("6-6");
			$("

").appendTo(list).append("4-4-4");
			$("

").appendTo(list).append("4-8");
			$("

").appendTo(list).append("8-4");
			$("

").appendTo(list).append("3-3-3-3");
			$("

").appendTo(list).append("2-10");
			$("

").appendTo(list).append("10-2");
			$("

").appendTo(list).append("3-9");
			$("

").appendTo(list).append("9-3");
			$("

").appendTo(list).append("Custom");
			$("<input type=\"text\" class=\"custom-layout form-control\"></input>").appendTo(parent).css({
				"width": w,
				"margin-top": 10
			}).hide();
			$("<button></button").appendTo(parent).addClass("btn btn-success").css("width", w)
				.css("margin-top", 10).text("Add Column Span").click(function () {
				var markupCode = $this.getCodeEditorMarkupSnippet({type: "column"});
				var markup = $this.getMarkup({type: "column"});
				// TODO: actually insert the new colspan :)
			});
			// attach events
			$("#grid-layout-dd > li > a").click(function (event) {
				// update value
				var text = $(this).text();
				button.find(".label").text(text);
				if (text === "Custom") {
					$(".custom-layout.form-control").show();
					event.preventDefault();
					return;
				} else {
					$(".custom-layout.form-control").hide();
				}
				// update code editor
				// change the layout based on the user selection
				// try to keep existing contents, instead of wiping them out, if possible (Twitter jetstrap style)
				// parse text
				var textarr = text.split("-");
				// for the length of textarr, create that # of spans. if they already exist, don't touch them
				var htmlrange = descriptor.htmlMarker.range;
				var r = new descriptor.rangeClass(htmlrange.start.row + 1, 0, htmlrange.end.row - 1, 0);
				// wipe out what's already there - TODO - preserve markup
				var newColsCode = "", tmpObj, totalLineCount = 0, newHtmlCode = "";
				for (var i = 0; i < textarr.length; i++) {
					tmpObj = $this.getCodeEditorMarkupSnippet({type: "column", colSpan: textarr[i], extraIndent: 1});
					totalLineCount += tmpObj.lineCount;
					newColsCode += tmpObj.codeString;
					newHtmlCode += $this.getMarkup({type: "column", colSpan: textarr[i]});
				}
				//1. update code editor
				//do we use the totalLineCount for sth?
				session.replace(r, newColsCode);
				// now update the DOM of the designer/view
				el.html(newHtmlCode);
				// now update the markup
				event.preventDefault();
			});
			// "change" is the better event here, but "keyup" is just so much cooler !
			$(".id.form-control").keyup(function (event) {
				el.attr("id", this.value);
				// update code editor
				// locate code fragment by marker
				// we only need the htmlmarker here
				var htmlrange = descriptor.htmlMarker.range;
				var r = new descriptor.rangeClass(htmlrange.start.row, 0, htmlrange.start.row, 1000);
				//get the first line from the segment and change the id
				var code = session.getTextRange(r);
				// check if we have an ID set already
				if (code.indexOf("id=") !== -1) {
					if (this.value === "") {
						code = code.replace(/id="(.*?)"/, "");
					} else {
						code = code.replace(/id="(.*?)"/, "id=\"" + this.value + "\"");
					}
				} else {
					code = code.replace("<div ", "<div id=\"" + this.value + "\" ");
				}
				session.replace(r, code);
			});
			//"change" evt better
			$(".classes.form-control").keyup(function (event) {
				el.attr("class", this.value);
				// update code editor
				// we are using very similar code to the one above
				// think about refactoring !
				var htmlrange = descriptor.htmlMarker.range;
				var r = new descriptor.rangeClass(htmlrange.start.row, 0, htmlrange.start.row, 1000);
				var code = session.getTextRange(r);
				// check if we have an ID set already
				if (code.indexOf("class=") !== -1) {
					if (this.value === "") {
						code = code.replace(/class="(.*?)"/, "class=\"row\"");
					} else {
						code = code.replace(/class="(.*?)"/, "class=\"row " + this.value + "\"");
					}
				} else {
					code = code.replace("<div ", "<div class=\"" + this.value + "\" ");
				}
				session.replace(r, code);
			});
			$(".custom-layout.form-control").change(function (event) {
				// update code editor

			});
		}
	});
	return BootstrapRow;
});<commit_msg>Removing the line that hides events<commit_after>define(["./_default-component"], function (BootstrapComponent) {
	var BootstrapRow = BootstrapRow || BootstrapComponent.extend({
		init: function (options) {
			this._super(options);
			return this;
		},
		render: function (container, descriptor) {
			var $this = this,
				parent = $("

").appendTo(container).addClass("bootstrap-row-adorner")
				.css("padding", 10), el = descriptor.element, w = "150px";
			// don't hardcode the default number of columns but take it from the running config
			var currentVal, session = descriptor.editorSession;
			if (el.hasClass("row")) {
				currentVal = el.children().length;
			} else {
				currentVal = el.find(".row").children().length;
			}
			/*
			$("

").appendTo(parent).text("Number of columns: " + currentVal).css("color", "white").css("padding-bottom", 10);
			$("

").appendTo(parent).attr("id", "slider");
			$("#slider").css("width", "80%").slider({
				value: currentVal,
				min: 1,
				max: 12,
				step: 1,
				slide: function( event, ui ) {
					container.find("h5").text("Number of columns: " + ui.value);
					// update code
					// what about columns that already have contents in them - do we just delete that?
				}
			});
			*/
			$("Id: <input type=\"text\" class=\"id form-control\"></input>").appendTo(parent).css("width", w);
			$("Classes: <input type=\"text\" class=\"classes form-control\"></input>").appendTo(parent).css("width", w);
			$("

").appendTo(parent).text("Grid Layout").addClass("label adorner-label").css({
				"padding-bottom": 10,
				"display": "block",
				"float": "left"
			});
			// append dropdown with list of layouts
			var dd = $("

").appendTo(parent).addClass("btn-group");
			var button = $("<button></button").appendTo(dd).attr("type", "button")
				.addClass("btn btn-primary dropdown-toggle").attr("data-toggle", "dropdown");
			button.css("width", w);
			$("").appendTo(button).addClass("label").text("Choose Layout ");
			$("").appendTo(button);
			var list = $("

").appendTo(dd).addClass("dropdown-menu")
				.attr("id", "grid-layout-dd").attr("role", "menu").css("width", w);
			// add list items
			$("

").appendTo(list).append("6-6");
			$("

").appendTo(list).append("4-4-4");
			$("

").appendTo(list).append("4-8");
			$("

").appendTo(list).append("8-4");
			$("

").appendTo(list).append("3-3-3-3");
			$("

").appendTo(list).append("2-10");
			$("

").appendTo(list).append("10-2");
			$("

").appendTo(list).append("3-9");
			$("

").appendTo(list).append("9-3");
			$("

").appendTo(list).append("Custom");
			$("<input type=\"text\" class=\"custom-layout form-control\"></input>").appendTo(parent).css({
				"width": w,
				"margin-top": 10
			}).hide();
			$("<button></button").appendTo(parent).addClass("btn btn-success").css("width", w)
				.css("margin-top", 10).text("Add Column Span").click(function () {
				var markupCode = $this.getCodeEditorMarkupSnippet({type: "column"});
				var markup = $this.getMarkup({type: "column"});
				// TODO: actually insert the new colspan :)
			});
			// attach events
			$("#grid-layout-dd > li > a").click(function (event) {
				// update value
				var text = $(this).text();
				button.find(".label").text(text);
				if (text === "Custom") {
					$(".custom-layout.form-control").show();
					event.preventDefault();
					return;
				} else {
					$(".custom-layout.form-control").hide();
				}
				// update code editor
				// change the layout based on the user selection
				// try to keep existing contents, instead of wiping them out, if possible (Twitter jetstrap style)
				// parse text
				var textarr = text.split("-");
				// for the length of textarr, create that # of spans. if they already exist, don't touch them
				var htmlrange = descriptor.htmlMarker.range;
				var r = new descriptor.rangeClass(htmlrange.start.row + 1, 0, htmlrange.end.row - 1, 0);
				// wipe out what's already there - TODO - preserve markup
				var newColsCode = "", tmpObj, totalLineCount = 0, newHtmlCode = "";
				for (var i = 0; i < textarr.length; i++) {
					tmpObj = $this.getCodeEditorMarkupSnippet({type: "column", colSpan: textarr[i], extraIndent: 1});
					totalLineCount += tmpObj.lineCount;
					newColsCode += tmpObj.codeString;
					newHtmlCode += $this.getMarkup({type: "column", colSpan: textarr[i]});
				}
				//1. update code editor
				//do we use the totalLineCount for sth?
				session.replace(r, newColsCode);
				// now update the DOM of the designer/view
				el.html(newHtmlCode);
				// now update the markup
				event.preventDefault();
			});
			// "change" is the better event here, but "keyup" is just so much cooler !
			$(".id.form-control").keyup(function (event) {
				el.attr("id", this.value);
				// update code editor
				// locate code fragment by marker
				// we only need the htmlmarker here
				var htmlrange = descriptor.htmlMarker.range;
				var r = new descriptor.rangeClass(htmlrange.start.row, 0, htmlrange.start.row, 1000);
				//get the first line from the segment and change the id
				var code = session.getTextRange(r);
				// check if we have an ID set already
				if (code.indexOf("id=") !== -1) {
					if (this.value === "") {
						code = code.replace(/id="(.*?)"/, "");
					} else {
						code = code.replace(/id="(.*?)"/, "id=\"" + this.value + "\"");
					}
				} else {
					code = code.replace("<div ", "<div id=\"" + this.value + "\" ");
				}
				session.replace(r, code);
			});
			//"change" evt better
			$(".classes.form-control").keyup(function (event) {
				el.attr("class", this.value);
				// update code editor
				// we are using very similar code to the one above
				// think about refactoring !
				var htmlrange = descriptor.htmlMarker.range;
				var r = new descriptor.rangeClass(htmlrange.start.row, 0, htmlrange.start.row, 1000);
				var code = session.getTextRange(r);
				// check if we have an ID set already
				if (code.indexOf("class=") !== -1) {
					if (this.value === "") {
						code = code.replace(/class="(.*?)"/, "class=\"row\"");
					} else {
						code = code.replace(/class="(.*?)"/, "class=\"row " + this.value + "\"");
					}
				} else {
					code = code.replace("<div ", "<div class=\"" + this.value + "\" ");
				}
				session.replace(r, code);
			});
			$(".custom-layout.form-control").change(function (event) {
				// update code editor

			});
		}
	});
	return BootstrapRow;
});<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2010 by Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
"use strict";

/** @scope modules */

const Modes = Module("modes", {
    init: function () {
        this.modeChars = {};
        this._main = 1;     // NORMAL
        this._extended = 0; // NONE

        this._lastShown = null;

        this._passNextKey = false;
        this._passAllKeys = false;
        this._isRecording = false;
        this._isReplaying = false; // playing a macro

        this._modeStack = [];

        this._mainModes = [this.NONE];
        this._lastMode = 0;
        this._modeMap = {};

        this.boundProperties = {};

        // main modes, only one should ever be active
        this.addMode("NORMAL",   { char: "n", display: -1 });
        this.addMode("INSERT",   { char: "i", input: true });
        this.addMode("VISUAL",   { char: "v", display: function () "VISUAL" + (this._extended & modes.LINE ? " LINE" : "") });
        this.addMode("COMMAND_LINE", { char: "c", input: true });
        this.addMode("CARET"); // text cursor is visible
        this.addMode("TEXTAREA", { char: "i" });
        this.addMode("EMBED",    { input: true });
        this.addMode("CUSTOM",   { display: function () plugins.mode });
        // this._extended modes, can include multiple modes, and even main modes
        this.addMode("EX", true);
        this.addMode("HINTS", true);
        this.addMode("INPUT_MULTILINE", true);
        this.addMode("OUTPUT_MULTILINE", true);
        this.addMode("SEARCH_FORWARD", true);
        this.addMode("SEARCH_BACKWARD", true);
        this.addMode("SEARCH_VIEW_FORWARD", true);
        this.addMode("SEARCH_VIEW_BACKWARD", true);
        this.addMode("MENU", true); // a popupmenu is active
        this.addMode("LINE", true); // linewise visual mode
        this.addMode("PROMPT", true);

        this.push(this.NORMAL, 0, {
            restore: function (prev) {
                // disable caret mode when we want to switch to normal mode
                if (options.getPref("accessibility.browsewithcaret"))
                    options.setPref("accessibility.browsewithcaret", false);

                statusline.updateUrl();
                dactyl.focusContent(true);
            }
        });
    },

    _getModeMessage: function () {
        if (this._passNextKey && !this._passAllKeys)
            return "-- PASS THROUGH (next) --";
        else if (this._passAllKeys && !this._passNextKey)
            return "-- PASS THROUGH --";

        // when recording a macro
        let macromode = "";
        if (modes.isRecording)
            macromode = "recording";
        else if (modes.isReplaying)
            macromode = "replaying";

        let ext = "";
        if (this._extended & modes.MENU) // TODO: desirable?
            ext += " (menu)";
        ext += " --" + macromode;

        if (this._main in this._modeMap && typeof this._modeMap[this._main].display == "function")
            return "-- " + this._modeMap[this._main].display() + ext;
        return macromode;
    },

    NONE: 0,

    __iterator__: function () array.iterValues(this.all),

    get all() this._mainModes.slice(),

    get mainModes() (mode for ([k, mode] in Iterator(modes._modeMap)) if (!mode.extended && mode.name == k)),

    get mainMode() this._modeMap[this._main],

    get topOfStack() this._modeStack[this._modeStack.length - 1],

    addMode: function (name, extended, options) {
        let disp = name.replace("_", " ", "g");
        this[name] = 1 << this._lastMode++;
        if (typeof extended == "object") {
            options = extended;
            extended = false;
        }
        let mode = util.extend({
            extended: extended,
            count: true,
            input: false,
            mask: this[name],
            name: name,
            disp: disp
        }, options);
        if (mode.char) {
            this.modeChars[mode.char] = this.modeChars[mode.char] || [];
            this.modeChars[mode.char].push(mode);
        }

        mode.display = mode.display || function () disp;
        this._modeMap[name] = mode;
        this._modeMap[this[name]] = mode;
        if (!extended)
            this._mainModes.push(this[name]);
        dactyl.triggerObserver("mode-add", mode);
    },

    getMode: function (name) this._modeMap[name],

    getCharModes: function (chr) [m for (m in values(this._modeMap)) if (m.char == chr)],

    matchModes: function (obj)
        [m for (m in values(this._modeMap)) if (Object.keys(obj).every(function (k) obj[k] == (m[k] || false)))],

    // show the current mode string in the command line
    show: function () {
        let msg = null;
        if (options["showmode"])
            msg = this._getModeMessage();
        commandline.widgets.mode = msg || null;
    },

    // add/remove always work on the this._extended mode only
    add: function (mode) {
        this._extended |= mode;
        this.show();
    },

    save: function (id, obj, prop) {
        if (!(id in this.boundProperties))
            for (let elem in values(this._modeStack))
                elem.saved[id] = { obj: obj, prop: prop, value: obj[prop] };
        this.boundProperties[id] = { obj: Cu.getWeakReference(obj), prop: prop };
    },

    // helper function to set both modes in one go
    // if silent == true, you also need to take care of the mode handling changes yourself
    set: function (mainMode, extendedMode, params, stack) {
        params = params || {};

        if (!stack && mainMode != null && this._modeStack.length > 1)
            this.reset();

        let push = mainMode != null && !(stack && stack.pop) &&
            Modes.StackElem(mainMode, extendedMode || this.NONE, params, {});
        if (push && this.topOfStack) {
            if (this.topOfStack.params.save)
                this.topOfStack.params.save(push);

            for (let [id, { obj, prop }] in Iterator(this.boundProperties)) {
                if (!obj.get())
                    delete this.boundProperties(id);
                else
                    this.topOfStack.saved[id] = { obj: obj.get(), prop: prop, value: obj.get()[prop] };
            }
        }

        let silent = this._main === mainMode && this._extended === extendedMode;
        // if a this._main mode is set, the this._extended is always cleared
        let oldMain = this._main, oldExtended = this._extended;

        if (typeof extendedMode === "number")
            this._extended = extendedMode;
        if (typeof mainMode === "number") {
            this._main = mainMode;
            if (!extendedMode)
                this._extended = this.NONE;
        }

        if (push)
            this._modeStack.push(push);

        dactyl.triggerObserver("modeChange", [oldMain, oldExtended], [this._main, this._extended], stack);

        if (!silent)
            this.show();
    },

    push: function (mainMode, extendedMode, params) {
        this.set(mainMode, extendedMode, params, { push: this.topOfStack });
    },

    pop: function () {
        let a = this._modeStack.pop();
        if (a.params.leave)
            a.params.leave(this.topOfStack);

        this.set(this.topOfStack.main, this.topOfStack.extended, this.topOfStack.params, { pop: a });
        if (this.topOfStack.params.restore)
            this.topOfStack.params.restore(a);

        for (let [k, { obj, prop, value }] in Iterator(this.topOfStack.saved))
            obj[prop] = value;
    },

    reset: function () {
        if (this._modeStack.length == 1 && this.topOfStack.params.restore)
            this.topOfStack.params.restore(this.topOfStack);
        while (this._modeStack.length > 1)
            this.pop();
    },

    remove: function (mode) {
        if (this._extended & mode) {
            this._extended &= ~mode;
            this.show();
        }
    },

    get passNextKey() this._passNextKey,
    set passNextKey(value) { this._passNextKey = value; this.show(); },

    get passAllKeys() this._passAllKeys,
    set passAllKeys(value) { this._passAllKeys = value; this.show(); },

    get isRecording() this._isRecording,
    set isRecording(value) { this._isRecording = value; this.show(); },

    get isReplaying() this._isReplaying,
    set isReplaying(value) { this._isReplaying = value; this.show(); },

    get main() this._main,
    set main(value) { this.set(value); },

    get extended() this._extended,
    set extended(value) { this.set(null, value); }
}, {
    StackElem: Struct("main", "extended", "params", "saved"),
    cacheId: 0,
    boundProperty: function boundProperty(desc) {
        desc = desc || {};
        let id = this.cacheId++, value;
        return Class.Property(update({
            enumerable: true,
            configurable: true,
            init: function (prop) update(this, {
                get: function () {
                    if (desc.get)
                        var val = desc.get.call(this, value);
                    return val === undefined ? value : val;
                },
                set: function (val) {
                    modes.save(id, this, prop)
                    if (desc.set)
                        value = desc.set.call(this, val);
                    value = !desc.set || value === undefined ? val : value;
                }
            })
        }, desc));
    }
});

// vim: set fdm=marker sw=4 ts=4 et:
<commit_msg>Use null rather than -1 for specifying a non-existent mode display function.<commit_after>// Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2010 by Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
"use strict";

/** @scope modules */

const Modes = Module("modes", {
    init: function () {
        this.modeChars = {};
        this._main = 1;     // NORMAL
        this._extended = 0; // NONE

        this._lastShown = null;

        this._passNextKey = false;
        this._passAllKeys = false;
        this._isRecording = false;
        this._isReplaying = false; // playing a macro

        this._modeStack = [];

        this._mainModes = [this.NONE];
        this._lastMode = 0;
        this._modeMap = {};

        this.boundProperties = {};

        // main modes, only one should ever be active
        this.addMode("NORMAL",   { char: "n", display: null });
        this.addMode("INSERT",   { char: "i", input: true });
        this.addMode("VISUAL",   { char: "v", display: function () "VISUAL" + (this._extended & modes.LINE ? " LINE" : "") });
        this.addMode("COMMAND_LINE", { char: "c", input: true });
        this.addMode("CARET"); // text cursor is visible
        this.addMode("TEXTAREA", { char: "i" });
        this.addMode("EMBED",    { input: true });
        this.addMode("CUSTOM",   { display: function () plugins.mode });
        // this._extended modes, can include multiple modes, and even main modes
        this.addMode("EX", true);
        this.addMode("HINTS", true);
        this.addMode("INPUT_MULTILINE", true);
        this.addMode("OUTPUT_MULTILINE", true);
        this.addMode("SEARCH_FORWARD", true);
        this.addMode("SEARCH_BACKWARD", true);
        this.addMode("SEARCH_VIEW_FORWARD", true);
        this.addMode("SEARCH_VIEW_BACKWARD", true);
        this.addMode("MENU", true); // a popupmenu is active
        this.addMode("LINE", true); // linewise visual mode
        this.addMode("PROMPT", true);

        this.push(this.NORMAL, 0, {
            restore: function (prev) {
                // disable caret mode when we want to switch to normal mode
                if (options.getPref("accessibility.browsewithcaret"))
                    options.setPref("accessibility.browsewithcaret", false);

                statusline.updateUrl();
                dactyl.focusContent(true);
            }
        });
    },

    _getModeMessage: function () {
        if (this._passNextKey && !this._passAllKeys)
            return "-- PASS THROUGH (next) --";
        else if (this._passAllKeys && !this._passNextKey)
            return "-- PASS THROUGH --";

        // when recording a macro
        let macromode = "";
        if (modes.isRecording)
            macromode = "recording";
        else if (modes.isReplaying)
            macromode = "replaying";

        let ext = "";
        if (this._extended & modes.MENU) // TODO: desirable?
            ext += " (menu)";
        ext += " --" + macromode;

        if (this._main in this._modeMap && typeof this._modeMap[this._main].display == "function")
            return "-- " + this._modeMap[this._main].display() + ext;
        return macromode;
    },

    NONE: 0,

    __iterator__: function () array.iterValues(this.all),

    get all() this._mainModes.slice(),

    get mainModes() (mode for ([k, mode] in Iterator(modes._modeMap)) if (!mode.extended && mode.name == k)),

    get mainMode() this._modeMap[this._main],

    get topOfStack() this._modeStack[this._modeStack.length - 1],

    addMode: function (name, extended, options) {
        let disp = name.replace("_", " ", "g");
        this[name] = 1 << this._lastMode++;
        if (typeof extended == "object") {
            options = extended;
            extended = false;
        }
        let mode = util.extend({
            extended: extended,
            count: true,
            input: false,
            mask: this[name],
            name: name,
            disp: disp
        }, options);
        if (mode.char) {
            this.modeChars[mode.char] = this.modeChars[mode.char] || [];
            this.modeChars[mode.char].push(mode);
        }

        if (mode.display !== null)
            mode.display = function () disp;
        this._modeMap[name] = mode;
        this._modeMap[this[name]] = mode;
        if (!extended)
            this._mainModes.push(this[name]);
        dactyl.triggerObserver("mode-add", mode);
    },

    getMode: function (name) this._modeMap[name],

    getCharModes: function (chr) [m for (m in values(this._modeMap)) if (m.char == chr)],

    matchModes: function (obj)
        [m for (m in values(this._modeMap)) if (Object.keys(obj).every(function (k) obj[k] == (m[k] || false)))],

    // show the current mode string in the command line
    show: function () {
        let msg = null;
        if (options["showmode"])
            msg = this._getModeMessage();
        commandline.widgets.mode = msg || null;
    },

    // add/remove always work on the this._extended mode only
    add: function (mode) {
        this._extended |= mode;
        this.show();
    },

    save: function (id, obj, prop) {
        if (!(id in this.boundProperties))
            for (let elem in values(this._modeStack))
                elem.saved[id] = { obj: obj, prop: prop, value: obj[prop] };
        this.boundProperties[id] = { obj: Cu.getWeakReference(obj), prop: prop };
    },

    // helper function to set both modes in one go
    // if silent == true, you also need to take care of the mode handling changes yourself
    set: function (mainMode, extendedMode, params, stack) {
        params = params || {};

        if (!stack && mainMode != null && this._modeStack.length > 1)
            this.reset();

        let push = mainMode != null && !(stack && stack.pop) &&
            Modes.StackElem(mainMode, extendedMode || this.NONE, params, {});
        if (push && this.topOfStack) {
            if (this.topOfStack.params.save)
                this.topOfStack.params.save(push);

            for (let [id, { obj, prop }] in Iterator(this.boundProperties)) {
                if (!obj.get())
                    delete this.boundProperties(id);
                else
                    this.topOfStack.saved[id] = { obj: obj.get(), prop: prop, value: obj.get()[prop] };
            }
        }

        let silent = this._main === mainMode && this._extended === extendedMode;
        // if a this._main mode is set, the this._extended is always cleared
        let oldMain = this._main, oldExtended = this._extended;

        if (typeof extendedMode === "number")
            this._extended = extendedMode;
        if (typeof mainMode === "number") {
            this._main = mainMode;
            if (!extendedMode)
                this._extended = this.NONE;
        }

        if (push)
            this._modeStack.push(push);

        dactyl.triggerObserver("modeChange", [oldMain, oldExtended], [this._main, this._extended], stack);

        if (!silent)
            this.show();
    },

    push: function (mainMode, extendedMode, params) {
        this.set(mainMode, extendedMode, params, { push: this.topOfStack });
    },

    pop: function () {
        let a = this._modeStack.pop();
        if (a.params.leave)
            a.params.leave(this.topOfStack);

        this.set(this.topOfStack.main, this.topOfStack.extended, this.topOfStack.params, { pop: a });
        if (this.topOfStack.params.restore)
            this.topOfStack.params.restore(a);

        for (let [k, { obj, prop, value }] in Iterator(this.topOfStack.saved))
            obj[prop] = value;
    },

    reset: function () {
        if (this._modeStack.length == 1 && this.topOfStack.params.restore)
            this.topOfStack.params.restore(this.topOfStack);
        while (this._modeStack.length > 1)
            this.pop();
    },

    remove: function (mode) {
        if (this._extended & mode) {
            this._extended &= ~mode;
            this.show();
        }
    },

    get passNextKey() this._passNextKey,
    set passNextKey(value) { this._passNextKey = value; this.show(); },

    get passAllKeys() this._passAllKeys,
    set passAllKeys(value) { this._passAllKeys = value; this.show(); },

    get isRecording() this._isRecording,
    set isRecording(value) { this._isRecording = value; this.show(); },

    get isReplaying() this._isReplaying,
    set isReplaying(value) { this._isReplaying = value; this.show(); },

    get main() this._main,
    set main(value) { this.set(value); },

    get extended() this._extended,
    set extended(value) { this.set(null, value); }
}, {
    StackElem: Struct("main", "extended", "params", "saved"),
    cacheId: 0,
    boundProperty: function boundProperty(desc) {
        desc = desc || {};
        let id = this.cacheId++, value;
        return Class.Property(update({
            enumerable: true,
            configurable: true,
            init: function (prop) update(this, {
                get: function () {
                    if (desc.get)
                        var val = desc.get.call(this, value);
                    return val === undefined ? value : val;
                },
                set: function (val) {
                    modes.save(id, this, prop)
                    if (desc.set)
                        value = desc.set.call(this, val);
                    value = !desc.set || value === undefined ? val : value;
                }
            })
        }, desc));
    }
});

// vim: set fdm=marker sw=4 ts=4 et:
<|endoftext|>


<commit_before>exports.defineTags = function(dictionary) {
  dictionary.defineTag('ngdoc', {
    mustHaveValue: true,
    onTagged : function(doclet, tag) {
      if (tag.value == "method") {
        doclet.addTag('kind', 'function');
      } else {
        doclet.addTag('kind', 'class');
      }
      doclet.ngdoc = tag.value;
    }
  });

  dictionary.defineTag('attribute', {
    mustHaveValue: true,
    canHaveType: true,
    canHaveName: true,
    onTagged: function(doclet, tag) {
      if (!doclet.attributes) { doclet.attributes = []; }
      doclet.attributes.push(tag.value);
    }
  })
  .synonym('attr');

  dictionary.defineTag('restrict', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      var restricts={
          'A': 'Attribute',
          'E': 'Element',
          'C': 'Class'
      }
      var s = tag.value.split('').map(function(aec) {
        return restricts[aec];
      })
      doclet.restrict = s;
    }
  });

  dictionary.defineTag('priority', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      doclet.priority = tag.value;
    }
  });

  dictionary.defineTag('eventType', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      doclet.eventType = tag.value;
    }
  });

  dictionary.defineTag('animations', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      doclet.animations = tag.value;
    }
  });

  dictionary.defineTag('scope', {
    onTagged: function(doclet, tag) {
      var scopeType={
        'object': '\'isolate\' scope',
        '{}': '\'isolate\' scope',
        'true': 'scope which prototypically inherits from its parent',
        'false': 'shared scope'
      }
      var s = function() {
        return scopeType[tag.value];
      }();
      if (!tag.value || !s) {
        doclet.scopeType = 'scope';
      } else {
        doclet.scopeType = s;
      }
      doclet.newScope = !(s == 'shared scope');
    }
  });

  dictionary.defineTag('description', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      var helper = require('jsdoc/util/templateHelper');

      // replace inline link tags
      tag.value = require('jsdoc/tag/inline').replaceInlineTag(tag.value, 'link', function(string, matchedTag) {
        var match;
        var longname;
        var method;
        var fragmentId;
        var link;

        match = /(\S+)#(methods|properties|events)_(\S+)\s(\S+)/.exec(matchedTag.text);
        if (match) {
          longname = match[1];
          method = match[4] || match[3];
          fragmentId = match[3];
        }

        helper.registerLink(longname, longname + '.html');
        link = helper.linkto(longname, helper.htmlsafe(method), null, fragmentId);

        return tag.value.replace(new RegExp(matchedTag.completeTag, 'g'), link);
      }).newString;
    },
    synonyms: ['desc']
  });
};
<commit_msg>inline link tags which point to an external url are now also replaced by a link<commit_after>exports.defineTags = function(dictionary) {
  function hasUrlPrefix(text) {
    return (/^(http|ftp)s?:\/\//).test(text);
  }

  dictionary.defineTag('ngdoc', {
    mustHaveValue: true,
    onTagged : function(doclet, tag) {
      if (tag.value == "method") {
        doclet.addTag('kind', 'function');
      } else {
        doclet.addTag('kind', 'class');
      }
      doclet.ngdoc = tag.value;
    }
  });

  dictionary.defineTag('attribute', {
    mustHaveValue: true,
    canHaveType: true,
    canHaveName: true,
    onTagged: function(doclet, tag) {
      if (!doclet.attributes) { doclet.attributes = []; }
      doclet.attributes.push(tag.value);
    }
  })
  .synonym('attr');

  dictionary.defineTag('restrict', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      var restricts={
          'A': 'Attribute',
          'E': 'Element',
          'C': 'Class'
      }
      var s = tag.value.split('').map(function(aec) {
        return restricts[aec];
      })
      doclet.restrict = s;
    }
  });

  dictionary.defineTag('priority', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      doclet.priority = tag.value;
    }
  });

  dictionary.defineTag('eventType', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      doclet.eventType = tag.value;
    }
  });

  dictionary.defineTag('animations', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      doclet.animations = tag.value;
    }
  });

  dictionary.defineTag('scope', {
    onTagged: function(doclet, tag) {
      var scopeType={
        'object': '\'isolate\' scope',
        '{}': '\'isolate\' scope',
        'true': 'scope which prototypically inherits from its parent',
        'false': 'shared scope'
      }
      var s = function() {
        return scopeType[tag.value];
      }();
      if (!tag.value || !s) {
        doclet.scopeType = 'scope';
      } else {
        doclet.scopeType = s;
      }
      doclet.newScope = !(s == 'shared scope');
    }
  });

  dictionary.defineTag('description', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      var helper = require('jsdoc/util/templateHelper');

      // replace inline link tags
      tag.value = require('jsdoc/tag/inline').replaceInlineTag(tag.value, 'link', function(string, matchedTag) {
        var match;
        var longname;
        var text;
        var fragmentId;
        var link;

        if ( hasUrlPrefix(matchedTag.text) ) {
          match = /(\S+)\s(\S+)/.exec(matchedTag.text);
          if (match) {
            longname = match[1];
            text = match[2] || match[1];
          }
        }
        else {
          match = /(\S+)#(methods|properties|events)_(\S+)\s(\S+)/.exec(matchedTag.text);
          if (match) {
            longname = match[1];
            text = match[4] || match[3];
            fragmentId = match[3];
            helper.registerLink(longname, longname + '.html');
          }
        }

        link = helper.linkto(longname, helper.htmlsafe(text), null, fragmentId);
        return tag.value.replace(new RegExp(require('escape-string-regexp')(matchedTag.completeTag), 'g'), link);
      }).newString;
    },
    synonyms: ['desc']
  });
};
<|endoftext|>


<commit_before>/* global $: false */

var core = require('kanso/core'),
    db = require('kanso/db'),
    loader = require('kanso/loader'),
    utils = require('kanso/utils'),
    widgets = require('kanso/widgets'),
    querystring = require('kanso/querystring'),
    sanitize = require('kanso/sanitize'),
    _ = require('kanso/underscore')._;

var h = sanitize.escapeHtml;

/**
 * Show a modal dialog containing an editable form. Once the
 * editing is completed, call addRow and pass along the JSON-encoded
 * form data.
 */
exports.showModal = function (type, div, field_td, row,
                              typename, val, rawval, field) {

    var form = new forms.Form(type, val);

    if (rawval) {
        form.validate(rawval);
    }

    div.html('<h2>' + (val ? 'Edit ': 'Add ') + h(typename) + '</h2>');
    div.append('<form>' + form.toHTML() + '</form>');

    var action = (val ? 'Update': 'Add');
    var okbtn = $(
        '<input type="button" value="' + h(action)  + '" />"'
    );

    okbtn.click(function () {
        var qs = $('form', div).serialize().replace(/\+/g, '%20');
        var rawval = querystring.parse(qs);
        form.validate(rawval);

        if (form.isValid()) {
            if (!val) {
                row = exports.addRow(
                    field_td, field, val, rawval, type
                );
            }
            /* Stash JSON-encoded form data in hidden input */
            var jsonval = JSON.stringify(form.values);
            $('input:hidden', row).val(jsonval);
            $('span.value', row).text(form.values._id);
            exports.updateRow(row);
            $.modal.close();
        }
        else {
            /* Repost form showing errors */
            exports.showModal(
                type, form, div, field_td, row,
                    typename, val, rawval, field
            );
        }
    });
    div.append(okbtn);
    div.submit(function (ev) {
        ev.preventDefault();
        okbtn.click();
        return false;
    });

    var cancelbtn = $(
        '<input type="button" value="Cancel" />'
    );
    cancelbtn.click(function () {
        $.modal.close();
    });
    div.append(cancelbtn);

    div.modal();
    utils.resizeModal(div);

    if (!val) {
        exports.generateNewDocumentIdentifier(div);
    }
};

<commit_msg>In embedList: Use default actions and widgets to match old behaviour in admin application. Remove old embed code.<commit_after><|endoftext|>


<commit_before>import React from 'react';
import classNames from 'classnames/bind';
import {connectToStores} from 'fluxible-addons-react';
import DeckPageStore from '../../stores/DeckPageStore';
import ServiceErrorStore from '../../stores/ServiceErrorStore';
import hideLeftColumn from '../../actions/deckpagelayout/hideLeftColumn';
import restoreDeckPageLayout from '../../actions/deckpagelayout/restoreDeckPageLayout';
import TreePanel from './TreePanel/TreePanel';
import SlideEditPanel from './SlideEditPanel/SlideEditPanel';
import ContentPanel from './ContentPanel/ContentPanel';
import ContentModulesPanel from './ContentModulesPanel/ContentModulesPanel';
//import ActivityFeedPanel from './ActivityFeedPanel/ActivityFeedPanel';
import ServiceUnavailable from '../Error/ServiceUnavailable';
import InfoPanel from './InfoPanel/InfoPanel';

class Deck extends React.Component {
    handleExpandClick(){
        this.context.executeAction(hideLeftColumn, {});
        return false;
    }
    handleCollapseClick(){
        this.context.executeAction(restoreDeckPageLayout, {});
        return false;
    }
    render() {
        const error = this.props.ServiceErrorStore.error;
        let status = this.props.DeckPageStore.componentsStatus;
        let navigationPanelClass = classNames({
            'twelve': status.NavigationPanel.columnSize===12,
            'sixteen': status.NavigationPanel.columnSize===16,
            'wide column': status.NavigationPanel.visible,
            'hide-element': !status.NavigationPanel.visible
        });
        let leftColClass = classNames({
            'three':  status.TreePanel.columnSize===3 || status.ActivityFeedPanel.columnSize===3,
            'four':  status.TreePanel.columnSize===4 || status.ActivityFeedPanel.columnSize===4,
            'twelve':  status.TreePanel.columnSize===12 || status.ActivityFeedPanel.columnSize===12,
            'sixteen':  status.TreePanel.columnSize===16 || status.ActivityFeedPanel.columnSize===16,
            'wide column': status.TreePanel.visible || status.ActivityFeedPanel.visible,
            'hide-element': !status.TreePanel.visible && !status.ActivityFeedPanel.visible
        });
        let treePanelClass = classNames({
            'hide-element': !status.TreePanel.visible
        });
        let leftColClassSlideEdit = classNames({
            'three':  status.SlideEditPanel.columnSize===3 || status.ActivityFeedPanel.columnSize===3,
            'four':  status.SlideEditPanel.columnSize===4 || status.ActivityFeedPanel.columnSize===4,
            'twelve':  status.SlideEditPanel.columnSize===12 || status.ActivityFeedPanel.columnSize===12,
            'sixteen':  status.SlideEditPanel.columnSize===16 || status.ActivityFeedPanel.columnSize===16,
            'wide column': status.SlideEditPanel.visible || status.ActivityFeedPanel.visible,
            'hide-element': !status.SlideEditPanel.visible && !status.ActivityFeedPanel.visible
        });
        let SlideEditPanelClass = classNames({
            'hide-element': !status.SlideEditPanel.visible
        });
        /*
        let ActivityFeedPanelClass = classNames({
            'hide-element': !status.ActivityFeedPanel.visible
        });
        */
        let centerColClass = classNames({
            'four':  status.ContentPanel.columnSize===4 || status.ContentModulesPanel.columnSize===4,
            'ten':  status.ContentPanel.columnSize===10 || status.ContentModulesPanel.columnSize===10,
            'twelve':  status.ContentPanel.columnSize===12 || status.ContentModulesPanel.columnSize===12,
            'sixteen':  status.ContentPanel.columnSize===16 || status.ContentModulesPanel.columnSize===16,
            'wide column': status.ContentPanel.visible || status.ContentModulesPanel.visible
        });
        let contentPanelClass = classNames({
            'ten':  status.ContentPanel.columnSize===10,
            'twelve':  status.ContentPanel.columnSize===12,
            'sixteen':  status.ContentPanel.columnSize===16,
            'wide column': status.ContentPanel.visible,
            'hide-element': !status.ContentPanel.visible
        });
        let contentModulesPanelClass = classNames({
            'ten':  status.ContentModulesPanel.columnSize===10,
            'twelve':  status.ContentModulesPanel.columnSize===12,
            'sixteen':  status.ContentModulesPanel.columnSize===16,
            'wide column': status.ContentModulesPanel.visible,
            'hide-element': !status.ContentModulesPanel.visible
        });
        let rightColClass = classNames({
            'three':  status.TreePanel.columnSize===3 || status.ActivityFeedPanel.columnSize===3,
            'four':  status.TreePanel.columnSize===4 || status.ActivityFeedPanel.columnSize===4,
            'twelve':  status.TreePanel.columnSize===12 || status.ActivityFeedPanel.columnSize===12,
            'sixteen':  status.TreePanel.columnSize===16 || status.ActivityFeedPanel.columnSize===16,
            'wide column': status.TreePanel.visible || status.ActivityFeedPanel.visible,
            'hide-element': !status.TreePanel.visible && !status.ActivityFeedPanel.visible,
            'ui container': true
        });
        let oneColumnMode = 0;
        if(!status.TreePanel.visible && !status.ActivityFeedPanel.visible){
            oneColumnMode = 1;
        }
        let dividerDIV = '';
        if(oneColumnMode){
            if(status.ContentModulesPanel.visible){
                dividerDIV =

;
            }
        }else{
            dividerDIV =

;
        }
        let leftPanel;
        if(this.props.DeckPageStore.mode === 'edit' && this.props.DeckPageStore.selector.stype == 'slide' && this.props.DeckPageStore.selector.spath !== '')
        {
            //if we view a slide in edit mode - show slide edit panel
            leftPanel =

                                        <SlideEditPanel mode={this.props.DeckPageStore.mode} page={this.props.DeckPageStore.page}/>

;
        }
        else {
            //if we view something else - show decktree
            leftPanel =

                                        <TreePanel mode={this.props.DeckPageStore.mode} page={this.props.DeckPageStore.page}/>

                                    {/*

                                            <ActivityFeedPanel />

*/}

;
        }
        return (

                {error.hasOwnProperty('statusCode') ? <ServiceUnavailable error={this.props.ServiceErrorStore.error} /> : ''}

                    {/*}

                      <NavigationPanel />

*/}

                {leftPanel}

                {dividerDIV}

                            <ContentPanel />

                                {this.props.DeckPageStore.mode !== 'view'? '' : <ContentModulesPanel mode='deck' />}

                        <InfoPanel />

        );
    }
}

Deck.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};
Deck = connectToStores(Deck, [DeckPageStore, ServiceErrorStore], (context, props) => {
    return {
        DeckPageStore: context.getStore(DeckPageStore).getState(),
        ServiceErrorStore: context.getStore(ServiceErrorStore).getState(),
    };
});
export default Deck;
<commit_msg>Better syntax<commit_after>import React from 'react';
import classNames from 'classnames/bind';
import {connectToStores} from 'fluxible-addons-react';
import DeckPageStore from '../../stores/DeckPageStore';
import ServiceErrorStore from '../../stores/ServiceErrorStore';
import hideLeftColumn from '../../actions/deckpagelayout/hideLeftColumn';
import restoreDeckPageLayout from '../../actions/deckpagelayout/restoreDeckPageLayout';
import TreePanel from './TreePanel/TreePanel';
import SlideEditPanel from './SlideEditPanel/SlideEditPanel';
import ContentPanel from './ContentPanel/ContentPanel';
import ContentModulesPanel from './ContentModulesPanel/ContentModulesPanel';
//import ActivityFeedPanel from './ActivityFeedPanel/ActivityFeedPanel';
import ServiceUnavailable from '../Error/ServiceUnavailable';
import InfoPanel from './InfoPanel/InfoPanel';

class Deck extends React.Component {
    handleExpandClick(){
        this.context.executeAction(hideLeftColumn, {});
        return false;
    }
    handleCollapseClick(){
        this.context.executeAction(restoreDeckPageLayout, {});
        return false;
    }
    render() {
        const error = this.props.ServiceErrorStore.error;
        let status = this.props.DeckPageStore.componentsStatus;
        let navigationPanelClass = classNames({
            'twelve': status.NavigationPanel.columnSize===12,
            'sixteen': status.NavigationPanel.columnSize===16,
            'wide column': status.NavigationPanel.visible,
            'hide-element': !status.NavigationPanel.visible
        });
        let leftColClass = classNames({
            'three':  status.TreePanel.columnSize===3 || status.ActivityFeedPanel.columnSize===3,
            'four':  status.TreePanel.columnSize===4 || status.ActivityFeedPanel.columnSize===4,
            'twelve':  status.TreePanel.columnSize===12 || status.ActivityFeedPanel.columnSize===12,
            'sixteen':  status.TreePanel.columnSize===16 || status.ActivityFeedPanel.columnSize===16,
            'wide column': status.TreePanel.visible || status.ActivityFeedPanel.visible,
            'hide-element': !status.TreePanel.visible && !status.ActivityFeedPanel.visible
        });
        let treePanelClass = classNames({
            'hide-element': !status.TreePanel.visible
        });
        let leftColClassSlideEdit = classNames({
            'three':  status.SlideEditPanel.columnSize===3 || status.ActivityFeedPanel.columnSize===3,
            'four':  status.SlideEditPanel.columnSize===4 || status.ActivityFeedPanel.columnSize===4,
            'twelve':  status.SlideEditPanel.columnSize===12 || status.ActivityFeedPanel.columnSize===12,
            'sixteen':  status.SlideEditPanel.columnSize===16 || status.ActivityFeedPanel.columnSize===16,
            'wide column': status.SlideEditPanel.visible || status.ActivityFeedPanel.visible,
            'hide-element': !status.SlideEditPanel.visible && !status.ActivityFeedPanel.visible
        });
        let SlideEditPanelClass = classNames({
            'hide-element': !status.SlideEditPanel.visible
        });
        /*
        let ActivityFeedPanelClass = classNames({
            'hide-element': !status.ActivityFeedPanel.visible
        });
        */
        let centerColClass = classNames({
            'four':  status.ContentPanel.columnSize===4 || status.ContentModulesPanel.columnSize===4,
            'ten':  status.ContentPanel.columnSize===10 || status.ContentModulesPanel.columnSize===10,
            'twelve':  status.ContentPanel.columnSize===12 || status.ContentModulesPanel.columnSize===12,
            'sixteen':  status.ContentPanel.columnSize===16 || status.ContentModulesPanel.columnSize===16,
            'wide column': status.ContentPanel.visible || status.ContentModulesPanel.visible
        });
        let contentPanelClass = classNames({
            'ten':  status.ContentPanel.columnSize===10,
            'twelve':  status.ContentPanel.columnSize===12,
            'sixteen':  status.ContentPanel.columnSize===16,
            'wide column': status.ContentPanel.visible,
            'hide-element': !status.ContentPanel.visible
        });
        let contentModulesPanelClass = classNames({
            'ten':  status.ContentModulesPanel.columnSize===10,
            'twelve':  status.ContentModulesPanel.columnSize===12,
            'sixteen':  status.ContentModulesPanel.columnSize===16,
            'wide column': status.ContentModulesPanel.visible,
            'hide-element': !status.ContentModulesPanel.visible
        });
        let rightColClass = classNames({
            'three':  status.TreePanel.columnSize===3 || status.ActivityFeedPanel.columnSize===3,
            'four':  status.TreePanel.columnSize===4 || status.ActivityFeedPanel.columnSize===4,
            'twelve':  status.TreePanel.columnSize===12 || status.ActivityFeedPanel.columnSize===12,
            'sixteen':  status.TreePanel.columnSize===16 || status.ActivityFeedPanel.columnSize===16,
            'wide column': status.TreePanel.visible || status.ActivityFeedPanel.visible,
            'hide-element': !status.TreePanel.visible && !status.ActivityFeedPanel.visible,
            'ui container': true
        });
        let oneColumnMode = 0;
        if(!status.TreePanel.visible && !status.ActivityFeedPanel.visible){
            oneColumnMode = 1;
        }
        let dividerDIV = '';
        if(oneColumnMode){
            if(status.ContentModulesPanel.visible){
                dividerDIV =

;
            }
        }else{
            dividerDIV =

;
        }
        let leftPanel;
        if(this.props.DeckPageStore.mode === 'edit' && this.props.DeckPageStore.selector.stype === 'slide' && this.props.DeckPageStore.selector.spath !== '')
        {
            //if we view a slide in edit mode - show slide edit panel
            leftPanel =

                                        <SlideEditPanel mode={this.props.DeckPageStore.mode} page={this.props.DeckPageStore.page}/>

;
        }
        else {
            //if we view something else - show decktree
            leftPanel =

                                        <TreePanel mode={this.props.DeckPageStore.mode} page={this.props.DeckPageStore.page}/>

                                    {/*

                                            <ActivityFeedPanel />

*/}

;
        }
        return (

                {error.hasOwnProperty('statusCode') ? <ServiceUnavailable error={this.props.ServiceErrorStore.error} /> : ''}

                    {/*}

                      <NavigationPanel />

*/}

                {leftPanel}

                {dividerDIV}

                            <ContentPanel />

                                {this.props.DeckPageStore.mode !== 'view'? '' : <ContentModulesPanel mode='deck' />}

                        <InfoPanel />

        );
    }
}

Deck.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};
Deck = connectToStores(Deck, [DeckPageStore, ServiceErrorStore], (context, props) => {
    return {
        DeckPageStore: context.getStore(DeckPageStore).getState(),
        ServiceErrorStore: context.getStore(ServiceErrorStore).getState(),
    };
});
export default Deck;
<|endoftext|>


<commit_before>/*!
 * jquery.selectpicker v0.1.2
 *
 * Copyright (c) 2012 Takayuki Sugita, http://github.com/sugilog
 * Released under the MIT License
*/
(function($) {

$.fn.selectpickerOptionsClose = function() {
  this.selectpicker({ callWidget: "hide" });
};
$.fn.selectpickerOptionsOpen = function() {
  this.selectpicker({ callWidget: "show" });
};
$.fn.selectpickerOptionsToggle = function() {
  this.selectpicker({ callWidget: "toggle" });
};
$.fn.selectpickerEnable = function() {
  this.selectpicker({ callWidget: "enable" });
};
$.fn.selectpickerDisable = function() {
  this.selectpicker({ callWidget: "disable" });
};
$.fn.selectpickerIsDisabled = function() {
  return this.selectpicker({ callWidget: "isDisabled" });
};
$.fn.selectpicker = function(_options) {
  // prepare
  var _this = this;
  _options = _options ? _options : {};

  var selectpickerItems = {
    select: {
      id:   "#" + $(this).eq(0).prop("id"),
      name: $(this).eq(0).prop("name"),
      labels: [],
      values: [],
      searchWords: []
    },
    dataKey: "selectpicker_option_value",
    cssClass: {
      base:    "selectpicker_base",
      frame:   "selectpicker_frame",
      label:   "selectpicker_label",
      search:  "selectpicker_search",
      list:    "selectpicker_list",
      item:    "selectpicker_item",
      open:    "selectpicker_label_open",
      close:   "selectpicker_label_close",
      current: "selectpicker_current_pick"
    },
    scrollDuration: (_options.scrollDuration || 10),
    tabIndex: (_options.tabIndex || $(this).prop("tabIndex") || 0)
  };

  $(this).find("option").each(function(idx, val) {
    var label = val.text;
    var searchWord = label;
    var kana = $(val).data("kana");

    if (typeof kana !== "undefined" && kana.toString().length > 0) {
      searchWord = label + "," + kana;
    }

    selectpickerItems.select.labels.push(label);
    selectpickerItems.select.values.push($(val).val());
    selectpickerItems.select.searchWords.push(searchWord);
  });

  var selectpickerWidget = {};
  selectpickerWidget.loaded = false;
  selectpickerWidget.picker = {
    baseId:  "#selectpicker_" + selectpickerItems.select.id.replace("#", ""),
    frameId: "#selectpicker_" + selectpickerItems.select.id.replace("#", "") + "_frame",
    labelId: "#selectpicker_" + selectpickerItems.select.id.replace("#", "") + "_label",
    append: function() {
      $(_this)
        .prop("disabled", true)
        .hide()
        .after(
          $("<div>")
            .prop({id: this.baseId.replace("#", "")})
            .css({position: "relative"})
            .addClass(selectpickerItems.cssClass.base)
            .append(
              $("<div>")
                .prop({id: this.frameId.replace("#", "")})
                .css({position: "absolute", zIndex: 100})
                .addClass(selectpickerItems.cssClass.frame)
                .append(
                  $("<div>")
                    .prop({id: this.labelId.replace("#", ""), tabIndex: selectpickerItems.tabIndex})
                    .addClass(selectpickerItems.cssClass.label)
                )
            )
            .append(
              $("<input>")
                .addClass("fakeInput")
                .prop({type: "text", tabIndex: -1})
                .css({width: 1, height: 1, border: 0, outline: 0, position: "absolute", top: -9999, left: -9999})
            )
        );
    }
  };
  selectpickerWidget.form = {
    id: selectpickerWidget.picker.frameId + "_hidden",
    append: function() {
      $(selectpickerWidget.picker.frameId)
        .append(
          $("<input>")
            .prop({
              type: "hidden",
              name: selectpickerItems.select.name,
              id:   this.id.replace("#", "")
            })
        );
      this.set($(selectpickerItems.select.id).val());
    },
    set: function(value) {
      if (typeof value === "undefined") {
        value = $(selectpickerItems.select.id).children(":first").val();
      }
      $(selectpickerItems.select.id).val(value);

      var label = $(selectpickerItems.select.id).find(":selected").text()

      $(this.id).val(value);
      $(selectpickerWidget.picker.labelId).text(label);

      if (selectpickerWidget.loaded) {
        // XXX: fake input to make enter-key-form-submitable
        $(selectpickerWidget.picker.baseId).find(".fakeInput").focus().select()

        if (typeof _options.onPick !== "undefined") {
          _options.onPick.apply(_this, [value, label]);
        }
      }
      else {
        if (typeof _options.onLoad !== "undefined") {
          _options.onLoad.apply(_this, [value, label]);
        }

        selectpickerWidget.loaded = true;
      }
    }
  };
  selectpickerWidget.options = {
    append: function(options) {
      var that = this;
      var base = that.base();

      $(options).each(function(_, val) {
        base.find(that.childId).append(that.child(val.label, val.value))
      });

      selectpickerWidget.options.setCurrentPick();
    },
    hide: function() {
      if ($(selectpickerWidget.form.id).is(":disabled")) {
        return;
      }

      $(selectpickerWidget.picker.frameId).css({zIndex: 100});
      $(this.baseId).hide();
      $(selectpickerWidget.picker.labelId)
        .removeClass(selectpickerItems.cssClass.close)
        .addClass(selectpickerItems.cssClass.open);

      // FOCUS
      $(selectpickerWidget.options.inputId).prop({tabIndex: 0});
      $(selectpickerWidget.picker.labelId)
        .prop({tabIndex: selectpickerItems.tabIndex})
        .off("focus.selectpicker")
        .on("focus.selectpicker", function(){
          selectpickerWidget.options.show();
        })

      setTimeout(function() {
        $(selectpickerWidget.picker.labelId).off("click.selectpicker");
      }, 300);
    },
    show: function() {
      $(this.baseId).show();
      $(selectpickerWidget.picker.frameId).css({zIndex: 999});
      $(this.inputId).focus().select();
      $(selectpickerWidget.picker.labelId)
        .removeClass(selectpickerItems.cssClass.open)
        .addClass(selectpickerItems.cssClass.close);

      selectpickerWidget.options.setCurrentPick();

      // FOCUS
      $(selectpickerWidget.picker.labelId)
        .prop({tabIndex: -1})
        .off("focus.selectpicker");

      setTimeout(function() {
        $(selectpickerWidget.picker.labelId)
          .on("click.selectpicker", function(){
            selectpickerWidget.options.hide();
          });
      }, 300);

      $(selectpickerWidget.options.inputId)
        .prop({tabIndex: selectpickerItems.tabIndex})
        .one("blur.selectpicker", function() {
          selectpickerWidget.options.hide();
        });
    },
    toggle: function() {
      if ($(selectpickerWidget.picker.labelId).hasClass(selectpickerItems.cssClass.open)) {
        this.show();
      }
      else {
        this.hide();
      }
    },
    disable: function() {
      this.hide();
      $(selectpickerWidget.form.id).prop("disabled", true);
      $(selectpickerWidget.picker.labelId)
        .prop({tabIndex: -1})
        .css({opacity: 0.5})
        .off("focus.selectpicker");
    },
    enable: function() {
      $(selectpickerWidget.form.id).prop("disabled", false);
      $(selectpickerWidget.picker.labelId).css({opacity: 1});
      $(selectpickerWidget.picker.labelId).on("focus.selectpicker", function() {
        selectpickerWidget.options.show();
      });
    },
    isDisabled: function() {
      return $(selectpickerWidget.form.id).prop("disabled");
    },
    baseId:  selectpickerWidget.picker.frameId + "_options",
    childId: selectpickerWidget.picker.frameId + "_options_child",
    inputId: selectpickerWidget.picker.frameId + "_options_search",
    base: function() {
      var optionsBase;

      if ($(this.baseId).length <= 0) {
        optionsBase = $("<div>").prop({id: this.baseId.replace("#", "")}).append(this.search());
        $(selectpickerWidget.picker.frameId).append(optionsBase);
      }
      else {
        optionsBase = $(this.baseId);
      }

      if (optionsBase.find(this.childId).length <= 0) {
        optionsBase
          .append(
            $("<ul>")
              .prop({id: this.childId.replace("#", "")})
              .addClass(selectpickerItems.cssClass.list)
              .on("mouseover.selectpicker", function() {
                $(selectpickerWidget.options.inputId).off("blur.selectpicker")
              })
              .on("mouseout.selectpicker", function() {
                $(selectpickerWidget.options.inputId).on("blur.selectpicker", function() {
                  selectpickerWidget.options.hide();
                })
              })
          );
      }
      else {
        optionsBase.find(this.childId).children().remove();
      }

      return optionsBase;
    },
    search: function() {
      return $("<input>")
        .addClass(selectpickerItems.cssClass.search)
        .prop({
          type: "text",
          id:   this.inputId.replace("#", ""),
          "autocomplete": "off"
        })
        .attr("autocomplete", "off");
        // for IE bug; attr autocomplete is not work for html attributes; only autocomplete??
    },
    child: function(label, value) {
      return $("<li>")
        .data(selectpickerItems.dataKey, value)
        .addClass(selectpickerItems.cssClass.item)
        .append(
          $("<a>")
            .prop({href: "javascript:void(0)", tabIndex: -1})
            .text(label)
            .on("click.selectpicker", function(){
              selectpickerWidget.form.set($(this).closest("li").data(selectpickerItems.dataKey));
              selectpickerWidget.options.hide();
            })
        )
    },
    find: function(query) {
      var that = this;

      return $(selectpickerItems.select.searchWords).map(function(idx, val){
        if (that.matchAll(query, val)) {
          return {
            value: selectpickerItems.select.values[idx],
            label: selectpickerItems.select.labels[idx]
          };
        }
      }).toArray();
    },
    matchAll: function(query, sequence) {
      var regexes = [/.*/];

      if (query.length > 0) {
        regexes = $(query.split(/(?:\s|　)/)).map(function(idx, val){
          return new RegExp(val, "i")
        }).toArray();
      }

      var result = true

      $.each(regexes, function(_, regex) {
        if (!regex.test(sequence)) {
          result = false
          return
        }
      })

      return result;
    },
    findCurrentPick: function() {
      var currentPick;

      $(selectpickerWidget.options.childId).find("li").each(function() {
        if ($(this).hasClass(selectpickerItems.cssClass.current)) {
          currentPick = $(this);
          return;
        }
      });

      return currentPick;
    },
    setCurrentPick: function(currentPick) {
      if (typeof currentPick === "undefined") {
        currentPick = selectpickerWidget.options.findCurrentPick() || $(selectpickerWidget.options.childId).children(":first");
      }

      if (currentPick.length != 0) {
        currentPick.addClass(selectpickerItems.cssClass.current);

        var scrollOption = {scrollTop: (currentPick.offset().top - currentPick.parent().children(":first").offset().top)};
        currentPick.parent().animate(scrollOption, selectpickerItems.scrollDuration);
      }

      return currentPick;
    }
  };

  if (typeof _options.callWidget !== "undefined") {
    return selectpickerWidget.options[_options.callWidget]();
  }
  else {
    selectpickerWidget.picker.append();
    selectpickerWidget.options.append(selectpickerWidget.options.find(""));
    selectpickerWidget.form.append();
    selectpickerWidget.options.hide();

    $(_this).selectpickerEnable();

    $(selectpickerWidget.options.inputId).observeField(0.2, function() {
      var query = $(this).val();
      var results = selectpickerWidget.options.find(query);
      selectpickerWidget.options.append( (results.length == 0) ? {label: ("not found for \"" + query + "\""), value: ""} : results);
    });

    $(selectpickerWidget.options.inputId).keydown(function(e) {
      if (e.keyCode == "13" || e.keyCode == "38" || e.keyCode == "40") {
        var currentPick = selectpickerWidget.options.setCurrentPick(selectpickerWidget.options.findCurrentPick());

        if (e.keyCode == "13") {
          selectpickerWidget.form.set(currentPick.data(selectpickerItems.dataKey));
          selectpickerWidget.options.hide();

          return false;
        }
        else {
          var target = ((e.keyCode == "38") ? currentPick.prev() : currentPick.next());

          if (target.length > 0) {
            selectpickerWidget.options.setCurrentPick(target);
            currentPick.removeClass(selectpickerItems.cssClass.current);
          }
        }
      }
    });

    $("." + selectpickerItems.cssClass.base).outerOff("click.selectpicker");
    $("." + selectpickerItems.cssClass.base).outerOn("click.selectpicker", function(e){
      $(this).each(function(){
        $(this).prev().selectpickerOptionsClose();
      });
    });
  }
}

if (typeof $.fn.outerOn === "undefined" && typeof $.fn.outerOff === "undefined") {
  $.fn.outerOn = function() {
    var args = $(arguments).toArray();
    var _this = this;
    var handleEvent = (args.shift() + [".outer" + "_" + _this.eq(0).prop("id")].join());
    var selector = "body";

    if (typeof args[0] !== "function") {
      selector = args.shift();
    }

    var callback = args.shift();

    $(selector).on(handleEvent, function(e) {
      if ($(e.target).closest(_this).length === 0) {
        callback.apply(_this, [e]);
      }
    });
  };

  $.fn.outerOff = function() {
    var args = $(arguments).toArray();
    var _this = this;
    var handleEvent = (args.shift() + [".outer" + "_" + _this.eq(0).prop("id")].join());
    var selector = "body";

    if (typeof args[0] !== "undefined") {
      selector = args.shift();
    }

    $(selector).off(handleEvent);
  }
}

if (typeof $.fn.observeField === "undefined") {
  // jquery.observe_field
  // https://github.com/splendeo/jquery.observe_field
  $.fn.observeField = function(frequency, callback) {
    frequency = frequency * 1000; // translate to milliseconds
    return this.each(function(){
      var _this = $(this);
      var prev = _this.val();
      var check = function() {
        var val = _this.val();
        if(prev != val){
          prev = val;
          _this.map(callback); // invokes the callback on $this
        }
      };
      var reset = function() {
        if(ti){
          clearInterval(ti);
          ti = setInterval(check, frequency);
        }
      };
      check();
      var ti = setInterval(check, frequency); // invoke check periodically
      // reset counter after user interaction
      _this.bind('keyup click mousemove', reset); //mousemove is for selects
    });
  };
}

})(jQuery);
<commit_msg> #5 remove position from fakeInput<commit_after>/*!
 * jquery.selectpicker v0.1.2
 *
 * Copyright (c) 2012 Takayuki Sugita, http://github.com/sugilog
 * Released under the MIT License
*/
(function($) {

$.fn.selectpickerOptionsClose = function() {
  this.selectpicker({ callWidget: "hide" });
};
$.fn.selectpickerOptionsOpen = function() {
  this.selectpicker({ callWidget: "show" });
};
$.fn.selectpickerOptionsToggle = function() {
  this.selectpicker({ callWidget: "toggle" });
};
$.fn.selectpickerEnable = function() {
  this.selectpicker({ callWidget: "enable" });
};
$.fn.selectpickerDisable = function() {
  this.selectpicker({ callWidget: "disable" });
};
$.fn.selectpickerIsDisabled = function() {
  return this.selectpicker({ callWidget: "isDisabled" });
};
$.fn.selectpicker = function(_options) {
  // prepare
  var _this = this;
  _options = _options ? _options : {};

  var selectpickerItems = {
    select: {
      id:   "#" + $(this).eq(0).prop("id"),
      name: $(this).eq(0).prop("name"),
      labels: [],
      values: [],
      searchWords: []
    },
    dataKey: "selectpicker_option_value",
    cssClass: {
      base:    "selectpicker_base",
      frame:   "selectpicker_frame",
      label:   "selectpicker_label",
      search:  "selectpicker_search",
      list:    "selectpicker_list",
      item:    "selectpicker_item",
      open:    "selectpicker_label_open",
      close:   "selectpicker_label_close",
      current: "selectpicker_current_pick"
    },
    scrollDuration: (_options.scrollDuration || 10),
    tabIndex: (_options.tabIndex || $(this).prop("tabIndex") || 0)
  };

  $(this).find("option").each(function(idx, val) {
    var label = val.text;
    var searchWord = label;
    var kana = $(val).data("kana");

    if (typeof kana !== "undefined" && kana.toString().length > 0) {
      searchWord = label + "," + kana;
    }

    selectpickerItems.select.labels.push(label);
    selectpickerItems.select.values.push($(val).val());
    selectpickerItems.select.searchWords.push(searchWord);
  });

  var selectpickerWidget = {};
  selectpickerWidget.loaded = false;
  selectpickerWidget.picker = {
    baseId:  "#selectpicker_" + selectpickerItems.select.id.replace("#", ""),
    frameId: "#selectpicker_" + selectpickerItems.select.id.replace("#", "") + "_frame",
    labelId: "#selectpicker_" + selectpickerItems.select.id.replace("#", "") + "_label",
    append: function() {
      $(_this)
        .prop("disabled", true)
        .hide()
        .after(
          $("<div>")
            .prop({id: this.baseId.replace("#", "")})
            .css({position: "relative"})
            .addClass(selectpickerItems.cssClass.base)
            .append(
              $("<div>")
                .prop({id: this.frameId.replace("#", "")})
                .css({position: "absolute", zIndex: 100})
                .addClass(selectpickerItems.cssClass.frame)
                .append(
                  $("<div>")
                    .prop({id: this.labelId.replace("#", ""), tabIndex: selectpickerItems.tabIndex})
                    .addClass(selectpickerItems.cssClass.label)
                )
            )
            .append(
              $("<input>")
                .addClass("fakeInput")
                .prop({type: "text", tabIndex: -1})
                .css({width: 1, height: 1, border: 0, outline: 0})
            )
        );
    }
  };
  selectpickerWidget.form = {
    id: selectpickerWidget.picker.frameId + "_hidden",
    append: function() {
      $(selectpickerWidget.picker.frameId)
        .append(
          $("<input>")
            .prop({
              type: "hidden",
              name: selectpickerItems.select.name,
              id:   this.id.replace("#", "")
            })
        );
      this.set($(selectpickerItems.select.id).val());
    },
    set: function(value) {
      if (typeof value === "undefined") {
        value = $(selectpickerItems.select.id).children(":first").val();
      }
      $(selectpickerItems.select.id).val(value);

      var label = $(selectpickerItems.select.id).find(":selected").text()

      $(this.id).val(value);
      $(selectpickerWidget.picker.labelId).text(label);

      if (selectpickerWidget.loaded) {
        // XXX: fake input to make enter-key-form-submitable
        $(selectpickerWidget.picker.baseId).find(".fakeInput").focus().select()

        if (typeof _options.onPick !== "undefined") {
          _options.onPick.apply(_this, [value, label]);
        }
      }
      else {
        if (typeof _options.onLoad !== "undefined") {
          _options.onLoad.apply(_this, [value, label]);
        }

        selectpickerWidget.loaded = true;
      }
    }
  };
  selectpickerWidget.options = {
    append: function(options) {
      var that = this;
      var base = that.base();

      $(options).each(function(_, val) {
        base.find(that.childId).append(that.child(val.label, val.value))
      });

      selectpickerWidget.options.setCurrentPick();
    },
    hide: function() {
      if ($(selectpickerWidget.form.id).is(":disabled")) {
        return;
      }

      $(selectpickerWidget.picker.frameId).css({zIndex: 100});
      $(this.baseId).hide();
      $(selectpickerWidget.picker.labelId)
        .removeClass(selectpickerItems.cssClass.close)
        .addClass(selectpickerItems.cssClass.open);

      // FOCUS
      $(selectpickerWidget.options.inputId).prop({tabIndex: 0});
      $(selectpickerWidget.picker.labelId)
        .prop({tabIndex: selectpickerItems.tabIndex})
        .off("focus.selectpicker")
        .on("focus.selectpicker", function(){
          selectpickerWidget.options.show();
        })

      setTimeout(function() {
        $(selectpickerWidget.picker.labelId).off("click.selectpicker");
      }, 300);
    },
    show: function() {
      $(this.baseId).show();
      $(selectpickerWidget.picker.frameId).css({zIndex: 999});
      $(this.inputId).focus().select();
      $(selectpickerWidget.picker.labelId)
        .removeClass(selectpickerItems.cssClass.open)
        .addClass(selectpickerItems.cssClass.close);

      selectpickerWidget.options.setCurrentPick();

      // FOCUS
      $(selectpickerWidget.picker.labelId)
        .prop({tabIndex: -1})
        .off("focus.selectpicker");

      setTimeout(function() {
        $(selectpickerWidget.picker.labelId)
          .on("click.selectpicker", function(){
            selectpickerWidget.options.hide();
          });
      }, 300);

      $(selectpickerWidget.options.inputId)
        .prop({tabIndex: selectpickerItems.tabIndex})
        .one("blur.selectpicker", function() {
          selectpickerWidget.options.hide();
        });
    },
    toggle: function() {
      if ($(selectpickerWidget.picker.labelId).hasClass(selectpickerItems.cssClass.open)) {
        this.show();
      }
      else {
        this.hide();
      }
    },
    disable: function() {
      this.hide();
      $(selectpickerWidget.form.id).prop("disabled", true);
      $(selectpickerWidget.picker.labelId)
        .prop({tabIndex: -1})
        .css({opacity: 0.5})
        .off("focus.selectpicker");
    },
    enable: function() {
      $(selectpickerWidget.form.id).prop("disabled", false);
      $(selectpickerWidget.picker.labelId).css({opacity: 1});
      $(selectpickerWidget.picker.labelId).on("focus.selectpicker", function() {
        selectpickerWidget.options.show();
      });
    },
    isDisabled: function() {
      return $(selectpickerWidget.form.id).prop("disabled");
    },
    baseId:  selectpickerWidget.picker.frameId + "_options",
    childId: selectpickerWidget.picker.frameId + "_options_child",
    inputId: selectpickerWidget.picker.frameId + "_options_search",
    base: function() {
      var optionsBase;

      if ($(this.baseId).length <= 0) {
        optionsBase = $("<div>").prop({id: this.baseId.replace("#", "")}).append(this.search());
        $(selectpickerWidget.picker.frameId).append(optionsBase);
      }
      else {
        optionsBase = $(this.baseId);
      }

      if (optionsBase.find(this.childId).length <= 0) {
        optionsBase
          .append(
            $("<ul>")
              .prop({id: this.childId.replace("#", "")})
              .addClass(selectpickerItems.cssClass.list)
              .on("mouseover.selectpicker", function() {
                $(selectpickerWidget.options.inputId).off("blur.selectpicker")
              })
              .on("mouseout.selectpicker", function() {
                $(selectpickerWidget.options.inputId).on("blur.selectpicker", function() {
                  selectpickerWidget.options.hide();
                })
              })
          );
      }
      else {
        optionsBase.find(this.childId).children().remove();
      }

      return optionsBase;
    },
    search: function() {
      return $("<input>")
        .addClass(selectpickerItems.cssClass.search)
        .prop({
          type: "text",
          id:   this.inputId.replace("#", ""),
          "autocomplete": "off"
        })
        .attr("autocomplete", "off");
        // for IE bug; attr autocomplete is not work for html attributes; only autocomplete??
    },
    child: function(label, value) {
      return $("<li>")
        .data(selectpickerItems.dataKey, value)
        .addClass(selectpickerItems.cssClass.item)
        .append(
          $("<a>")
            .prop({href: "javascript:void(0)", tabIndex: -1})
            .text(label)
            .on("click.selectpicker", function(){
              selectpickerWidget.form.set($(this).closest("li").data(selectpickerItems.dataKey));
              selectpickerWidget.options.hide();
            })
        )
    },
    find: function(query) {
      var that = this;

      return $(selectpickerItems.select.searchWords).map(function(idx, val){
        if (that.matchAll(query, val)) {
          return {
            value: selectpickerItems.select.values[idx],
            label: selectpickerItems.select.labels[idx]
          };
        }
      }).toArray();
    },
    matchAll: function(query, sequence) {
      var regexes = [/.*/];

      if (query.length > 0) {
        regexes = $(query.split(/(?:\s|　)/)).map(function(idx, val){
          return new RegExp(val, "i")
        }).toArray();
      }

      var result = true

      $.each(regexes, function(_, regex) {
        if (!regex.test(sequence)) {
          result = false
          return
        }
      })

      return result;
    },
    findCurrentPick: function() {
      var currentPick;

      $(selectpickerWidget.options.childId).find("li").each(function() {
        if ($(this).hasClass(selectpickerItems.cssClass.current)) {
          currentPick = $(this);
          return;
        }
      });

      return currentPick;
    },
    setCurrentPick: function(currentPick) {
      if (typeof currentPick === "undefined") {
        currentPick = selectpickerWidget.options.findCurrentPick() || $(selectpickerWidget.options.childId).children(":first");
      }

      if (currentPick.length != 0) {
        currentPick.addClass(selectpickerItems.cssClass.current);

        var scrollOption = {scrollTop: (currentPick.offset().top - currentPick.parent().children(":first").offset().top)};
        currentPick.parent().animate(scrollOption, selectpickerItems.scrollDuration);
      }

      return currentPick;
    }
  };

  if (typeof _options.callWidget !== "undefined") {
    return selectpickerWidget.options[_options.callWidget]();
  }
  else {
    selectpickerWidget.picker.append();
    selectpickerWidget.options.append(selectpickerWidget.options.find(""));
    selectpickerWidget.form.append();
    selectpickerWidget.options.hide();

    $(_this).selectpickerEnable();

    $(selectpickerWidget.options.inputId).observeField(0.2, function() {
      var query = $(this).val();
      var results = selectpickerWidget.options.find(query);
      selectpickerWidget.options.append( (results.length == 0) ? {label: ("not found for \"" + query + "\""), value: ""} : results);
    });

    $(selectpickerWidget.options.inputId).keydown(function(e) {
      if (e.keyCode == "13" || e.keyCode == "38" || e.keyCode == "40") {
        var currentPick = selectpickerWidget.options.setCurrentPick(selectpickerWidget.options.findCurrentPick());

        if (e.keyCode == "13") {
          selectpickerWidget.form.set(currentPick.data(selectpickerItems.dataKey));
          selectpickerWidget.options.hide();

          return false;
        }
        else {
          var target = ((e.keyCode == "38") ? currentPick.prev() : currentPick.next());

          if (target.length > 0) {
            selectpickerWidget.options.setCurrentPick(target);
            currentPick.removeClass(selectpickerItems.cssClass.current);
          }
        }
      }
    });

    $("." + selectpickerItems.cssClass.base).outerOff("click.selectpicker");
    $("." + selectpickerItems.cssClass.base).outerOn("click.selectpicker", function(e){
      $(this).each(function(){
        $(this).prev().selectpickerOptionsClose();
      });
    });
  }
}

if (typeof $.fn.outerOn === "undefined" && typeof $.fn.outerOff === "undefined") {
  $.fn.outerOn = function() {
    var args = $(arguments).toArray();
    var _this = this;
    var handleEvent = (args.shift() + [".outer" + "_" + _this.eq(0).prop("id")].join());
    var selector = "body";

    if (typeof args[0] !== "function") {
      selector = args.shift();
    }

    var callback = args.shift();

    $(selector).on(handleEvent, function(e) {
      if ($(e.target).closest(_this).length === 0) {
        callback.apply(_this, [e]);
      }
    });
  };

  $.fn.outerOff = function() {
    var args = $(arguments).toArray();
    var _this = this;
    var handleEvent = (args.shift() + [".outer" + "_" + _this.eq(0).prop("id")].join());
    var selector = "body";

    if (typeof args[0] !== "undefined") {
      selector = args.shift();
    }

    $(selector).off(handleEvent);
  }
}

if (typeof $.fn.observeField === "undefined") {
  // jquery.observe_field
  // https://github.com/splendeo/jquery.observe_field
  $.fn.observeField = function(frequency, callback) {
    frequency = frequency * 1000; // translate to milliseconds
    return this.each(function(){
      var _this = $(this);
      var prev = _this.val();
      var check = function() {
        var val = _this.val();
        if(prev != val){
          prev = val;
          _this.map(callback); // invokes the callback on $this
        }
      };
      var reset = function() {
        if(ti){
          clearInterval(ti);
          ti = setInterval(check, frequency);
        }
      };
      check();
      var ti = setInterval(check, frequency); // invoke check periodically
      // reset counter after user interaction
      _this.bind('keyup click mousemove', reset); //mousemove is for selects
    });
  };
}

})(jQuery);
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import omit from 'lodash/omit';

import Dropzone from 'react-dropzone';

// Utils
import { post } from 'utils/request';

// Components
import Spinner from 'components/ui/Spinner';

import FormElement from './FormElement';

class File extends FormElement {
  constructor(props) {
    super(props);

    this.state = {
      ...this.state,
      validations: props.validations,
      accepted: [],
      rejected: [],
      dropzoneActive: false,
      loading: false
    };

    // BINDINGS
    this.triggerBrowseOrCancel = this.triggerBrowseOrCancel.bind(this);
    this.onDragEnter = this.onDragEnter.bind(this);
    this.onDragLeave = this.onDragLeave.bind(this);
    this.onDrop = this.onDrop.bind(this);
  }

  /**
   * DROPZONE EVENTS
   * - onDragEnter
   * - onDragLeave
   * - onDrop
  */
  onDragEnter() {
    this.setState({
      dropzoneActive: true
    });
  }

  onDragLeave() {
    this.setState({
      dropzoneActive: false
    });
  }

  onDrop(accepted, rejected) {
    this.setState({
      accepted,
      rejected,
      dropzoneActive: false
    }, () => {
      if (this.state.accepted.length) {
        this.uploadFile(this.state.accepted[0]);
      }
    });
  }

  /**
   * UI EVENTS
   * - triggerBrowseOrCancel
   * - triggerChange
  */
  triggerBrowseOrCancel() {
    const { accepted } = this.state;
    if (accepted.length) {
      this.setState({
        accepted: [],
        value: '',
        validations: ['required', 'url']
      }, () => {
        // Publish the new value to the form
        if (this.props.onChange) this.props.onChange(this.state.value);
        // Trigger validation
        this.triggerValidate();
      });
    } else {
      this.dropzone.open();
    }
  }

  triggerChange(e) {
    this.setState({
      value: e.currentTarget.value,
      validations: ['required', 'url']
    }, () => {
      // Publish the new value to the form
      if (this.props.onChange) this.props.onChange(this.state.value);
      // Trigger validation
      this.triggerValidate();
    });
  }

  /**
   * HELPERS
   * - getFileName
   * - uploadFile
  */
  getFileName() {
    const { accepted } = this.state;

    if (accepted.length) {
      const current = accepted[0];
      return current.name;
    }

    return 'Select file to import data';
  }

  uploadFile(file) {
    const formData = new FormData();
    formData.append('dataset', file);
    formData.append('provider', this.props.properties.provider);

    this.setState({ loading: true, errors: [] });

    post({
      type: 'POST',
      url: `${process.env.WRI_API_URL}/dataset/upload`,
      headers: [{
        key: 'Authorization', value: this.props.properties.authorization
      }],
      body: formData,
      multipart: true,
      onSuccess: ({ connectorUrl, fields }) => {
        this.setState({
          value: connectorUrl,
          validations: ['required'],
          loading: false
        }, () => {
          // Publish the new value to the form
          if (this.props.onChange) this.props.onChange({
            fields,
            value: connectorUrl
          });
          // Trigger validation
          this.triggerValidate();
        });
      },
      onError: (err) => {
        this.setState({
          accepted: [],
          loading: false
        });
        if (this.props.onValid) this.props.onValid(false, err);
      }
    });
  }

  render() {
    const { properties } = this.props;
    const { accepted, loading } = this.state;

    const inputClassName = classnames({
      [properties.className]: !!properties.className
    });

    return (

        <Dropzone
          ref={(node) => { this.dropzone = node; }}
          className="file-dropzone"
          multiple={false}
          disableClick
          disablePreview
          onDrop={this.onDrop}
          onDragEnter={this.onDragEnter}
          onDragLeave={this.onDragLeave}
        >
          {/* {dropzoneActive &&

              Drop files...

          } */}

          <input
            {...omit(properties, 'authorization', 'provider')}
            className={`input ${inputClassName}`}
            value={this.state.value}
            id={`input-${properties.name}`}
            readOnly={!!accepted.length}
            onChange={this.triggerChange}
          />

          <button
            type="button"
            className="c-button -primary -compressed file-button"
            onClick={this.triggerBrowseOrCancel}
          >
            <Spinner className="-light -small" isLoading={loading} />
            {(accepted.length) ? 'Cancel' : 'Browse file'}
          </button>
        </Dropzone>

    );
  }
}

File.propTypes = {
  properties: PropTypes.object.isRequired,
  validations: PropTypes.array,
  onChange: PropTypes.func
};

export default File;
<commit_msg>Filters empty columns in document selection<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import omit from 'lodash/omit';

import Dropzone from 'react-dropzone';

// Utils
import { post } from 'utils/request';

// Components
import Spinner from 'components/ui/Spinner';

import FormElement from './FormElement';

class File extends FormElement {
  constructor(props) {
    super(props);

    this.state = {
      ...this.state,
      validations: props.validations,
      accepted: [],
      rejected: [],
      dropzoneActive: false,
      loading: false
    };

    // BINDINGS
    this.triggerBrowseOrCancel = this.triggerBrowseOrCancel.bind(this);
    this.onDragEnter = this.onDragEnter.bind(this);
    this.onDragLeave = this.onDragLeave.bind(this);
    this.onDrop = this.onDrop.bind(this);
  }

  /**
   * DROPZONE EVENTS
   * - onDragEnter
   * - onDragLeave
   * - onDrop
  */
  onDragEnter() {
    this.setState({
      dropzoneActive: true
    });
  }

  onDragLeave() {
    this.setState({
      dropzoneActive: false
    });
  }

  onDrop(accepted, rejected) {
    this.setState({
      accepted,
      rejected,
      dropzoneActive: false
    }, () => {
      if (this.state.accepted.length) {
        this.uploadFile(this.state.accepted[0]);
      }
    });
  }

  /**
   * UI EVENTS
   * - triggerBrowseOrCancel
   * - triggerChange
  */
  triggerBrowseOrCancel() {
    const { accepted } = this.state;
    if (accepted.length) {
      this.setState({
        accepted: [],
        value: '',
        validations: ['required', 'url']
      }, () => {
        // Publish the new value to the form
        if (this.props.onChange) this.props.onChange(this.state.value);
        // Trigger validation
        this.triggerValidate();
      });
    } else {
      this.dropzone.open();
    }
  }

  triggerChange(e) {
    this.setState({
      value: e.currentTarget.value,
      validations: ['required', 'url']
    }, () => {
      // Publish the new value to the form
      if (this.props.onChange) this.props.onChange(this.state.value);
      // Trigger validation
      this.triggerValidate();
    });
  }

  /**
   * HELPERS
   * - getFileName
   * - uploadFile
  */
  getFileName() {
    const { accepted } = this.state;

    if (accepted.length) {
      const current = accepted[0];
      return current.name;
    }

    return 'Select file to import data';
  }

  uploadFile(file) {
    const formData = new FormData();
    formData.append('dataset', file);
    formData.append('provider', this.props.properties.provider);

    this.setState({ loading: true, errors: [] });

    post({
      type: 'POST',
      url: `${process.env.WRI_API_URL}/dataset/upload`,
      headers: [{
        key: 'Authorization', value: this.props.properties.authorization
      }],
      body: formData,
      multipart: true,
      onSuccess: ({ connectorUrl, fields }) => {
        this.setState({
          value: connectorUrl,
          validations: ['required'],
          loading: false
        }, () => {
          // Publish the new value to the form
          if (this.props.onChange) {
            this.props.onChange({
              // filters non-empty fields
              fields: fields.filter(field => (field || '').length),
              value: connectorUrl
            });
          }
          // Trigger validation
          this.triggerValidate();
        });
      },
      onError: (err) => {
        this.setState({
          accepted: [],
          loading: false
        });
        if (this.props.onValid) this.props.onValid(false, err);
      }
    });
  }

  render() {
    const { properties } = this.props;
    const { accepted, loading } = this.state;

    const inputClassName = classnames({
      [properties.className]: !!properties.className
    });

    return (

        <Dropzone
          ref={(node) => { this.dropzone = node; }}
          className="file-dropzone"
          multiple={false}
          disableClick
          disablePreview
          onDrop={this.onDrop}
          onDragEnter={this.onDragEnter}
          onDragLeave={this.onDragLeave}
        >
          {/* {dropzoneActive &&

              Drop files...

          } */}

          <input
            {...omit(properties, 'authorization', 'provider')}
            className={`input ${inputClassName}`}
            value={this.state.value}
            id={`input-${properties.name}`}
            readOnly={!!accepted.length}
            onChange={this.triggerChange}
          />

          <button
            type="button"
            className="c-button -primary -compressed file-button"
            onClick={this.triggerBrowseOrCancel}
          >
            <Spinner className="-light -small" isLoading={loading} />
            {(accepted.length) ? 'Cancel' : 'Browse file'}
          </button>
        </Dropzone>

    );
  }
}

File.propTypes = {
  properties: PropTypes.object.isRequired,
  validations: PropTypes.array,
  onChange: PropTypes.func
};

export default File;
<|endoftext|>