<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var event = require("../lib/event");
var useragent = require("../lib/useragent");
var dom = require("../lib/dom");
var lang = require("../lib/lang");
var BROKEN_SETDATA = useragent.isChrome < 18;
var USE_IE_MIME_TYPE =  useragent.isIE;

var TextInputIOS = require("./textinput_ios").TextInput;
var TextInput = function(parentNode, host) {
    if (useragent.isIOS)
        return TextInputIOS.call(this, parentNode, host);

    var text = dom.createElement("textarea");
    text.className = "ace_text-input";

    text.setAttribute("wrap", "off");
    text.setAttribute("autocorrect", "off");
    text.setAttribute("autocapitalize", "off");
    text.setAttribute("spellcheck", false);

    text.style.opacity = "0";
    parentNode.insertBefore(text, parentNode.firstChild);

    var PLACEHOLDER = "\u2028\u2028";

    var copied = false;
    var pasted = false;
    var inComposition = false;
    var tempStyle = '';
    var isSelectionEmpty = true;
    var copyWithEmptySelection = false;

    // FOCUS
    // ie9 throws error if document.activeElement is accessed too soon
    try { var isFocused = document.activeElement === text; } catch(e) {}

    event.addListener(text, "blur", function(e) {
        host.onBlur(e);
        isFocused = false;
    });
    event.addListener(text, "focus", function(e) {
        isFocused = true;
        host.onFocus(e);
        resetSelection();
    });
    this.focus = function() {
        if (tempStyle) return text.focus();
        var top = text.style.top;
        text.style.position = "fixed";
        text.style.top = "0px";
        text.focus();
        setTimeout(function() {
            text.style.position = "";
            if (text.style.top == "0px")
                text.style.top = top;
        }, 0);
    };
    this.blur = function() {
        text.blur();
    };
    this.isFocused = function() {
        return isFocused;
    };

    // modifying selection of blured textarea can focus it (chrome mac/linux)
    var syncSelection = lang.delayedCall(function() {
        isFocused && resetSelection(isSelectionEmpty);
    });
    var syncValue = lang.delayedCall(function() {
         if (!inComposition) {
            text.value = PLACEHOLDER;
            isFocused && resetSelection();
         }
    });

    function resetSelection(isEmpty) {
        isEmpty = copyWithEmptySelection ? false : isEmpty;
        if (inComposition)
            return;

        // this prevents infinite recursion on safari 8
        // see https://github.com/ajaxorg/ace/issues/2114
        inComposition = true;

        if (inputHandler) {
            var selectionStart = 0;
            var selectionEnd = isEmpty ? 0 : text.value.length - 1;
        } else {
            var selectionStart = isEmpty ? 2 : 1;
            var selectionEnd = 2;
        }
        // on firefox this throws if textarea is hidden
        try {
            text.setSelectionRange(selectionStart, selectionEnd);
        } catch(e){}

        inComposition = false;
    }

    function resetValue() {
        if (inComposition)
            return;
        text.value = PLACEHOLDER;
        //http://code.google.com/p/chromium/issues/detail?id=76516
        if (useragent.isWebKit)
            syncValue.schedule();
    }

    useragent.isWebKit || host.addEventListener('changeSelection', function() {
        if (host.selection.isEmpty() != isSelectionEmpty) {
            isSelectionEmpty = !isSelectionEmpty;
            syncSelection.schedule();
        }
    });

    resetValue();
    if (isFocused)
        host.onFocus();

    var isAllSelected = function(text) {
        return text.selectionStart === 0 && text.selectionEnd === text.value.length;
    };

    var onSelect = function(e) {
        if (copied) {
            copied = false;
        } else if (isAllSelected(text)) {
            host.selectAll();
            resetSelection();
        } else if (inputHandler) {
            resetSelection(host.selection.isEmpty());
        }
    };

    var inputHandler = null;
    this.setInputHandler = function(cb) {inputHandler = cb;};
    this.getInputHandler = function() {return inputHandler;};
    var afterContextMenu = false;

    var sendText = function(data) {
        if (inputHandler) {
            data = inputHandler(data);
            inputHandler = null;
        }
        if (pasted) {
            resetSelection();
            if (data)
                host.onPaste(data);
            pasted = false;
        } else if (data == PLACEHOLDER.charAt(0)) {
            if (afterContextMenu)
                host.execCommand("del", {source: "ace"});
            else // some versions of android do not fire keydown when pressing backspace
                host.execCommand("backspace", {source: "ace"});
        } else {
            if (data.substring(0, 2) == PLACEHOLDER)
                data = data.substr(2);
            else if (data.charAt(0) == PLACEHOLDER.charAt(0))
                data = data.substr(1);
            else if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0))
                data = data.slice(0, -1);
            // can happen if undo in textarea isn't stopped
            if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0))
                data = data.slice(0, -1);

            if (data)
                host.onTextInput(data);
        }
        if (afterContextMenu)
            afterContextMenu = false;
    };
    var onInput = function(e) {
        // console.log("onInput", inComposition)
        if (inComposition)
            return;
        var data = text.value;
        sendText(data);
        resetValue();
    };

    var handleClipboardData = function(e, data, forceIEMime) {
        var clipboardData = e.clipboardData || window.clipboardData;
        if (!clipboardData || BROKEN_SETDATA)
            return;
        // using "Text" doesn't work on old webkit but ie needs it
        var mime = USE_IE_MIME_TYPE || forceIEMime ? "Text" : "text/plain";
        try {
            if (data) {
                // Safari 5 has clipboardData object, but does not handle setData()
                return clipboardData.setData(mime, data) !== false;
            } else {
                return clipboardData.getData(mime);
            }
        } catch(e) {
            if (!forceIEMime)
                return handleClipboardData(e, data, true);
        }
    };

    var doCopy = function(e, isCut) {
        var data = host.getCopyText();
        if (!data)
            return event.preventDefault(e);

        if (handleClipboardData(e, data)) {
            isCut ? host.onCut() : host.onCopy();
            event.preventDefault(e);
        } else {
            copied = true;
            text.value = data;
            text.select();
            setTimeout(function(){
                copied = false;
                resetValue();
                resetSelection();
                isCut ? host.onCut() : host.onCopy();
            });
        }
    };

    var onCut = function(e) {
        doCopy(e, true);
    };

    var onCopy = function(e) {
        doCopy(e, false);
    };

    var onPaste = function(e) {
        var data = handleClipboardData(e);
        if (typeof data == "string") {
            if (data)
                host.onPaste(data, e);
            if (useragent.isIE)
                setTimeout(resetSelection);
            event.preventDefault(e);
        }
        else {
            text.value = "";
            pasted = true;
        }
    };

    event.addCommandKeyListener(text, host.onCommandKey.bind(host));

    event.addListener(text, "select", onSelect);

    event.addListener(text, "input", onInput);

    event.addListener(text, "cut", onCut);
    event.addListener(text, "copy", onCopy);
    event.addListener(text, "paste", onPaste);

    // Opera has no clipboard events
    if (!('oncut' in text) || !('oncopy' in text) || !('onpaste' in text)) {
        event.addListener(parentNode, "keydown", function(e) {
            if ((useragent.isMac && !e.metaKey) || !e.ctrlKey)
                return;

            switch (e.keyCode) {
                case 67:
                    onCopy(e);
                    break;
                case 86:
                    onPaste(e);
                    break;
                case 88:
                    onCut(e);
                    break;
            }
        });
    }

    // COMPOSITION
    var onCompositionStart = function(e) {
        if (inComposition || !host.onCompositionStart || host.$readOnly)
            return;
        // console.log("onCompositionStart", inComposition)
        inComposition = {};
        inComposition.canUndo = host.session.$undoManager;
        host.onCompositionStart();
        setTimeout(onCompositionUpdate, 0);
        host.on("mousedown", onCompositionEnd);
        if (inComposition.canUndo && !host.selection.isEmpty()) {
            host.insert("");
            host.session.markUndoGroup();
            host.selection.clearSelection();
        }
        host.session.markUndoGroup();
    };

    var onCompositionUpdate = function() {
        // console.log("onCompositionUpdate", inComposition && JSON.stringify(text.value))
        if (!inComposition || !host.onCompositionUpdate || host.$readOnly)
            return;
        var val = text.value.replace(/\u2028/g, "");
        if (inComposition.lastValue === val) return;

        host.onCompositionUpdate(val);
        if (inComposition.lastValue)
            host.undo();
        if (inComposition.canUndo)
            inComposition.lastValue = val;
        if (inComposition.lastValue) {
            var r = host.selection.getRange();
            host.insert(inComposition.lastValue);
            host.session.markUndoGroup();
            inComposition.range = host.selection.getRange();
            host.selection.setRange(r);
            host.selection.clearSelection();
        }
    };

    var onCompositionEnd = function(e) {
        if (!host.onCompositionEnd || host.$readOnly) return;
        // console.log("onCompositionEnd", inComposition &&inComposition.lastValue)
        var c = inComposition;
        inComposition = false;
        var timer = setTimeout(function() {
            timer = null;
            var str = text.value.replace(/\u2028/g, "");
            // console.log(str, c.lastValue)
            if (inComposition)
                return;
            else if (str == c.lastValue)
                resetValue();
            else if (!c.lastValue && str) {
                resetValue();
                sendText(str);
            }
        });
        inputHandler = function compositionInputHandler(str) {
            // console.log("onCompositionEnd", str, c.lastValue)
            if (timer)
                clearTimeout(timer);
            str = str.replace(/\u2028/g, "");
            if (str == c.lastValue)
                return "";
            if (c.lastValue && timer)
                host.undo();
            return str;
        };
        host.onCompositionEnd();
        host.removeListener("mousedown", onCompositionEnd);
        if (e.type == "compositionend" && c.range) {
            host.selection.setRange(c.range);
        }
        // Workaround for #3027, #3045, #3097, #3100, #3249
        var needsOnInput =
            (!!useragent.isChrome && useragent.isChrome >= 53) ||
            (!!useragent.isWebKit && useragent.isWebKit >= 603);

        if (needsOnInput) {
          onInput();
        }
    };

    var syncComposition = lang.delayedCall(onCompositionUpdate, 50);

    event.addListener(text, "compositionstart", onCompositionStart);
    event.addListener(text, "compositionupdate", function(){syncComposition.schedule();});
    event.addListener(text, "keyup", function(){syncComposition.schedule();});
    event.addListener(text, "keydown", function(){syncComposition.schedule();});
    event.addListener(text, "compositionend", onCompositionEnd);

    this.getElement = function() {
        return text;
    };

    this.setReadOnly = function(readOnly) {
       text.readOnly = readOnly;
    };

    this.setCopyWithEmptySelection = function(value) {
        copyWithEmptySelection = value;
    };

    this.onContextMenu = function(e) {
        afterContextMenu = true;
        resetSelection(host.selection.isEmpty());
        host._emit("nativecontextmenu", {target: host, domEvent: e});
        this.moveToMouse(e, true);
    };

    this.moveToMouse = function(e, bringToFront) {
        if (!tempStyle)
            tempStyle = text.style.cssText;
        text.style.cssText = (bringToFront ? "z-index:100000;" : "")
            + "height:" + text.style.height + ";"
            + (useragent.isIE ? "opacity:0.1;" : "");

        var rect = host.container.getBoundingClientRect();
        var style = dom.computedStyle(host.container);
        var top = rect.top + (parseInt(style.borderTopWidth) || 0);
        var left = rect.left + (parseInt(rect.borderLeftWidth) || 0);
        var maxTop = rect.bottom - top - text.clientHeight -2;
        var move = function(e) {
            text.style.left = e.clientX - left - 2 + "px";
            text.style.top = Math.min(e.clientY - top - 2, maxTop) + "px";
        };
        move(e);

        if (e.type != "mousedown")
            return;

        if (host.renderer.$keepTextAreaAtCursor)
            host.renderer.$keepTextAreaAtCursor = null;

        clearTimeout(closeTimeout);
        // on windows context menu is opened after mouseup
        if (useragent.isWin)
            event.capture(host.container, move, onContextMenuClose);
    };

    this.onContextMenuClose = onContextMenuClose;
    var closeTimeout;
    function onContextMenuClose() {
        clearTimeout(closeTimeout);
        closeTimeout = setTimeout(function () {
            if (tempStyle) {
                text.style.cssText = tempStyle;
                tempStyle = '';
            }
            if (host.renderer.$keepTextAreaAtCursor == null) {
                host.renderer.$keepTextAreaAtCursor = true;
                host.renderer.$moveTextAreaToCursor();
            }
        }, 0);
    }

    var onContextMenu = function(e) {
        host.textInput.onContextMenu(e);
        onContextMenuClose();
    };
    event.addListener(text, "mouseup", onContextMenu);
    event.addListener(text, "mousedown", function(e) {
        e.preventDefault();
        onContextMenuClose();
    });
    event.addListener(host.renderer.scroller, "contextmenu", onContextMenu);
    event.addListener(text, "contextmenu", onContextMenu);
};

exports.TextInput = TextInput;
});
<commit_msg>Fixed Windows OS / IE unicode IME not working<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var event = require("../lib/event");
var useragent = require("../lib/useragent");
var dom = require("../lib/dom");
var lang = require("../lib/lang");
var BROKEN_SETDATA = useragent.isChrome < 18;
var USE_IE_MIME_TYPE =  useragent.isIE;

var TextInputIOS = require("./textinput_ios").TextInput;
var TextInput = function(parentNode, host) {
    if (useragent.isIOS)
        return TextInputIOS.call(this, parentNode, host);

    var text = dom.createElement("textarea");
    text.className = "ace_text-input";

    text.setAttribute("wrap", "off");
    text.setAttribute("autocorrect", "off");
    text.setAttribute("autocapitalize", "off");
    text.setAttribute("spellcheck", false);

    text.style.opacity = "0";
    parentNode.insertBefore(text, parentNode.firstChild);

    var PLACEHOLDER = "\u2028\u2028";

    var copied = false;
    var pasted = false;
    var inComposition = false;
    var tempStyle = '';
    var isSelectionEmpty = true;
    var copyWithEmptySelection = false;

    // FOCUS
    // ie9 throws error if document.activeElement is accessed too soon
    try { var isFocused = document.activeElement === text; } catch(e) {}

    event.addListener(text, "blur", function(e) {
        host.onBlur(e);
        isFocused = false;
    });
    event.addListener(text, "focus", function(e) {
        isFocused = true;
        host.onFocus(e);
        resetSelection();
    });
    this.focus = function() {
        if (tempStyle) return text.focus();
        var top = text.style.top;
        text.style.position = "fixed";
        text.style.top = "0px";
        text.focus();
        setTimeout(function() {
            text.style.position = "";
            if (text.style.top == "0px")
                text.style.top = top;
        }, 0);
    };
    this.blur = function() {
        text.blur();
    };
    this.isFocused = function() {
        return isFocused;
    };

    // modifying selection of blured textarea can focus it (chrome mac/linux)
    var syncSelection = lang.delayedCall(function() {
        isFocused && resetSelection(isSelectionEmpty);
    });
    var syncValue = lang.delayedCall(function() {
         if (!inComposition) {
            text.value = PLACEHOLDER;
            isFocused && resetSelection();
         }
    });

    function resetSelection(isEmpty) {
        isEmpty = copyWithEmptySelection ? false : isEmpty;
        if (inComposition)
            return;

        // this prevents infinite recursion on safari 8
        // see https://github.com/ajaxorg/ace/issues/2114
        inComposition = true;

        if (inputHandler) {
            var selectionStart = 0;
            var selectionEnd = isEmpty ? 0 : text.value.length - 1;
        } else {
            var selectionStart = isEmpty ? 2 : 1;
            var selectionEnd = 2;
        }
        // on firefox this throws if textarea is hidden
        try {
            text.setSelectionRange(selectionStart, selectionEnd);
        } catch(e){}

        inComposition = false;
    }

    function resetValue() {
        if (inComposition)
            return;
        text.value = PLACEHOLDER;
        //http://code.google.com/p/chromium/issues/detail?id=76516
        if (useragent.isWebKit)
            syncValue.schedule();
    }

    useragent.isWebKit || host.addEventListener('changeSelection', function() {
        if (host.selection.isEmpty() != isSelectionEmpty) {
            isSelectionEmpty = !isSelectionEmpty;
            syncSelection.schedule();
        }
    });

    resetValue();
    if (isFocused)
        host.onFocus();

    var isAllSelected = function(text) {
        return text.selectionStart === 0 && text.selectionEnd === text.value.length;
    };

    var onSelect = function(e) {
        if (copied) {
            copied = false;
        } else if (isAllSelected(text)) {
            host.selectAll();
            resetSelection();
        } else if (inputHandler) {
            resetSelection(host.selection.isEmpty());
        }
    };

    var inputHandler = null;
    this.setInputHandler = function(cb) {inputHandler = cb;};
    this.getInputHandler = function() {return inputHandler;};
    var afterContextMenu = false;

    var sendText = function(data) {
        if (inputHandler) {
            data = inputHandler(data);
            inputHandler = null;
        }
        if (pasted) {
            resetSelection();
            if (data)
                host.onPaste(data);
            pasted = false;
        } else if (data == PLACEHOLDER.charAt(0)) {
            if (afterContextMenu)
                host.execCommand("del", {source: "ace"});
            else // some versions of android do not fire keydown when pressing backspace
                host.execCommand("backspace", {source: "ace"});
        } else {
            if (data.substring(0, 2) == PLACEHOLDER)
                data = data.substr(2);
            else if (data.charAt(0) == PLACEHOLDER.charAt(0))
                data = data.substr(1);
            else if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0))
                data = data.slice(0, -1);
            // can happen if undo in textarea isn't stopped
            if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0))
                data = data.slice(0, -1);

            if (data)
                host.onTextInput(data);
        }
        if (afterContextMenu)
            afterContextMenu = false;
    };
    var onInput = function(e) {
        // console.log("onInput", inComposition)
        if (inComposition)
            return;
        var data = text.value;
        sendText(data);
        resetValue();
    };

    var handleClipboardData = function(e, data, forceIEMime) {
        var clipboardData = e.clipboardData || window.clipboardData;
        if (!clipboardData || BROKEN_SETDATA)
            return;
        // using "Text" doesn't work on old webkit but ie needs it
        var mime = USE_IE_MIME_TYPE || forceIEMime ? "Text" : "text/plain";
        try {
            if (data) {
                // Safari 5 has clipboardData object, but does not handle setData()
                return clipboardData.setData(mime, data) !== false;
            } else {
                return clipboardData.getData(mime);
            }
        } catch(e) {
            if (!forceIEMime)
                return handleClipboardData(e, data, true);
        }
    };

    var doCopy = function(e, isCut) {
        var data = host.getCopyText();
        if (!data)
            return event.preventDefault(e);

        if (handleClipboardData(e, data)) {
            isCut ? host.onCut() : host.onCopy();
            event.preventDefault(e);
        } else {
            copied = true;
            text.value = data;
            text.select();
            setTimeout(function(){
                copied = false;
                resetValue();
                resetSelection();
                isCut ? host.onCut() : host.onCopy();
            });
        }
    };

    var onCut = function(e) {
        doCopy(e, true);
    };

    var onCopy = function(e) {
        doCopy(e, false);
    };

    var onPaste = function(e) {
        var data = handleClipboardData(e);
        if (typeof data == "string") {
            if (data)
                host.onPaste(data, e);
            if (useragent.isIE)
                setTimeout(resetSelection);
            event.preventDefault(e);
        }
        else {
            text.value = "";
            pasted = true;
        }
    };

    event.addCommandKeyListener(text, host.onCommandKey.bind(host));

    event.addListener(text, "select", onSelect);

    event.addListener(text, "input", onInput);

    event.addListener(text, "cut", onCut);
    event.addListener(text, "copy", onCopy);
    event.addListener(text, "paste", onPaste);

    // Opera has no clipboard events
    if (!('oncut' in text) || !('oncopy' in text) || !('onpaste' in text)) {
        event.addListener(parentNode, "keydown", function(e) {
            if ((useragent.isMac && !e.metaKey) || !e.ctrlKey)
                return;

            switch (e.keyCode) {
                case 67:
                    onCopy(e);
                    break;
                case 86:
                    onPaste(e);
                    break;
                case 88:
                    onCut(e);
                    break;
            }
        });
    }

    // COMPOSITION
    var onCompositionStart = function(e) {
        if (inComposition || !host.onCompositionStart || host.$readOnly)
            return;
        // console.log("onCompositionStart", inComposition)
        inComposition = {};
        inComposition.canUndo = host.session.$undoManager;
        host.onCompositionStart();
        setTimeout(onCompositionUpdate, 0);
        host.on("mousedown", onCompositionEnd);
        if (inComposition.canUndo && !host.selection.isEmpty()) {
            host.insert("");
            host.session.markUndoGroup();
            host.selection.clearSelection();
        }
        host.session.markUndoGroup();
    };

    var onCompositionUpdate = function() {
        // console.log("onCompositionUpdate", inComposition && JSON.stringify(text.value))
        if (!inComposition || !host.onCompositionUpdate || host.$readOnly)
            return;
        var val = text.value.replace(/\u2028/g, "");
        if (inComposition.lastValue === val) return;

        host.onCompositionUpdate(val);
        if (inComposition.lastValue)
            host.undo();
        if (inComposition.canUndo)
            inComposition.lastValue = val;
        if (inComposition.lastValue) {
            var r = host.selection.getRange();
            host.insert(inComposition.lastValue);
            host.session.markUndoGroup();
            inComposition.range = host.selection.getRange();
            host.selection.setRange(r);
            host.selection.clearSelection();
        }
    };

    var onCompositionEnd = function(e) {
        if (!host.onCompositionEnd || host.$readOnly) return;
        // console.log("onCompositionEnd", inComposition &&inComposition.lastValue)
        var c = inComposition;
        inComposition = false;
        var timer = setTimeout(function() {
            timer = null;
            var str = text.value.replace(/\u2028/g, "");
            // console.log(str, c.lastValue)
            if (inComposition)
                return;
            else if (str == c.lastValue)
                resetValue();
            else if (!c.lastValue && str) {
                resetValue();
                sendText(str);
            }
        });
        inputHandler = function compositionInputHandler(str) {
            // console.log("onCompositionEnd", str, c.lastValue)
            if (timer)
                clearTimeout(timer);
            str = str.replace(/\u2028/g, "");
            if (str == c.lastValue)
                return "";
            if (c.lastValue && timer)
                host.undo();
            return str;
        };
        host.onCompositionEnd();
        host.removeListener("mousedown", onCompositionEnd);
        if (e.type == "compositionend" && c.range) {
            host.selection.setRange(c.range);
        }
        // Workaround for #3027, #3045, #3097, #3100, #3249
        var needsOnInput =
            (!!useragent.isChrome && useragent.isChrome >= 53) ||
            (!!useragent.isWebKit && useragent.isWebKit >= 603);

        if (!needsOnInput) {
            if (useragent.isWin && useragent.isIE) {
                needsOnInput = true;
            }
        }

        if (needsOnInput) {
          onInput();
        }
    };

    var syncComposition = lang.delayedCall(onCompositionUpdate, 50);

    event.addListener(text, "compositionstart", onCompositionStart);
    event.addListener(text, "compositionupdate", function(){syncComposition.schedule();});
    event.addListener(text, "keyup", function(){syncComposition.schedule();});
    event.addListener(text, "keydown", function(){syncComposition.schedule();});
    event.addListener(text, "compositionend", onCompositionEnd);

    this.getElement = function() {
        return text;
    };

    this.setReadOnly = function(readOnly) {
       text.readOnly = readOnly;
    };

    this.setCopyWithEmptySelection = function(value) {
        copyWithEmptySelection = value;
    };

    this.onContextMenu = function(e) {
        afterContextMenu = true;
        resetSelection(host.selection.isEmpty());
        host._emit("nativecontextmenu", {target: host, domEvent: e});
        this.moveToMouse(e, true);
    };

    this.moveToMouse = function(e, bringToFront) {
        if (!tempStyle)
            tempStyle = text.style.cssText;
        text.style.cssText = (bringToFront ? "z-index:100000;" : "")
            + "height:" + text.style.height + ";"
            + (useragent.isIE ? "opacity:0.1;" : "");

        var rect = host.container.getBoundingClientRect();
        var style = dom.computedStyle(host.container);
        var top = rect.top + (parseInt(style.borderTopWidth) || 0);
        var left = rect.left + (parseInt(rect.borderLeftWidth) || 0);
        var maxTop = rect.bottom - top - text.clientHeight -2;
        var move = function(e) {
            text.style.left = e.clientX - left - 2 + "px";
            text.style.top = Math.min(e.clientY - top - 2, maxTop) + "px";
        };
        move(e);

        if (e.type != "mousedown")
            return;

        if (host.renderer.$keepTextAreaAtCursor)
            host.renderer.$keepTextAreaAtCursor = null;

        clearTimeout(closeTimeout);
        // on windows context menu is opened after mouseup
        if (useragent.isWin)
            event.capture(host.container, move, onContextMenuClose);
    };

    this.onContextMenuClose = onContextMenuClose;
    var closeTimeout;
    function onContextMenuClose() {
        clearTimeout(closeTimeout);
        closeTimeout = setTimeout(function () {
            if (tempStyle) {
                text.style.cssText = tempStyle;
                tempStyle = '';
            }
            if (host.renderer.$keepTextAreaAtCursor == null) {
                host.renderer.$keepTextAreaAtCursor = true;
                host.renderer.$moveTextAreaToCursor();
            }
        }, 0);
    }

    var onContextMenu = function(e) {
        host.textInput.onContextMenu(e);
        onContextMenuClose();
    };
    event.addListener(text, "mouseup", onContextMenu);
    event.addListener(text, "mousedown", function(e) {
        e.preventDefault();
        onContextMenuClose();
    });
    event.addListener(host.renderer.scroller, "contextmenu", onContextMenu);
    event.addListener(text, "contextmenu", onContextMenu);
};

exports.TextInput = TextInput;
});
<|endoftext|>


<commit_before>/* Handles all the Ajax Requests */

/** Create the XMLHttpRequest object.
 *
 *  @param method: "POST"/"GET"/etc
 *  @param url: the URL to send the Request
 *  @param callback: the callback function to be called on ServerResponse.
 *                   We serve the xmlHttpRequest for that function.
 *  @return xmlHttpRequest ready to be send()
 */
function createRequest(method, url, callback) {

    var xhr = new XMLHttpRequest();

    if ("withCredentials" in xhr) {
        // XHR for Chrome/Firefox/Opera/Safari.
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
        // XDomainRequest for IE.
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        // CORS not supported.
        xhr = null;
    }

    xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
    xhr.withCredentials = true;
    xhr.onload = function () {
        if (xhr.status == 400 || xhr.status == 200 || xhr.status == 401) {
            console.log(xhr);
            callback(xhr);
        } else if (xhr.status == 404 || xhr.status == 408 || xhr.status == 444 ||
                   xhr.status == 503 || xhr.status == 504) {
            console.log(xhr);
            alert("Something went wrong, please check your internet connection!");
            return;
        } else {
            if (xhr.status == 403){
                if (me.state.isCurrent(STATE_LOGIN)) {
                    alert("wrong e-mail or password!");
                }
                return;
            }
            console.log(xhr);
            alert("Internal server error. Please try again, later!");
            return;
        }
    };

    return xhr;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~ Defining the Request-Send-Functions ~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Session ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ POST /login ~ jsonData: JSON.login
function ajaxSendLoginRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/login", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /logout
function ajaxSendLogoutRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/logout", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ User ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ POST /signup ~ jsonData: JSON.signup
function ajaxSendSignupRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/signup", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ POST /users ~ jsonData: JSON.user
function ajaxSendUsersRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/users", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ DELETE /users
function ajaxSendUsersDeleteRequest(onload) {
    var xmlHttpRequest = createRequest("DELETE", "/users", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /users/password
function ajaxSendUsersResetPasswordRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/users/password", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /users/student
function ajaxSendUserStudentRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/users/student", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Profile ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /profile/homework
function ajaxSendProfileHomeworkRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/homework", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /profile
function ajaxSendProfileRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/profile", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /profile/:id ~ id: the ProfileID
function ajaxSendProfileIdRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /profile/character
function ajaxSendProfileCharacterRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/character", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /profile/inventory
function ajaxSendProfileInventoryRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/character", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Item ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /profile/character
function ajaxSendProfileBeltRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/belt", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /profile/belt ~ jsonData: JSON.belt
function ajaxSendProfileBeltSetRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/profile/belt", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /profile/used/:potion,slot ~ potion: PotionID slot: SlotID ~ jsonData: JSON.potionused
function ajaxSendProfileUsedRequest( slot, onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/used/" + slot, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /profile/collected ~ jsonData: JSON.collected
function ajaxSendProfileCollectedRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/profile/collected", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Settings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /profile/settings
function ajaxSendProfileSettingsRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/settings", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /profile/settings ~ jsonData: JSON.settings
function ajaxSendProfileSettingsSetRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/profile/settings", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Challenge ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /challenge/reset
function ajaxSendChallengeResetRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge/reset", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /challenge
function ajaxSendChallengeRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /challenge/skip
function ajaxNextChallengeRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge/skip", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /challenge ~ id: ChallengeID
function ajaxSendChallengeIDRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /challenge ~ jsonData: JSON.challenge
function ajaxSendChallengeCreateRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/challenge", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /challenge/story
function ajaxSendChallengeStoryRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge/story", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET  /profile/avatar/:id
function ajaxSendProfileAvatarIdRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/avatar/"+ id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /challenge/trivia
function ajaxSendChallengeTriviaRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge/trivia", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /challenge/homework
function ajaxSendChallengeHomeworkRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge/homework", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SQLController ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /SQL/Story/:id ~ id: StoryTaskID
function ajaxSendTaskStoryIDRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/SQL/Story/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /SQL/Story/:id ~ id: StoryTaskID, jsonData: JSON.task.solve
function ajaxSendTaskStorySolveRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/SQL/Story/" + id, onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /SQL/Trivia/:id: StoryTaskID | difficulty: DifficultyLevel
function ajaxSendTaskTriviaRequest(difficulty, onload) {
    var xmlHttpRequest = createRequest("GET", "/SQL/Trivia/" + difficulty, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /SQL/Trivia/:id ~ id: TriviaTaskID, jsonData: JSON.task.solve
function ajaxSendTaskTriviaSolveRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/SQL/Trivia/" + id, onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /SQL/Homework
function ajaxSendTaskHomeworkRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/SQL/Homework", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /SQL/Homework/:id ~ id: HomeworkID, jsonData: JSON.task.solve
function ajaxSendTaskHomeworkSolveRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/SQL/Homework/" + id, onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TaskController ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ POST /TaskSet/:id/Task
function ajaxSendTaskOverTaskSetRequest(id, onload) {
    var xmlHttpRequest = createRequest("Post", "/TaskSet/" + id + "/Task", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /Task/
function ajaxSendTaskRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/Task/", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /Task/:id/ ~ id: TaskID
function ajaxSendTaskIdRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/Task/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ PATCH /task/:id ~ id: TaskID, jsonData: JSON.task
function ajaxSendTaskIdEditRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("PATCH", "/task/" + id, onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ DELETE /task/:id ~ id: TaskID, jsonData: JSON.task
function ajaxSendTaskIdEditRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("DELETE", "/task/" + id, onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ POST /Task/:id/rate ~ id: TaskID, jsonData: JSON.rating
function ajaxSendTaskIdRatingRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/Task/" + id + "/rate", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /Task/:id/comment ~ id: TaskID
function ajaxSendTaskIdCommentRequest(id, onload) {
  var xmlHttpRequest = createRequest("GET", "/Task/" + id + "/comment", onload);

  xmlHttpRequest.send();

  return xmlHttpRequest;
}

// ~ POST /task/:id/comment ~ id: TaskID, jsonData: JSON.comment
function ajaxSendTaskIdCommentSetRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/task/" + id + "/comment", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Shop ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /shop
function ajaxSendShopRequest(onload) {
  var xmlHttpRequest = createRequest("GET", "/shop/avatar", onload);

  xmlHttpRequest.send();

  return xmlHttpRequest;
}

// ~ GET /shop/belt
function ajaxSendShopBeltRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/shop/belt", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /shop/:id ~ id: ItemID, [jsonData: JSON.shopitem]
function ajaxSendShopIdRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/shop/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /shop/belt/:id ~ id: ItemID, [jsonData: JSON.shopitem]
function ajaxSendShopBeltIdRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/shop/belt/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Highscore ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /highscore/points
function ajaxSendHighscorePointsRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/highscore/points", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /highscore/time
function ajaxSendHighscoreTimeRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/highscore/time", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /highscore/runs
function ajaxSendHighscoreRunsRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/highscore/runs", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /highscore/sql
function ajaxSendHighscoreSQLRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/highscore/sql", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /highscore/rate
function ajaxSendHighscoreRateRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/highscore/rate", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /highscore/coins
function ajaxSendHighscoreCoinsRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/highscore/coins", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}<commit_msg>TaskSet<commit_after>/* Handles all the Ajax Requests */

/** Create the XMLHttpRequest object.
 *
 *  @param method: "POST"/"GET"/etc
 *  @param url: the URL to send the Request
 *  @param callback: the callback function to be called on ServerResponse.
 *                   We serve the xmlHttpRequest for that function.
 *  @return xmlHttpRequest ready to be send()
 */
function createRequest(method, url, callback) {

    var xhr = new XMLHttpRequest();

    if ("withCredentials" in xhr) {
        // XHR for Chrome/Firefox/Opera/Safari.
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
        // XDomainRequest for IE.
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        // CORS not supported.
        xhr = null;
    }

    xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
    xhr.withCredentials = true;
    xhr.onload = function () {
        if (xhr.status == 400 || xhr.status == 200 || xhr.status == 401) {
            console.log(xhr);
            callback(xhr);
        } else if (xhr.status == 404 || xhr.status == 408 || xhr.status == 444 ||
                   xhr.status == 503 || xhr.status == 504) {
            console.log(xhr);
            alert("Something went wrong, please check your internet connection!");
            return;
        } else {
            if (xhr.status == 403){
                if (me.state.isCurrent(STATE_LOGIN)) {
                    alert("wrong e-mail or password!");
                }
                return;
            }
            console.log(xhr);
            alert("Internal server error. Please try again, later!");
            return;
        }
    };

    return xhr;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~ Defining the Request-Send-Functions ~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Session ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ POST /login ~ jsonData: JSON.login
function ajaxSendLoginRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/login", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /logout
function ajaxSendLogoutRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/logout", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ User ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ POST /signup ~ jsonData: JSON.signup
function ajaxSendSignupRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/signup", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ POST /users ~ jsonData: JSON.user
function ajaxSendUsersRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/users", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ DELETE /users
function ajaxSendUsersDeleteRequest(onload) {
    var xmlHttpRequest = createRequest("DELETE", "/users", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /users/password
function ajaxSendUsersResetPasswordRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/users/password", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /users/student
function ajaxSendUserStudentRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/users/student", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Profile ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /profile/homework
function ajaxSendProfileHomeworkRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/homework", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /profile
function ajaxSendProfileRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/profile", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /profile/:id ~ id: the ProfileID
function ajaxSendProfileIdRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /profile/character
function ajaxSendProfileCharacterRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/character", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /profile/inventory
function ajaxSendProfileInventoryRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/character", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Item ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /profile/character
function ajaxSendProfileBeltRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/belt", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /profile/belt ~ jsonData: JSON.belt
function ajaxSendProfileBeltSetRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/profile/belt", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /profile/used/:potion,slot ~ potion: PotionID slot: SlotID ~ jsonData: JSON.potionused
function ajaxSendProfileUsedRequest( slot, onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/used/" + slot, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /profile/collected ~ jsonData: JSON.collected
function ajaxSendProfileCollectedRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/profile/collected", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Settings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /profile/settings
function ajaxSendProfileSettingsRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/settings", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /profile/settings ~ jsonData: JSON.settings
function ajaxSendProfileSettingsSetRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/profile/settings", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Challenge ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /challenge/reset
function ajaxSendChallengeResetRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge/reset", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /challenge
function ajaxSendChallengeRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /challenge/skip
function ajaxNextChallengeRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge/skip", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /challenge ~ id: ChallengeID
function ajaxSendChallengeIDRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /challenge ~ jsonData: JSON.challenge
function ajaxSendChallengeCreateRequest(jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/challenge", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /challenge/story
function ajaxSendChallengeStoryRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge/story", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET  /profile/avatar/:id
function ajaxSendProfileAvatarIdRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/profile/avatar/"+ id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /challenge/trivia
function ajaxSendChallengeTriviaRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge/trivia", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /challenge/homework
function ajaxSendChallengeHomeworkRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/challenge/homework", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SQLController ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /SQL/Story/:id ~ id: StoryTaskID
function ajaxSendTaskStoryIDRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/SQL/Story/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /SQL/Story/:id ~ id: StoryTaskID, jsonData: JSON.task.solve
function ajaxSendTaskStorySolveRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/SQL/Story/" + id, onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /SQL/Trivia/:id: StoryTaskID | difficulty: DifficultyLevel
function ajaxSendTaskTriviaRequest(difficulty, onload) {
    var xmlHttpRequest = createRequest("GET", "/SQL/Trivia/" + difficulty, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /SQL/Trivia/:id ~ id: TriviaTaskID, jsonData: JSON.task.solve
function ajaxSendTaskTriviaSolveRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/SQL/Trivia/" + id, onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ GET /SQL/Homework
function ajaxSendTaskHomeworkRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/SQL/Homework", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ POST /SQL/Homework/:id ~ id: HomeworkID, jsonData: JSON.task.solve
function ajaxSendTaskHomeworkSolveRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/SQL/Homework/" + id, onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TaskController ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ POST /TaskSet/:id/Task
function ajaxSendTaskOverTaskSetRequest(id, onload) {
    var xmlHttpRequest = createRequest("Post", "/TaskSet/" + id + "/Task", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /Task
function ajaxSendTaskRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/Task", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /Task/:id/ ~ id: TaskID
function ajaxSendTaskIdRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/Task/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ PATCH /Task/:id ~ id: TaskID, jsonData: JSON.task
function ajaxSendTaskIdEditRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("PATCH", "/Task/" + id, onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ DELETE /Task/:id ~ id: TaskID, jsonData: JSON.task
function ajaxSendTaskIdEditRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("DELETE", "/Task/" + id, onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ POST /Task/:id/rate ~ id: TaskID, jsonData: JSON.rating
function ajaxSendTaskIdRatingRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/Task/" + id + "/rate", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ POST /task/:id/comment ~ id: TaskID, jsonData: JSON.comment
function ajaxSendTaskIdCommentSetRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/task/" + id + "/comment", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TaskSetController ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ POST /TaskSet
function ajaxSendTaskSetRequest(id, onload) {
    var xmlHttpRequest = createRequest("Post", "/TaskSet", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /TaskSet
function ajaxSendTaskSetRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/TaskSet", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /TaskSet/:id ~ id: TaskSetID
function ajaxSendTaskSetIdRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/TaskSet/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ PATCH /TaskSet/:id ~ id: TaskSetID, jsonData: JSON.task
function ajaxSendTaskSetIdEditRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("PATCH", "/TaskSet/" + id, onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ DELETE /TaskSet/:id ~ id: TaskSetID, jsonData: JSON.task
function ajaxSendTaskSetIdEditRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("DELETE", "/TaskSet/" + id, onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ POST /TaskSet/:id/rate ~ id: TaskSetID, jsonData: JSON.rating
function ajaxSendTaskSetIdRatingRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/TaskSet/" + id + "/rate", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

// ~ POST /task/:id/comment ~ id: TaskSetID, jsonData: JSON.comment
function ajaxSendTaskSetIdCommentSetRequest(id, jsonData, onload) {
    var xmlHttpRequest = createRequest("POST", "/task/" + id + "/comment", onload);

    xmlHttpRequest.send(jsonData);

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Shop ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /shop
function ajaxSendShopRequest(onload) {
  var xmlHttpRequest = createRequest("GET", "/shop/avatar", onload);

  xmlHttpRequest.send();

  return xmlHttpRequest;
}

// ~ GET /shop/belt
function ajaxSendShopBeltRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/shop/belt", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /shop/:id ~ id: ItemID, [jsonData: JSON.shopitem]
function ajaxSendShopIdRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/shop/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /shop/belt/:id ~ id: ItemID, [jsonData: JSON.shopitem]
function ajaxSendShopBeltIdRequest(id, onload) {
    var xmlHttpRequest = createRequest("GET", "/shop/belt/" + id, onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Highscore ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

// ~ GET /highscore/points
function ajaxSendHighscorePointsRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/highscore/points", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /highscore/time
function ajaxSendHighscoreTimeRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/highscore/time", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /highscore/runs
function ajaxSendHighscoreRunsRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/highscore/runs", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /highscore/sql
function ajaxSendHighscoreSQLRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/highscore/sql", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /highscore/rate
function ajaxSendHighscoreRateRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/highscore/rate", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}

// ~ GET /highscore/coins
function ajaxSendHighscoreCoinsRequest(onload) {
    var xmlHttpRequest = createRequest("GET", "/highscore/coins", onload);

    xmlHttpRequest.send();

    return xmlHttpRequest;
}<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {

var oop = require("../lib/oop");
var dom = require("../lib/dom");
var lang = require("../lib/lang");
var useragent = require("../lib/useragent");
var EventEmitter = require("../lib/event_emitter").EventEmitter;

var CHAR_COUNT = 0;

var FontMetrics = exports.FontMetrics = function(parentEl, interval) {
    this.el = dom.createElement("div");
    this.$setMeasureNodeStyles(this.el.style, true);

    this.$main = dom.createElement("div");
    this.$setMeasureNodeStyles(this.$main.style);

    this.$measureNode = dom.createElement("div");
    this.$setMeasureNodeStyles(this.$measureNode.style);

    this.el.appendChild(this.$main);
    this.el.appendChild(this.$measureNode);
    parentEl.appendChild(this.el);

    if (!CHAR_COUNT)
        this.$testFractionalRect();
    this.$measureNode.innerHTML = lang.stringRepeat("X", CHAR_COUNT);

    this.$characterSize = {width: 0, height: 0};
    this.checkForSizeChanges();
};

(function() {

    oop.implement(this, EventEmitter);

    this.$characterSize = {width: 0, height: 0};

    this.$testFractionalRect = function() {
        var el = dom.createElement("div");
        this.$setMeasureNodeStyles(el.style);
        el.style.width = "0.2px";
        document.documentElement.appendChild(el);
        var w = el.getBoundingClientRect().width;
        if (w > 0 && w < 1)
            CHAR_COUNT = 1;
        else
            CHAR_COUNT = 100;
        el.parentNode.removeChild(el);
    };

    this.$setMeasureNodeStyles = function(style, isRoot) {
        style.width = style.height = "auto";
        style.left = style.top = "-100px";
        style.visibility = "hidden";
        style.position = "fixed";
        style.whiteSpace = "pre";

        if (useragent.isIE < 8) {
            style["font-family"] = "inherit";
        } else {
            style.font = "inherit";
        }
        style.overflow = isRoot ? "hidden" : "visible";
    };

    this.checkForSizeChanges = function() {
        var size = this.$measureSizes();
        if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) {
            this.$measureNode.style.fontWeight = "bold";
            var boldSize = this.$measureSizes();
            this.$measureNode.style.fontWeight = "";
            this.$characterSize = size;
            this.charSizes = Object.create(null);
            this.allowBoldFonts = boldSize && boldSize.width === size.width && boldSize.height === size.height;
            this._emit("changeCharacterSize", {data: size});
        }
    };

    this.$pollSizeChanges = function() {
        if (this.$pollSizeChangesTimer)
            return this.$pollSizeChangesTimer;
        var self = this;
        return this.$pollSizeChangesTimer = setInterval(function() {
            self.checkForSizeChanges();
        }, 500);
    };

    this.setPolling = function(val) {
        if (val) {
            this.$pollSizeChanges();
        } else {
            if (this.$pollSizeChangesTimer)
                this.$pollSizeChangesTimer;
        }
    };

    this.$measureSizes = function() {
        if (CHAR_COUNT === 1) {
            var rect = null;
            try {
               rect = this.$measureNode.getBoundingClientRect();
            } catch(e) {
               rect = { top : this.$measureNode.offsetTop, left : this.$measureNode.offsetLeft }
            };
            var size = {
                height: rect.height,
                width: rect.width
            };
        } else {
            var size = {
                height: this.$measureNode.clientHeight,
                width: this.$measureNode.clientWidth / CHAR_COUNT
            };
        }
        // Size and width can be null if the editor is not visible or
        // detached from the document
        if (size.width === 0 || size.height === 0)
            return null;
        return size;
    };

    this.$measureCharWidth = function(ch) {
        this.$main.innerHTML = lang.stringRepeat(ch, CHAR_COUNT);
        var rect = this.$main.getBoundingClientRect();
        return rect.width / CHAR_COUNT;
    };

    this.getCharacterWidth = function(ch) {
        var w = this.charSizes[ch];
        if (w === undefined) {
            this.charSizes[ch] = this.$measureCharWidth(ch) / this.$characterSize.width;
        }
        return w;
    };

    this.destroy = function() {
        clearInterval(this.$pollSizeChangesTimer);
        if (this.el && this.el.parentNode)
            this.el.parentNode.removeChild(this.el);
    };

}).call(FontMetrics.prototype);

});
<commit_msg>ie11 fix getBoundingClientRect() error<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {

var oop = require("../lib/oop");
var dom = require("../lib/dom");
var lang = require("../lib/lang");
var useragent = require("../lib/useragent");
var EventEmitter = require("../lib/event_emitter").EventEmitter;

var CHAR_COUNT = 0;

var FontMetrics = exports.FontMetrics = function(parentEl, interval) {
    this.el = dom.createElement("div");
    this.$setMeasureNodeStyles(this.el.style, true);

    this.$main = dom.createElement("div");
    this.$setMeasureNodeStyles(this.$main.style);

    this.$measureNode = dom.createElement("div");
    this.$setMeasureNodeStyles(this.$measureNode.style);

    this.el.appendChild(this.$main);
    this.el.appendChild(this.$measureNode);
    parentEl.appendChild(this.el);

    if (!CHAR_COUNT)
        this.$testFractionalRect();
    this.$measureNode.innerHTML = lang.stringRepeat("X", CHAR_COUNT);

    this.$characterSize = {width: 0, height: 0};
    this.checkForSizeChanges();
};

(function() {

    oop.implement(this, EventEmitter);

    this.$characterSize = {width: 0, height: 0};

    this.$testFractionalRect = function() {
        var el = dom.createElement("div");
        this.$setMeasureNodeStyles(el.style);
        el.style.width = "0.2px";
        document.documentElement.appendChild(el);
        var w = el.getBoundingClientRect().width;
        if (w > 0 && w < 1)
            CHAR_COUNT = 1;
        else
            CHAR_COUNT = 100;
        el.parentNode.removeChild(el);
    };

    this.$setMeasureNodeStyles = function(style, isRoot) {
        style.width = style.height = "auto";
        style.left = style.top = "-100px";
        style.visibility = "hidden";
        style.position = "fixed";
        style.whiteSpace = "pre";

        if (useragent.isIE < 8) {
            style["font-family"] = "inherit";
        } else {
            style.font = "inherit";
        }
        style.overflow = isRoot ? "hidden" : "visible";
    };

    this.checkForSizeChanges = function() {
        var size = this.$measureSizes();
        if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) {
            this.$measureNode.style.fontWeight = "bold";
            var boldSize = this.$measureSizes();
            this.$measureNode.style.fontWeight = "";
            this.$characterSize = size;
            this.charSizes = Object.create(null);
            this.allowBoldFonts = boldSize && boldSize.width === size.width && boldSize.height === size.height;
            this._emit("changeCharacterSize", {data: size});
        }
    };

    this.$pollSizeChanges = function() {
        if (this.$pollSizeChangesTimer)
            return this.$pollSizeChangesTimer;
        var self = this;
        return this.$pollSizeChangesTimer = setInterval(function() {
            self.checkForSizeChanges();
        }, 500);
    };

    this.setPolling = function(val) {
        if (val) {
            this.$pollSizeChanges();
        } else {
            if (this.$pollSizeChangesTimer)
                this.$pollSizeChangesTimer;
        }
    };

    this.$measureSizes = function() {
        if (CHAR_COUNT === 1) {
            var rect = null;
            try {
               rect = this.$measureNode.getBoundingClientRect();
            } catch(e) {
               rect = {width: 0, height:0 }
            };
            var size = {
                height: rect.height,
                width: rect.width
            };
        } else {
            var size = {
                height: this.$measureNode.clientHeight,
                width: this.$measureNode.clientWidth / CHAR_COUNT
            };
        }
        // Size and width can be null if the editor is not visible or
        // detached from the document
        if (size.width === 0 || size.height === 0)
            return null;
        return size;
    };

    this.$measureCharWidth = function(ch) {
        this.$main.innerHTML = lang.stringRepeat(ch, CHAR_COUNT);
        var rect = this.$main.getBoundingClientRect();
        return rect.width / CHAR_COUNT;
    };

    this.getCharacterWidth = function(ch) {
        var w = this.charSizes[ch];
        if (w === undefined) {
            this.charSizes[ch] = this.$measureCharWidth(ch) / this.$characterSize.width;
        }
        return w;
    };

    this.destroy = function() {
        clearInterval(this.$pollSizeChangesTimer);
        if (this.el && this.el.parentNode)
            this.el.parentNode.removeChild(this.el);
    };

}).call(FontMetrics.prototype);

});
<|endoftext|>


<commit_before>import Vue from 'vue'
import axios from 'axios'

var HTTP = axios.create({
  // Create axios instance
  baseURL: process.env.backendUrl
})

Vue.prototype.$http = HTTP

if (process.browser) {
  var BearerAuth = localStorage ? 'Bearer ' + localStorage.getItem('id_token') : 'Bearer ' + null
  Vue.prototype.$http.defaults.headers.common['Authorization'] = BearerAuth
}
<commit_msg>lock plugin to handle authorisation header setting<commit_after>import Vue from 'vue'
import axios from 'axios'

var HTTP = axios.create({
  // Create axios instance
  baseURL: process.env.backendUrl
})

Vue.prototype.$http = HTTP
<|endoftext|>


<commit_before>module.exports = function(app, connection) {
  'use strict';
  var memcached = require('./store')(connection);
  var RSVP = require('rsvp');
  var UserModel = require('../../models/user');
  var undefsafe = require('undefsafe');

  function setMetadata(obj, val) {
    console.log('setUserMetadata', val);
    obj.session.user = val;
    obj._userJSONCopy = JSON.stringify(val);
  }

  function populateMemcached(user) {
    console.log('populateMemcached', user);
    return memcached.set(user.name, user);
  }

  function getMetadata(username, req) {
    var setUserMetadata = setMetadata.bind(null, req);

    var promise = new RSVP.Promise(function(resolve, reject){
      // go to database get data about user etc...
      UserModel.load(username, function(err, user) {
        if (err) {
          reject(err);
        } else {
          resolve(user);
        }
      });

    })
    .then(populateMemcached)
    .then(setUserMetadata);

    return promise;
  }

  app.use(function(req, res, next) {
    // Removes user data from old cookies
    var username = undefsafe(req, 'session.user.name');
    console.log(username);
    console.log(req.session);

    var setUserMetadata = setMetadata.bind(null, req);
    var populateUserMetadata = getMetadata.bind(null, username, req);

    if (username) {
      memcached
        .get(username)
        .then(setUserMetadata)
        .catch(populateUserMetadata)
        .then(next);
    } else {
      next();
    }

    res.on('header', function () {
      if (req.session.user) {
        if (JSON.stringify(req.session.user) !== req._userJSONCopy) {
          memcached.set(req.session.user.name, req.session.user);
        }
      }
    });
  });

};
<commit_msg>Adding check for username<commit_after>module.exports = function(app, connection) {
  'use strict';
  var memcached = require('./store')(connection);
  var RSVP = require('rsvp');
  var UserModel = require('../../models/user');
  var undefsafe = require('undefsafe');

  function setMetadata(obj, val) {
    console.log('setUserMetadata', val);
    obj.session.user = val;
    obj._userJSONCopy = JSON.stringify(val);
  }

  function populateMemcached(user) {
    console.log('populateMemcached', user);
    return memcached.set(user.name, user);
  }

  function getMetadata(username, req) {
    var setUserMetadata = setMetadata.bind(null, req);

    var promise = new RSVP.Promise(function(resolve, reject){
      // go to database get data about user etc...
      UserModel.load(username, function(err, user) {
        if (err) {
          reject(err);
        } else {
          resolve(user);
        }
      });

    })
    .then(populateMemcached)
    .then(setUserMetadata);

    return promise;
  }

  app.use(function(req, res, next) {
    // Removes user data from old cookies
    var username = undefsafe(req, 'session.user.name');

    var setUserMetadata = setMetadata.bind(null, req);
    var populateUserMetadata = getMetadata.bind(null, username, req);

    if (username) {
      memcached
        .get(username)
        .then(setUserMetadata)
        .catch(populateUserMetadata)
        .then(next);
    } else {
      next();
    }

    res.on('header', function () {
      if (req.session.user) {
        if (JSON.stringify(req.session.user) !== req._userJSONCopy) {
          memcached.set(req.session.user.name, req.session.user);
        }
      }
    });
  });

};
<|endoftext|>


<commit_before>'use strict';

const jwt = require('jsonwebtoken');
const User = require('../model/user.js');
const universalify = require('universalify');

module.exports = (req, res, next) => {

  let {authorization} = req.headers;
  if(!authorization)
    return new Error('unauthorized, no authorization header');

  let token = authorization.split('Bearer ')[1];
  if(!token)
    return next(new Error('unauthorized to token found'));

  universalify.fromCallback(jwt.verify)(token, process.env.APP_SECRET)

    .then(decoded => User.findOne({tokenSeed:decoded.tokenSeed}))

    .then(user => {
      if(!user)
        throw new Error('unauthorized no user found');

      req.user = user;
      next();
    })
    .catch(next);
};
<commit_msg>fixed misspelled error<commit_after>'use strict';

const jwt = require('jsonwebtoken');
const User = require('../model/user.js');
const universalify = require('universalify');

module.exports = (req, res, next) => {

  let {authorization} = req.headers;
  if(!authorization)
    return new Error('unauthorized, no authorization header');

  let token = authorization.split('Bearer ')[1];
  if(!token)
    return next(new Error('unauthorized no token found'));

  universalify.fromCallback(jwt.verify)(token, process.env.APP_SECRET)

    .then(decoded => User.findOne({tokenSeed:decoded.tokenSeed}))

    .then(user => {
      if(!user)
        throw new Error('unauthorized no user found');

      req.user = user;
      next();
    })
    .catch(next);
};
<|endoftext|>


<commit_before>import { removeFromArray } from 'utils/array';
import { isFunction } from 'utils/is';

export default class TransitionManager {
  constructor(callback, parent) {
    this.callback = callback;
    this.parent = parent;

    this.intros = [];
    this.outros = [];

    this.children = [];
    this.totalChildren = this.outroChildren = 0;

    this.detachQueue = [];
    this.outrosComplete = false;

    if (parent) {
      parent.addChild(this);
    }
  }

  add(transition) {
    const list = transition.isIntro ? this.intros : this.outros;
    transition.starting = true;
    list.push(transition);
  }

  addChild(child) {
    this.children.push(child);

    this.totalChildren += 1;
    this.outroChildren += 1;
  }

  decrementOutros() {
    this.outroChildren -= 1;
    check(this);
  }

  decrementTotal() {
    this.totalChildren -= 1;
    check(this);
  }

  detachNodes() {
    this.detachQueue.forEach(detach);
    this.children.forEach(_detachNodes);
    this.detachQueue = [];
  }

  ready() {
    if (this.detachQueue.length) detachImmediate(this);
  }

  remove(transition) {
    const list = transition.isIntro ? this.intros : this.outros;
    removeFromArray(list, transition);
    check(this);
  }

  start() {
    this.children.forEach(c => c.start());
    this.intros.concat(this.outros).forEach(t => t.start());
    this.ready = true;
    check(this);
  }
}

function detach(element) {
  element.detach();
}

function _detachNodes(tm) {
  // _ to avoid transpiler quirk
  tm.detachNodes();
}

function check(tm) {
  if (!tm.ready || tm.outros.length || tm.outroChildren) return;

  // If all outros are complete, and we haven't already done this,
  // we notify the parent if there is one, otherwise
  // start detaching nodes
  if (!tm.outrosComplete) {
    tm.outrosComplete = true;

    if (tm.parent && !tm.parent.outrosComplete) {
      tm.parent.decrementOutros(tm);
    } else {
      tm.detachNodes();
    }
  }

  // Once everything is done, we can notify parent transition
  // manager and call the callback
  if (!tm.intros.length && !tm.totalChildren) {
    if (isFunction(tm.callback)) {
      tm.callback();
    }

    if (tm.parent && !tm.notifiedTotal) {
      tm.notifiedTotal = true;
      tm.parent.decrementTotal();
    }
  }
}

// check through the detach queue to see if a node is up or downstream from a
// transition and if not, go ahead and detach it
function detachImmediate(manager) {
  const queue = manager.detachQueue;
  const outros = collectAllOutros(manager);

  let i = queue.length;
  let j = 0;
  let node, trans;
  start: while (i--) {
    node = queue[i].node;
    j = outros.length;
    while (j--) {
      trans = outros[j].element.node;
      // check to see if the node is, contains, or is contained by the transitioning node
      if (trans === node || trans.contains(node) || node.contains(trans)) continue start;
    }

    // no match, we can drop it
    queue[i].detach();
    queue.splice(i, 1);
  }
}

function collectAllOutros(manager, _list) {
  let list = _list;

  // if there's no list, we're starting at the root to build one
  if (!list) {
    list = [];
    let parent = manager;
    while (parent.parent) parent = parent.parent;
    return collectAllOutros(parent, list);
  } else {
    // grab all outros from child managers
    let i = manager.children.length;
    while (i--) {
      list = collectAllOutros(manager.children[i], list);
    }

    // grab any from this manager if there are any
    if (manager.outros.length) list = list.concat(manager.outros);

    return list;
  }
}
<commit_msg>swap some foreach calls in the transition manager and avoid a bunch of array splices when detaching<commit_after>import { removeFromArray } from 'utils/array';
import { isFunction } from 'utils/is';

export default class TransitionManager {
  constructor(callback, parent) {
    this.callback = callback;
    this.parent = parent;

    this.intros = [];
    this.outros = [];

    this.children = [];
    this.totalChildren = this.outroChildren = 0;

    this.detachQueue = [];
    this.outrosComplete = false;

    if (parent) {
      parent.addChild(this);
    }
  }

  add(transition) {
    const list = transition.isIntro ? this.intros : this.outros;
    transition.starting = true;
    list.push(transition);
  }

  addChild(child) {
    this.children.push(child);

    this.totalChildren += 1;
    this.outroChildren += 1;
  }

  decrementOutros() {
    this.outroChildren -= 1;
    check(this);
  }

  decrementTotal() {
    this.totalChildren -= 1;
    check(this);
  }

  detachNodes() {
    let len = this.detachQueue.length;
    for (let i = 0; i < len; i++) this.detachQueue[i].detach();
    len = this.children.length;
    for (let i = 0; i < len; i++) this.children[i].detachNodes();
    this.detachQueue = [];
  }

  ready() {
    if (this.detachQueue.length) detachImmediate(this);
  }

  remove(transition) {
    const list = transition.isIntro ? this.intros : this.outros;
    removeFromArray(list, transition);
    check(this);
  }

  start() {
    this.children.forEach(c => c.start());
    this.intros.concat(this.outros).forEach(t => t.start());
    this.ready = true;
    check(this);
  }
}

function check(tm) {
  if (!tm.ready || tm.outros.length || tm.outroChildren) return;

  // If all outros are complete, and we haven't already done this,
  // we notify the parent if there is one, otherwise
  // start detaching nodes
  if (!tm.outrosComplete) {
    tm.outrosComplete = true;

    if (tm.parent && !tm.parent.outrosComplete) {
      tm.parent.decrementOutros(tm);
    } else {
      tm.detachNodes();
    }
  }

  // Once everything is done, we can notify parent transition
  // manager and call the callback
  if (!tm.intros.length && !tm.totalChildren) {
    if (isFunction(tm.callback)) {
      tm.callback();
    }

    if (tm.parent && !tm.notifiedTotal) {
      tm.notifiedTotal = true;
      tm.parent.decrementTotal();
    }
  }
}

// check through the detach queue to see if a node is up or downstream from a
// transition and if not, go ahead and detach it
function detachImmediate(manager) {
  const queue = manager.detachQueue;
  const outros = collectAllOutros(manager);

  if (!outros.length) {
    manager.detachNodes();
  } else {
    let i = queue.length;
    let j = 0;
    let node, trans;
    const nqueue = (manager.detachQueue = []);

    start: while (i--) {
      node = queue[i].node;
      j = outros.length;
      while (j--) {
        trans = outros[j].element.node;
        // check to see if the node is, contains, or is contained by the transitioning node
        if (trans === node || trans.contains(node) || node.contains(trans)) {
          nqueue.push(queue[i]);
          continue start;
        }
      }

      // no match, we can drop it
      queue[i].detach();
    }
  }
}

function collectAllOutros(manager, _list) {
  let list = _list;

  // if there's no list, we're starting at the root to build one
  if (!list) {
    list = [];
    let parent = manager;
    while (parent.parent) parent = parent.parent;
    return collectAllOutros(parent, list);
  } else {
    // grab all outros from child managers
    let i = manager.children.length;
    while (i--) {
      list = collectAllOutros(manager.children[i], list);
    }

    // grab any from this manager if there are any
    if (manager.outros.length) list = list.concat(manager.outros);

    return list;
  }
}
<|endoftext|>


<commit_before>export class UserController {
  constructor($firebaseArray, $firebaseAuth, $log) {
    'ngInject';
    var appURL = "https://vyapi.firebaseio.com/";
    var onlineUsersRef = new Firebase(appURL + "onlineUsers/");
    this.onlineUsers = {};
    var t = $firebaseArray(onlineUsersRef); //no idea what this line does, but removing this criples whole application
    this.goOnline = function() {

      var uid;
      this.fa = $firebaseAuth;
      this.clog = $log;
      this.ref = new Firebase(appURL);
      this.authObj = this.fa(this.ref);
      var authData = this.authObj.$getAuth();
      if (authData) {
        this.clog.log("Logged in as:", authData.uid);
        uid = authData.uid;
      } else {
        this.clog.log("Not Logged it. Please login");
        return;
      }

      //check self connection state
      var connectedRef = new Firebase(appURL + ".info/connected");
      connectedRef.on("value", (snap) => {
        if (snap.val() === true) {
          this.clog.log("connected");
          //register self as online
          (new Firebase(encodeURI(appURL + "users/" + uid + "/google/cachedUserProfile/given_name/"))).once("value", (value) => {
            var userName = value.val();
            (new Firebase(encodeURI(appURL + "users/" + uid + "/google/profileImageURL/"))).once("value", (value) => {
              var profileImageURL = value.val();
              onlineUsersRef.child(uid).set({name: userName, photo : profileImageURL});
            });
          });

          //setup offline mechanism when going offline
          onlineUsersRef.child(uid).onDisconnect().remove();
        } else {
          console.log("not connected");
        }
      });

      //user came online
      onlineUsersRef.on('child_added', (userId) => {
        console.log("User: " + userId.key() + " came online");
        this.onlineUsers[userId.key().replace(":", "")] = userId.val();
        //console.table(this.onlineUsers);
      });
      //user went offline
      onlineUsersRef.on('child_removed', (userId)=> {
        console.log("User: " + userId.key() + " went offline");
        delete this.onlineUsers[userId.key().replace(":", "")];
      });

    }

    this.goOnline();
  }
}
<commit_msg>use $log<commit_after>export class UserController {
  constructor($firebaseArray, $firebaseAuth, $log) {
    'ngInject';
    var appURL = "https://vyapi.firebaseio.com/";
    var onlineUsersRef = new Firebase(appURL + "onlineUsers/");
    this.onlineUsers = {};
    var t = $firebaseArray(onlineUsersRef); //no idea what this line does, but removing this criples whole application
    this.goOnline = function() {

      var uid;
      this.fa = $firebaseAuth;
      this.ref = new Firebase(appURL);
      this.authObj = this.fa(this.ref);
      var authData = this.authObj.$getAuth();
      if (authData) {
        $log.log("Logged in as:", authData.uid);
        uid = authData.uid;
      } else {
        $log.error("Not Logged it. Please login");
        return;
      }

      //check self connection state
      var connectedRef = new Firebase(appURL + ".info/connected");
      connectedRef.on("value", (snap) => {
        if (snap.val() === true) {
          $log.log("connected");
          //register self as online
          (new Firebase(encodeURI(appURL + "users/" + uid + "/google/cachedUserProfile/given_name/"))).once("value", (value) => {
            var userName = value.val();
            (new Firebase(encodeURI(appURL + "users/" + uid + "/google/profileImageURL/"))).once("value", (value) => {
              var profileImageURL = value.val();
              onlineUsersRef.child(uid).set({name: userName, photo : profileImageURL});
            });
          });

          //setup offline mechanism when going offline
          onlineUsersRef.child(uid).onDisconnect().remove();
        } else {
          $log.warn("not connected");
        }
      });

      //user came online
      onlineUsersRef.on('child_added', (userId) => {
        $log.log("User: " + userId.key() + " came online");
        this.onlineUsers[userId.key().replace(":", "")] = userId.val();
      });
      //user went offline
      onlineUsersRef.on('child_removed', (userId)=> {
        $log.log("User: " + userId.key() + " went offline");
        delete this.onlineUsers[userId.key().replace(":", "")];
      });

    }

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


<commit_before>
import Portal from 'react-portal'
import React from 'react'
import findDOMNode from '../utils/find-dom-node'

/**
 * Placeholder.
 */

class Placeholder extends React.Component {

  /**
   * Properties.
   */

  static propTypes = {
    children: React.PropTypes.any.isRequired,
    className: React.PropTypes.string,
    node: React.PropTypes.object.isRequired,
    parent: React.PropTypes.object.isRequired,
    state: React.PropTypes.object.isRequired,
    style: React.PropTypes.object
  };

  /**
   * Should the component update?
   *
   * @param {Object} props
   * @param {Object} state
   * @return {Boolean}
   */

  shouldComponentUpdate = (props, state) => {
    return (
      props.children != this.props.children ||
      props.className != this.props.className ||
      props.parent != this.props.parent ||
      props.node != this.props.node ||
      props.style != this.props.style
    )
  }

  /**
   * Is the placeholder visible?
   *
   * @return {Boolean}
   */

  isVisible = () => {
    const { onlyFirstChild, node, parent } = this.props
    if (node.text) return false
    if (parent.nodes.size > 1) return false

    const isFirst = parent.nodes.first() === node
    if (isFirst) return true

    return false
  }

  /**
   * On open, update the placeholder element's position.
   *
   * @param {Element} portal
   */

  onOpen = (portal) => {
    const { node } = this.props
    const el = portal.firstChild
    const nodeEl = findDOMNode(node)
    const rect = nodeEl.getBoundingClientRect()
    el.style.pointerEvents = 'none'
    el.style.position = 'absolute'
    el.style.top = `${rect.top}px`
    el.style.left = `${rect.left}px`
    el.style.width = `${rect.width}px`
    el.style.height = `${rect.height}px`
  }

  /**
   * Render.
   *
   * If the placeholder is a string, and no `className` or `style` has been
   * passed, give it a default style of lowered opacity.
   *
   * @return {Element} element
   */

  render = () => {
    const isOpen = this.isVisible()
    const { children, className } = this.props
    let { style } = this.props

    if (typeof children === 'string' && style == null && className == null) {
      style = { opacity: '0.333'}
    }

    return (
      <Portal isOpened={isOpen} onOpen={this.onOpen}>
        {children}
      </Portal>
    )
  }

}

/**
 * Export.
 */

export default Placeholder
<commit_msg>fix placeholder positioning<commit_after>
import Portal from 'react-portal'
import React from 'react'
import findDOMNode from '../utils/find-dom-node'

/**
 * Placeholder.
 */

class Placeholder extends React.Component {

  /**
   * Properties.
   */

  static propTypes = {
    children: React.PropTypes.any.isRequired,
    className: React.PropTypes.string,
    node: React.PropTypes.object.isRequired,
    parent: React.PropTypes.object.isRequired,
    state: React.PropTypes.object.isRequired,
    style: React.PropTypes.object
  };

  /**
   * Should the component update?
   *
   * @param {Object} props
   * @param {Object} state
   * @return {Boolean}
   */

  shouldComponentUpdate = (props, state) => {
    return (
      props.children != this.props.children ||
      props.className != this.props.className ||
      props.parent != this.props.parent ||
      props.node != this.props.node ||
      props.style != this.props.style
    )
  }

  /**
   * Is the placeholder visible?
   *
   * @return {Boolean}
   */

  isVisible = () => {
    const { onlyFirstChild, node, parent } = this.props
    if (node.text) return false
    if (parent.nodes.size > 1) return false

    const isFirst = parent.nodes.first() === node
    if (isFirst) return true

    return false
  }

  /**
   * On open, update the placeholder element's position.
   *
   * @param {Element} portal
   */

  onOpen = (portal) => {
    const { node } = this.props
    const el = portal.firstChild
    const nodeEl = findDOMNode(node)
    const rect = nodeEl.getBoundingClientRect()
    el.style.pointerEvents = 'none'
    el.style.position = 'absolute'
    el.style.top = `${window.scrollY + rect.top}px`
    el.style.left = `${window.scrollX + rect.left}px`
    el.style.width = `${rect.width}px`
    el.style.height = `${rect.height}px`
  }

  /**
   * Render.
   *
   * If the placeholder is a string, and no `className` or `style` has been
   * passed, give it a default style of lowered opacity.
   *
   * @return {Element} element
   */

  render = () => {
    const isOpen = this.isVisible()
    const { children, className } = this.props
    let { style } = this.props

    if (typeof children === 'string' && style == null && className == null) {
      style = { opacity: '0.333'}
    }

    return (
      <Portal isOpened={isOpen} onOpen={this.onOpen}>
        {children}
      </Portal>
    )
  }

}

/**
 * Export.
 */

export default Placeholder
<|endoftext|>