<commit_before>/****************************************************
*  UTF-8/UTF-16/UTF-32 and Base64 encoding utility  *
*  Copyright (c) 2015 Witold Sieraczyński           *
*  https://cerosrhino.github.io/js-enc-utils/       *
****************************************************/

(function() {
    'use strict';

    var EncUtils,
        utf16HRegex = /[\ud800-\udbff]([^\udc00-\udfff]|$)/,
        utf16LRegex = /(^|[^\ud800-\udbff])[\udc00-\udfff]/;

    function strToUTF16(str, littleEndian, array) {
        if (typeof str !== 'string') {
            throw new TypeError('Not a string');
        }

        if (utf16HRegex.test(str)) {
            utf16HRegex.lastIndex = 0;
            throw new Error('UTF-16 high surrogate not followed by low surrogate');
        } else if (utf16LRegex.test(str)) {
            utf16LRegex.lastIndex = 0;
            throw new Error('Unexpected UTF-16 low surrogate');
        }

        var bytes = [];

        for (var i = 0; i < str.length; i++) {
            var code = str.charCodeAt(i),
                high = code >> 8,
                low = code & 0xff;

            if (littleEndian === true) {
                bytes.push(low, high);
            } else {
                bytes.push(high, low);
            }
        }

        return (array === true) ? bytes : new Uint8Array(bytes);
    }

    function utf16ToStr(bytes, littleEndian) {
        bytes = new Uint8Array(bytes);

        if (bytes.length % 2 !== 0) {
            throw new Error('Incorrect number of bytes supplied');
        }

        var str = '';

        for (var i = 0; i < bytes.length; i += 2) {
            var code;
            if (littleEndian === true) {
                code = (bytes[i + 1] << 8) | bytes[i];
            } else {
                code = (bytes[i] << 8) | bytes[i + 1];
            }
            str += String.fromCharCode(code);
        }

        if (utf16HRegex.test(str)) {
            utf16HRegex.lastIndex = 0;
            throw new Error('UTF-16 high surrogate not followed by low surrogate');
        } else if (utf16LRegex.test(str)) {
            utf16LRegex.lastIndex = 0;
            throw new Error('Unexpected UTF-16 low surrogate');
        }

        return str;
    }

    function strToUTF32(str, littleEndian, array) {
        if (typeof str !== 'string') {
            throw new TypeError('Not a string');
        }

        var bytes = [];

        for (var i = 0; i < str.length; i++) {
            var code = str.charCodeAt(i);
            if (code >= 0xd800 && code <= 0xdbff) {
                if (i < str.length - 1) {
                    var nextCode = str.charCodeAt(i + 1);
                    if (nextCode >= 0xdc00 && nextCode <= 0xdfff) {
                        code = ((code - 0xd800) << 10) + nextCode - 0xdc00 + 0x10000;
                        i++;
                    } else {
                        throw new Error('UTF-16 high surrogate not followed by low surrogate');
                    }
                } else {
                    throw new Error('UTF-16 high surrogate not followed by low surrogate');
                }
            }
            if (littleEndian === true) {
                bytes.push(code & 0xff, (code >> 8) & 0xff, code >> 16, 0);
            } else {
                bytes.push(0, code >> 16, (code >> 8) & 0xff, code & 0xff);
            }
        }

        return (array === true) ? bytes : new Uint8Array(bytes);
    }

    function utf32ToStr(bytes, littleEndian) {
        bytes = new Uint8Array(bytes);

        if (bytes.length % 4 !== 0) {
            throw new Error('Incorrect number of bytes supplied');
        }

        var str = '';

        for (var i = 0; i < bytes.length; i += 4) {
            var code;
            if (littleEndian === true) {
                if (bytes[i + 3] !== 0) {
                    throw new Error('Invalid UTF-32 sequence');
                }
                code = (bytes[i + 2] << 16) | (bytes[i + 1] << 8) | bytes[i];
            } else {
                if (bytes[i] !== 0) {
                    throw new Error('Invalid UTF-32 sequence');
                }
                code = (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3];
            }
            if (code <= 0xffff) {
                if (code >= 0xd800 && code <= 0xdfff) {
                    throw new Error('Found code point reserved by UTF-16 for surrogate pairs');
                }
                str += String.fromCharCode(code);
            } else if (code > 0x10ffff) {
                throw new RangeError('Code point exceeds allowed limit (U+10FFFF)');
            } else {
                code -= 0x10000;
                str += String.fromCharCode(0xd800 + (code >> 10), 0xdc00 + (code & 0x03ff));
            }
        }

        return str;
    }

    EncUtils = {
        strToUTF8: function(str, array) {
            if (typeof str !== 'string') {
                throw new TypeError('Not a string');
            }

            var bytes = [];

            for (var i = 0; i < str.length; i++) {
                var code = str.charCodeAt(i);
                if (code <= 0x7f) {
                    bytes.push(code);
                } else {
                    if (code >= 0xd800 && code <= 0xdbff) {
                        if (i < str.length - 1) {
                            var nextCode = str.charCodeAt(i + 1);
                            if (nextCode >= 0xdc00 && nextCode <= 0xdfff) {
                                code = ((code - 0xd800) << 10) + nextCode - 0xdc00 + 0x10000;
                                i++;
                            } else {
                                throw new Error('UTF-16 high surrogate not followed by low surrogate');
                            }
                        } else {
                            throw new Error('UTF-16 high surrogate not followed by low surrogate');
                        }
                    } else if (code >= 0xdc00 && code <= 0xdfff) {
                        throw new Error('Unexpected UTF-16 low surrogate');
                    }

                    var length;
                    if (code <= 0x07ff) {
                        bytes.push(0xc0 | (code >> 6));
                        length = 2;
                    } else if (code <= 0xffff) {
                        bytes.push(0xe0 | (code >> 12));
                        length = 3;
                    } else if (code <= 0x10ffff) {
                        bytes.push(0xf0 | (code >> 18));
                        length = 4;
                    } else {
                        throw new RangeError('Code point exceeds allowed limit (U+10FFFF)');
                    }

                    for (var j = 0; j < length - 1; j++) {
                        bytes.push(0x80 | ((code >> ((length - 2 - j) * 6)) & 0x3f));
                    }
                }
            }

            return (array === true) ? bytes : new Uint8Array(bytes);
        },
        utf8ToStr: function(bytes) {
            bytes = new Uint8Array(bytes);

            var str = '',
                code,
                count = 0,
                overlongCheck;

            for (var i = 0; i < bytes.length; i++) {
                if (count === 0) {
                    if (bytes[i] <= 0x7f) {
                        code = bytes[i];
                        count = 0;
                        overlongCheck = 0;
                    } else if ((bytes[i] & 0xf8) === 0xf0 && i < bytes.length - 3) {
                        code = bytes[i] & 0x07;
                        count = 3;
                        if ((bytes[i] & 0x07) === 0)
                            overlongCheck = 0x30;
                    } else if ((bytes[i] & 0xf0) === 0xe0 && i < bytes.length - 2) {
                        code = bytes[i] & 0x0f;
                        count = 2;
                        if ((bytes[i] & 0x0f) === 0)
                            overlongCheck = 0x10;
                    } else if ((bytes[i] & 0xe0) === 0xc0 && (bytes[i] & 0x1e) !== 0 && i < bytes.length - 1) {
                        code = bytes[i] & 0x1f;
                        count = 1;
                        overlongCheck = 0;
                    } else {
                        throw new Error('Invalid UTF-8 sequence');
                    }
                } else if ((bytes[i] & 0xc0) === 0x80) {
                    if (overlongCheck && (bytes[i] & overlongCheck) === 0) {
                        throw new Error('Invalid UTF-8 sequence; possibly overlong encoding used');
                    }

                    code = (code << 6) | (bytes[i] & 0x3f);
                    count--;
                    overlongCheck = 0;
                } else {
                    throw new Error('Invalid UTF-8 sequence');
                }

                if (count === 0) {
                    if (code <= 0xffff) {
                        if (code >= 0xd800 && code <= 0xdfff) {
                            throw new Error('Found code point reserved by UTF-16 for surrogate pairs');
                        }
                        str += String.fromCharCode(code);
                    } else if (code > 0x10ffff) {
                        throw new RangeError('Code point exceeds allowed limit (U+10FFFF)');
                    } else {
                        code -= 0x10000;
                        str += String.fromCharCode(0xd800 + (code >> 10), 0xdc00 + (code & 0x03ff));
                    }
                }
            }

            return str;
        },
        strToUTF16BE: function(str, array) {
            return strToUTF16(str, false, array);
        },
        utf16BEToStr: function(bytes) {
            return utf16ToStr(bytes);
        },
        strToUTF16LE: function(str, array) {
            return strToUTF16(str, true, array);
        },
        utf16LEToStr: function(bytes) {
            return utf16ToStr(bytes, true);
        },
        strToUTF32BE: function(str, array) {
            return strToUTF32(str, false, array);
        },
        utf32BEToStr: function (bytes) {
            return utf32ToStr(bytes);
        },
        strToUTF32LE: function(str, array) {
            return strToUTF32(str, true, array);
        },
        utf32LEToStr: function(bytes) {
            return utf32ToStr(bytes, true);
        },
        bytesToBase64: function(bytes) {
            bytes = new Uint8Array(bytes);

            var str = '';

            for (var i = 0; i < bytes.length; i++) {
                str += String.fromCharCode(bytes[i]);
            }

            return btoa(str);
        },
        base64ToBytes: function(str, array) {
            if (typeof str !== 'string') {
                throw new TypeError('Not a string');
            }

            str = atob(str);

            var bytes = [];

            for (var i = 0; i < str.length; i++) {
                bytes.push(str.charCodeAt(i));
            }

            return (array === true) ? bytes : new Uint8Array(bytes);
        }
    };

    if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
        module.exports = EncUtils;
    } else {
        window.EncUtils = EncUtils;
    }
})();
<commit_msg>Slightly refactored the code<commit_after>/****************************************************
*  UTF-8/UTF-16/UTF-32 and Base64 encoding utility  *
*  Copyright (c) 2015 Witold Sieraczyński           *
*  https://cerosrhino.github.io/js-enc-utils/       *
****************************************************/

(function() {
    'use strict';

    var EncUtils,
        utf16HRegex = /[\ud800-\udbff]([^\udc00-\udfff]|$)/,
        utf16LRegex = /(^|[^\ud800-\udbff])[\udc00-\udfff]/;

    function strToUTF16(str, littleEndian, array) {
        if (typeof str !== 'string') {
            throw new TypeError('Not a string');
        }

        if (utf16HRegex.test(str)) {
            utf16HRegex.lastIndex = 0;
            throw new Error('UTF-16 high surrogate not followed by low surrogate');
        } else if (utf16LRegex.test(str)) {
            utf16LRegex.lastIndex = 0;
            throw new Error('Unexpected UTF-16 low surrogate');
        }

        var bytes = [];

        for (var i = 0; i < str.length; i++) {
            var code = str.charCodeAt(i),
                high = code >> 8,
                low = code & 0xff;

            if (littleEndian === true) {
                bytes.push(low, high);
            } else {
                bytes.push(high, low);
            }
        }

        return (array === true) ? bytes : new Uint8Array(bytes);
    }

    function utf16ToStr(bytes, littleEndian) {
        bytes = new Uint8Array(bytes);

        if (bytes.length % 2 !== 0) {
            throw new Error('Incorrect number of bytes supplied');
        }

        var str = '';

        for (var i = 0; i < bytes.length; i += 2) {
            var code;
            if (littleEndian === true) {
                code = (bytes[i + 1] << 8) | bytes[i];
            } else {
                code = (bytes[i] << 8) | bytes[i + 1];
            }
            str += String.fromCharCode(code);
        }

        if (utf16HRegex.test(str)) {
            utf16HRegex.lastIndex = 0;
            throw new Error('UTF-16 high surrogate not followed by low surrogate');
        } else if (utf16LRegex.test(str)) {
            utf16LRegex.lastIndex = 0;
            throw new Error('Unexpected UTF-16 low surrogate');
        }

        return str;
    }

    function strToUTF32(str, littleEndian, array) {
        if (typeof str !== 'string') {
            throw new TypeError('Not a string');
        }

        var bytes = [];

        for (var i = 0; i < str.length; i++) {
            var code = str.charCodeAt(i);
            if (code >= 0xd800 && code <= 0xdbff) {
                if (i < str.length - 1) {
                    var nextCode = str.charCodeAt(i + 1);
                    if (nextCode >= 0xdc00 && nextCode <= 0xdfff) {
                        code = ((code - 0xd800) << 10) + nextCode - 0xdc00 + 0x10000;
                        i++;
                    } else {
                        throw new Error('UTF-16 high surrogate not followed by low surrogate');
                    }
                } else {
                    throw new Error('UTF-16 high surrogate not followed by low surrogate');
                }
            }
            if (littleEndian === true) {
                bytes.push(code & 0xff, (code >> 8) & 0xff, code >> 16, 0);
            } else {
                bytes.push(0, code >> 16, (code >> 8) & 0xff, code & 0xff);
            }
        }

        return (array === true) ? bytes : new Uint8Array(bytes);
    }

    function utf32ToStr(bytes, littleEndian) {
        bytes = new Uint8Array(bytes);

        if (bytes.length % 4 !== 0) {
            throw new Error('Incorrect number of bytes supplied');
        }

        var str = '';

        for (var i = 0; i < bytes.length; i += 4) {
            var code;
            if (littleEndian === true) {
                if (bytes[i + 3] !== 0) {
                    throw new Error('Invalid UTF-32 sequence');
                }
                code = (bytes[i + 2] << 16) | (bytes[i + 1] << 8) | bytes[i];
            } else {
                if (bytes[i] !== 0) {
                    throw new Error('Invalid UTF-32 sequence');
                }
                code = (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3];
            }
            if (code <= 0xffff) {
                if (code >= 0xd800 && code <= 0xdfff) {
                    throw new Error('Found code point reserved by UTF-16 for surrogate pairs');
                }
                str += String.fromCharCode(code);
            } else if (code > 0x10ffff) {
                throw new RangeError('Code point exceeds allowed limit (U+10FFFF)');
            } else {
                code -= 0x10000;
                str += String.fromCharCode(0xd800 + (code >> 10), 0xdc00 + (code & 0x03ff));
            }
        }

        return str;
    }

    EncUtils = {
        strToUTF8: function(str, array) {
            if (typeof str !== 'string') {
                throw new TypeError('Not a string');
            }

            var bytes = [];

            for (var i = 0; i < str.length; i++) {
                var code = str.charCodeAt(i);
                if (code <= 0x7f) {
                    bytes.push(code);
                } else {
                    if (code >= 0xd800 && code <= 0xdbff) {
                        if (i < str.length - 1) {
                            var nextCode = str.charCodeAt(i + 1);
                            if (nextCode >= 0xdc00 && nextCode <= 0xdfff) {
                                code = ((code - 0xd800) << 10) + nextCode - 0xdc00 + 0x10000;
                                i++;
                            } else {
                                throw new Error('UTF-16 high surrogate not followed by low surrogate');
                            }
                        } else {
                            throw new Error('UTF-16 high surrogate not followed by low surrogate');
                        }
                    } else if (code >= 0xdc00 && code <= 0xdfff) {
                        throw new Error('Unexpected UTF-16 low surrogate');
                    }

                    var length;
                    if (code <= 0x07ff) {
                        bytes.push(0xc0 | (code >> 6));
                        length = 2;
                    } else if (code <= 0xffff) {
                        bytes.push(0xe0 | (code >> 12));
                        length = 3;
                    } else if (code <= 0x10ffff) {
                        bytes.push(0xf0 | (code >> 18));
                        length = 4;
                    } else {
                        throw new RangeError('Code point exceeds allowed limit (U+10FFFF)');
                    }

                    for (var j = 0; j < length - 1; j++) {
                        bytes.push(0x80 | ((code >> ((length - 2 - j) * 6)) & 0x3f));
                    }
                }
            }

            return (array === true) ? bytes : new Uint8Array(bytes);
        },
        utf8ToStr: function(bytes) {
            bytes = new Uint8Array(bytes);

            var str = '',
                code,
                count = 0,
                overlongCheck;

            for (var i = 0; i < bytes.length; i++) {
                if (count === 0) {
                    if (bytes[i] <= 0x7f) {
                        code = bytes[i];
                        count = 0;
                        overlongCheck = 0;
                    } else if ((bytes[i] & 0xf8) === 0xf0 && i < bytes.length - 3) {
                        code = bytes[i] & 0x07;
                        count = 3;
                        if ((bytes[i] & 0x07) === 0)
                            overlongCheck = 0x30;
                    } else if ((bytes[i] & 0xf0) === 0xe0 && i < bytes.length - 2) {
                        code = bytes[i] & 0x0f;
                        count = 2;
                        if ((bytes[i] & 0x0f) === 0)
                            overlongCheck = 0x10;
                    } else if ((bytes[i] & 0xe0) === 0xc0 && (bytes[i] & 0x1e) !== 0 && i < bytes.length - 1) {
                        code = bytes[i] & 0x1f;
                        count = 1;
                        overlongCheck = 0;
                    } else {
                        throw new Error('Invalid UTF-8 sequence');
                    }
                } else if ((bytes[i] & 0xc0) === 0x80) {
                    if (overlongCheck && (bytes[i] & overlongCheck) === 0) {
                        throw new Error('Invalid UTF-8 sequence; possibly overlong encoding used');
                    }

                    code = (code << 6) | (bytes[i] & 0x3f);
                    count--;
                    overlongCheck = 0;
                } else {
                    throw new Error('Invalid UTF-8 sequence');
                }

                if (count === 0) {
                    if (code <= 0xffff) {
                        if (code >= 0xd800 && code <= 0xdfff) {
                            throw new Error('Found code point reserved by UTF-16 for surrogate pairs');
                        }
                        str += String.fromCharCode(code);
                    } else if (code > 0x10ffff) {
                        throw new RangeError('Code point exceeds allowed limit (U+10FFFF)');
                    } else {
                        code -= 0x10000;
                        str += String.fromCharCode(0xd800 + (code >> 10), 0xdc00 + (code & 0x03ff));
                    }
                }
            }

            return str;
        },
        strToUTF16BE: function(str, array) {
            return strToUTF16(str, false, array);
        },
        utf16BEToStr: function(bytes) {
            return utf16ToStr(bytes);
        },
        strToUTF16LE: function(str, array) {
            return strToUTF16(str, true, array);
        },
        utf16LEToStr: function(bytes) {
            return utf16ToStr(bytes, true);
        },
        strToUTF32BE: function(str, array) {
            return strToUTF32(str, false, array);
        },
        utf32BEToStr: function (bytes) {
            return utf32ToStr(bytes);
        },
        strToUTF32LE: function(str, array) {
            return strToUTF32(str, true, array);
        },
        utf32LEToStr: function(bytes) {
            return utf32ToStr(bytes, true);
        },
        bytesToBase64: function(bytes) {
            return btoa([].reduce.call(new Uint8Array(bytes), function(prev, cur) {
                return prev + String.fromCharCode(cur);
            }, ''));
        },
        base64ToBytes: function(str, array) {
            if (typeof str !== 'string') {
                throw new TypeError('Not a string');
            }

            var bytes = [].map.call(atob(str), function(el) {
                return el.charCodeAt(0);
            });

            return (array === true) ? bytes : new Uint8Array(bytes);
        }
    };

    if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
        module.exports = EncUtils;
    } else {
        window.EncUtils = EncUtils;
    }
})();
<|endoftext|>


<commit_before>/**
 * Copyright JS Foundation and other contributors, http://js.foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
RED.sidebar = (function() {

    //$('#sidebar').tabs();
    var sidebar_tabs;
    var knownTabs = {};

    function addTab(title,content,closeable,visible) {
        var options;
        if (typeof title === "string") {
            // TODO: legacy support in case anyone uses this...
            options = {
                id: content.id,
                label: title,
                name: title,
                content: content,
                closeable: closeable,
                visible: visible
            }
        } else if (typeof title === "object") {
            options = title;
        }

        delete options.closeable;

        options.wrapper = $('
',{style:"height:100%"}).appendTo("#red-ui-sidebar-content")
        options.wrapper.append(options.content);
        options.wrapper.hide();

        if (!options.enableOnEdit) {
            options.shade = $('
',{class:"red-ui-sidebar-shade hide"}).appendTo(options.wrapper);
        }

        if (options.toolbar) {
            $("#red-ui-sidebar-footer").append(options.toolbar);
            $(options.toolbar).hide();
        }
        var id = options.id;

        RED.menu.addItem("menu-item-view-menu",{
            id:"menu-item-view-menu-"+options.id,
            label:options.name,
            onselect:function() {
                showSidebar(options.id);
            },
            group: "sidebar-tabs"
        });

        options.iconClass = options.iconClass || "fa fa-square-o"

        knownTabs[options.id] = options;

        if (options.visible !== false) {
            sidebar_tabs.addTab(knownTabs[options.id]);
        }
    }

    function removeTab(id) {
        sidebar_tabs.removeTab(id);
        $(knownTabs[id].wrapper).remove();
        if (knownTabs[id].footer) {
            knownTabs[id].footer.remove();
        }
        delete knownTabs[id];
        RED.menu.removeItem("menu-item-view-menu-"+id);
    }

    var sidebarSeparator =  {};
    sidebarSeparator.dragging = false;

    function setupSidebarSeparator() {
        $("#red-ui-sidebar-separator").draggable({
                axis: "x",
                start:function(event,ui) {
                    sidebarSeparator.closing = false;
                    sidebarSeparator.opening = false;
                    var winWidth = $("#red-ui-editor").width();
                    sidebarSeparator.start = ui.position.left;
                    sidebarSeparator.chartWidth = $("#red-ui-workspace").width();
                    sidebarSeparator.chartRight = winWidth-$("#red-ui-workspace").width()-$("#red-ui-workspace").offset().left-2;
                    sidebarSeparator.dragging = true;

                    if (!RED.menu.isSelected("menu-item-sidebar")) {
                        sidebarSeparator.opening = true;
                        var newChartRight = 7;
                        $("#red-ui-sidebar").addClass("closing");
                        $("#red-ui-workspace").css("right",newChartRight);
                        $("#red-ui-editor-stack").css("right",newChartRight+1);
                        $("#red-ui-sidebar").width(0);
                        RED.menu.setSelected("menu-item-sidebar",true);
                        RED.events.emit("sidebar:resize");
                    }
                    sidebarSeparator.width = $("#red-ui-sidebar").width();
                },
                drag: function(event,ui) {
                    var d = ui.position.left-sidebarSeparator.start;
                    var newSidebarWidth = sidebarSeparator.width-d;
                    if (sidebarSeparator.opening) {
                        newSidebarWidth -= 3;
                    }

                    if (newSidebarWidth > 150) {
                        if (sidebarSeparator.chartWidth+d < 200) {
                            ui.position.left = 200+sidebarSeparator.start-sidebarSeparator.chartWidth;
                            d = ui.position.left-sidebarSeparator.start;
                            newSidebarWidth = sidebarSeparator.width-d;
                        }
                    }

                    if (newSidebarWidth < 150) {
                        if (!sidebarSeparator.closing) {
                            $("#red-ui-sidebar").addClass("closing");
                            sidebarSeparator.closing = true;
                        }
                        if (!sidebarSeparator.opening) {
                            newSidebarWidth = 150;
                            ui.position.left = sidebarSeparator.width-(150 - sidebarSeparator.start);
                            d = ui.position.left-sidebarSeparator.start;
                        }
                    } else if (newSidebarWidth > 150 && (sidebarSeparator.closing || sidebarSeparator.opening)) {
                        sidebarSeparator.closing = false;
                        $("#red-ui-sidebar").removeClass("closing");
                    }

                    var newChartRight = sidebarSeparator.chartRight-d;
                    $("#red-ui-workspace").css("right",newChartRight);
                    $("#red-ui-editor-stack").css("right",newChartRight+1);
                    $("#red-ui-sidebar").width(newSidebarWidth);

                    sidebar_tabs.resize();
                    RED.events.emit("sidebar:resize");
                },
                stop:function(event,ui) {
                    sidebarSeparator.dragging = false;
                    if (sidebarSeparator.closing) {
                        $("#red-ui-sidebar").removeClass("closing");
                        RED.menu.setSelected("menu-item-sidebar",false);
                        if ($("#red-ui-sidebar").width() < 180) {
                            $("#red-ui-sidebar").width(180);
                            $("#red-ui-workspace").css("right",187);
                            $("#red-ui-editor-stack").css("right",188);
                        }
                    }
                    $("#red-ui-sidebar-separator").css("left","auto");
                    $("#red-ui-sidebar-separator").css("right",($("#red-ui-sidebar").width()+2)+"px");
                    RED.events.emit("sidebar:resize");
                }
        });

        var sidebarControls = $('
<i class="fa fa-chevron-right"
').appendTo($("#red-ui-sidebar-separator"));
        sidebarControls.on("click", function() {
            sidebarControls.hide();
            RED.menu.toggleSelected("menu-item-sidebar");
        })
        $("#red-ui-sidebar-separator").on("mouseenter", function() {
            if (!sidebarSeparator.dragging) {
                if (RED.menu.isSelected("menu-item-sidebar")) {
                    sidebarControls.find("i").addClass("fa-chevron-right").removeClass("fa-chevron-left");
                } else {
                    sidebarControls.find("i").removeClass("fa-chevron-right").addClass("fa-chevron-left");
                }
                sidebarControls.toggle("slide", { direction: "right" }, 200);
            }
        })
        $("#red-ui-sidebar-separator").on("mouseleave", function() {
            if (!sidebarSeparator.dragging) {
                sidebarControls.stop(false,true);
                sidebarControls.hide();
            }
        });
    }

    function toggleSidebar(state) {
        if (!state) {
            $("#red-ui-main-container").addClass("red-ui-sidebar-closed");
        } else {
            $("#red-ui-main-container").removeClass("red-ui-sidebar-closed");
            sidebar_tabs.resize();
        }
        RED.events.emit("sidebar:resize");
    }

    function showSidebar(id) {
        if (id === ":first") {
            id = RED.settings.get("editor.sidebar.order",["info", "help", "version-control", "debug"])[0]
        }
        if (id) {
            if (!containsTab(id)) {
                sidebar_tabs.addTab(knownTabs[id]);
            }
            sidebar_tabs.activateTab(id);
            if (!RED.menu.isSelected("menu-item-sidebar")) {
                RED.menu.setSelected("menu-item-sidebar",true);
            }
        }
    }

    function containsTab(id) {
        return sidebar_tabs.contains(id);
    }

    function init () {
        setupSidebarSeparator();
        sidebar_tabs = RED.tabs.create({
            element: $('

').appendTo("#red-ui-sidebar"),
            onchange:function(tab) {
                $("#red-ui-sidebar-content").children().hide();
                $("#red-ui-sidebar-footer").children().hide();
                if (tab.onchange) {
                    tab.onchange.call(tab);
                }
                $(tab.wrapper).show();
                if (tab.toolbar) {
                    $(tab.toolbar).show();
                }
            },
            onremove: function(tab) {
                $(tab.wrapper).hide();
                if (tab.onremove) {
                    tab.onremove.call(tab);
                }
            },
            // minimumActiveTabWidth: 70,
            collapsible: true,
            onreorder: function(order) {
                RED.settings.set("editor.sidebar.order",order);
            },
            order: RED.settings.get("editor.sidebar.order",["info", "help", "version-control", "debug"])
            // scrollable: true
        });

        $('

').appendTo("#red-ui-sidebar");
        $('

').appendTo("#red-ui-sidebar");
        $('

').appendTo("#red-ui-sidebar");

        RED.actions.add("core:toggle-sidebar",function(state){
            if (state === undefined) {
                RED.menu.toggleSelected("menu-item-sidebar");
            } else {
                toggleSidebar(state);
            }
        });
        RED.popover.tooltip($("#red-ui-sidebar-separator").find(".red-ui-sidebar-control-right"),RED._("keyboard.toggleSidebar"),"core:toggle-sidebar");
        showSidebar();
        RED.sidebar.info.init();
        RED.sidebar.help.init();
        RED.sidebar.config.init();
        RED.sidebar.context.init();
        // hide info bar at start if screen rather narrow...
        if ($("#red-ui-editor").width() < 600) { RED.menu.setSelected("menu-item-sidebar",false); }
    }

    return {
        init: init,
        addTab: addTab,
        removeTab: removeTab,
        show: showSidebar,
        containsTab: containsTab,
        toggleSidebar: toggleSidebar,
    }

})();
<commit_msg>Handle sidebar tab that no longer exists when setting first active<commit_after>/**
 * Copyright JS Foundation and other contributors, http://js.foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
RED.sidebar = (function() {

    //$('#sidebar').tabs();
    var sidebar_tabs;
    var knownTabs = {};

    function addTab(title,content,closeable,visible) {
        var options;
        if (typeof title === "string") {
            // TODO: legacy support in case anyone uses this...
            options = {
                id: content.id,
                label: title,
                name: title,
                content: content,
                closeable: closeable,
                visible: visible
            }
        } else if (typeof title === "object") {
            options = title;
        }

        delete options.closeable;

        options.wrapper = $('
',{style:"height:100%"}).appendTo("#red-ui-sidebar-content")
        options.wrapper.append(options.content);
        options.wrapper.hide();

        if (!options.enableOnEdit) {
            options.shade = $('
',{class:"red-ui-sidebar-shade hide"}).appendTo(options.wrapper);
        }

        if (options.toolbar) {
            $("#red-ui-sidebar-footer").append(options.toolbar);
            $(options.toolbar).hide();
        }
        var id = options.id;

        RED.menu.addItem("menu-item-view-menu",{
            id:"menu-item-view-menu-"+options.id,
            label:options.name,
            onselect:function() {
                showSidebar(options.id);
            },
            group: "sidebar-tabs"
        });

        options.iconClass = options.iconClass || "fa fa-square-o"

        knownTabs[options.id] = options;

        if (options.visible !== false) {
            sidebar_tabs.addTab(knownTabs[options.id]);
        }
    }

    function removeTab(id) {
        sidebar_tabs.removeTab(id);
        $(knownTabs[id].wrapper).remove();
        if (knownTabs[id].footer) {
            knownTabs[id].footer.remove();
        }
        delete knownTabs[id];
        RED.menu.removeItem("menu-item-view-menu-"+id);
    }

    var sidebarSeparator =  {};
    sidebarSeparator.dragging = false;

    function setupSidebarSeparator() {
        $("#red-ui-sidebar-separator").draggable({
                axis: "x",
                start:function(event,ui) {
                    sidebarSeparator.closing = false;
                    sidebarSeparator.opening = false;
                    var winWidth = $("#red-ui-editor").width();
                    sidebarSeparator.start = ui.position.left;
                    sidebarSeparator.chartWidth = $("#red-ui-workspace").width();
                    sidebarSeparator.chartRight = winWidth-$("#red-ui-workspace").width()-$("#red-ui-workspace").offset().left-2;
                    sidebarSeparator.dragging = true;

                    if (!RED.menu.isSelected("menu-item-sidebar")) {
                        sidebarSeparator.opening = true;
                        var newChartRight = 7;
                        $("#red-ui-sidebar").addClass("closing");
                        $("#red-ui-workspace").css("right",newChartRight);
                        $("#red-ui-editor-stack").css("right",newChartRight+1);
                        $("#red-ui-sidebar").width(0);
                        RED.menu.setSelected("menu-item-sidebar",true);
                        RED.events.emit("sidebar:resize");
                    }
                    sidebarSeparator.width = $("#red-ui-sidebar").width();
                },
                drag: function(event,ui) {
                    var d = ui.position.left-sidebarSeparator.start;
                    var newSidebarWidth = sidebarSeparator.width-d;
                    if (sidebarSeparator.opening) {
                        newSidebarWidth -= 3;
                    }

                    if (newSidebarWidth > 150) {
                        if (sidebarSeparator.chartWidth+d < 200) {
                            ui.position.left = 200+sidebarSeparator.start-sidebarSeparator.chartWidth;
                            d = ui.position.left-sidebarSeparator.start;
                            newSidebarWidth = sidebarSeparator.width-d;
                        }
                    }

                    if (newSidebarWidth < 150) {
                        if (!sidebarSeparator.closing) {
                            $("#red-ui-sidebar").addClass("closing");
                            sidebarSeparator.closing = true;
                        }
                        if (!sidebarSeparator.opening) {
                            newSidebarWidth = 150;
                            ui.position.left = sidebarSeparator.width-(150 - sidebarSeparator.start);
                            d = ui.position.left-sidebarSeparator.start;
                        }
                    } else if (newSidebarWidth > 150 && (sidebarSeparator.closing || sidebarSeparator.opening)) {
                        sidebarSeparator.closing = false;
                        $("#red-ui-sidebar").removeClass("closing");
                    }

                    var newChartRight = sidebarSeparator.chartRight-d;
                    $("#red-ui-workspace").css("right",newChartRight);
                    $("#red-ui-editor-stack").css("right",newChartRight+1);
                    $("#red-ui-sidebar").width(newSidebarWidth);

                    sidebar_tabs.resize();
                    RED.events.emit("sidebar:resize");
                },
                stop:function(event,ui) {
                    sidebarSeparator.dragging = false;
                    if (sidebarSeparator.closing) {
                        $("#red-ui-sidebar").removeClass("closing");
                        RED.menu.setSelected("menu-item-sidebar",false);
                        if ($("#red-ui-sidebar").width() < 180) {
                            $("#red-ui-sidebar").width(180);
                            $("#red-ui-workspace").css("right",187);
                            $("#red-ui-editor-stack").css("right",188);
                        }
                    }
                    $("#red-ui-sidebar-separator").css("left","auto");
                    $("#red-ui-sidebar-separator").css("right",($("#red-ui-sidebar").width()+2)+"px");
                    RED.events.emit("sidebar:resize");
                }
        });

        var sidebarControls = $('
<i class="fa fa-chevron-right"
').appendTo($("#red-ui-sidebar-separator"));
        sidebarControls.on("click", function() {
            sidebarControls.hide();
            RED.menu.toggleSelected("menu-item-sidebar");
        })
        $("#red-ui-sidebar-separator").on("mouseenter", function() {
            if (!sidebarSeparator.dragging) {
                if (RED.menu.isSelected("menu-item-sidebar")) {
                    sidebarControls.find("i").addClass("fa-chevron-right").removeClass("fa-chevron-left");
                } else {
                    sidebarControls.find("i").removeClass("fa-chevron-right").addClass("fa-chevron-left");
                }
                sidebarControls.toggle("slide", { direction: "right" }, 200);
            }
        })
        $("#red-ui-sidebar-separator").on("mouseleave", function() {
            if (!sidebarSeparator.dragging) {
                sidebarControls.stop(false,true);
                sidebarControls.hide();
            }
        });
    }

    function toggleSidebar(state) {
        if (!state) {
            $("#red-ui-main-container").addClass("red-ui-sidebar-closed");
        } else {
            $("#red-ui-main-container").removeClass("red-ui-sidebar-closed");
            sidebar_tabs.resize();
        }
        RED.events.emit("sidebar:resize");
    }

    function showSidebar(id) {
        if (id === ":first") {
            id = RED.settings.get("editor.sidebar.order",["info", "help", "version-control", "debug"])[0]
        }
        if (id) {
            if (!containsTab(id) && knownTabs[id]) {
                sidebar_tabs.addTab(knownTabs[id]);
            }
            sidebar_tabs.activateTab(id);
            if (!RED.menu.isSelected("menu-item-sidebar")) {
                RED.menu.setSelected("menu-item-sidebar",true);
            }
        }
    }

    function containsTab(id) {
        return sidebar_tabs.contains(id);
    }

    function init () {
        setupSidebarSeparator();
        sidebar_tabs = RED.tabs.create({
            element: $('

').appendTo("#red-ui-sidebar"),
            onchange:function(tab) {
                $("#red-ui-sidebar-content").children().hide();
                $("#red-ui-sidebar-footer").children().hide();
                if (tab.onchange) {
                    tab.onchange.call(tab);
                }
                $(tab.wrapper).show();
                if (tab.toolbar) {
                    $(tab.toolbar).show();
                }
            },
            onremove: function(tab) {
                $(tab.wrapper).hide();
                if (tab.onremove) {
                    tab.onremove.call(tab);
                }
            },
            // minimumActiveTabWidth: 70,
            collapsible: true,
            onreorder: function(order) {
                RED.settings.set("editor.sidebar.order",order);
            },
            order: RED.settings.get("editor.sidebar.order",["info", "help", "version-control", "debug"])
            // scrollable: true
        });

        $('

').appendTo("#red-ui-sidebar");
        $('

').appendTo("#red-ui-sidebar");
        $('

').appendTo("#red-ui-sidebar");

        RED.actions.add("core:toggle-sidebar",function(state){
            if (state === undefined) {
                RED.menu.toggleSelected("menu-item-sidebar");
            } else {
                toggleSidebar(state);
            }
        });
        RED.popover.tooltip($("#red-ui-sidebar-separator").find(".red-ui-sidebar-control-right"),RED._("keyboard.toggleSidebar"),"core:toggle-sidebar");
        showSidebar();
        RED.sidebar.info.init();
        RED.sidebar.help.init();
        RED.sidebar.config.init();
        RED.sidebar.context.init();
        // hide info bar at start if screen rather narrow...
        if ($("#red-ui-editor").width() < 600) { RED.menu.setSelected("menu-item-sidebar",false); }
    }

    return {
        init: init,
        addTab: addTab,
        removeTab: removeTab,
        show: showSidebar,
        containsTab: containsTab,
        toggleSidebar: toggleSidebar,
    }

})();
<|endoftext|>


<commit_before>/**
  @module ember-data
*/

import Evented from '@ember/object/evented';

import ArrayProxy from '@ember/array/proxy';
import { set, get, computed } from '@ember/object';
import { Promise } from 'rsvp';
import { PromiseArray } from '../promise-proxies';
import SnapshotRecordArray from '../snapshot-record-array';

/**
  A record array is an array that contains records of a certain modelName. The record
  array materializes records as needed when they are retrieved for the first
  time. You should not create record arrays yourself. Instead, an instance of
  `DS.RecordArray` or its subclasses will be returned by your application's store
  in response to queries.

  @class RecordArray
  @namespace DS
  @extends Ember.ArrayProxy
  @uses Ember.Evented
*/

export default ArrayProxy.extend(Evented, {
  init() {
    this._super(...arguments);

    /**
      The array of client ids backing the record array. When a
      record is requested from the record array, the record
      for the client id at the same index is materialized, if
      necessary, by the store.

      @property content
      @private
      @type Ember.Array
      */
    this.set('content', this.content || null);

    /**
    The flag to signal a `RecordArray` is finished loading data.

    Example

    ```javascript
    var people = store.peekAll('person');
    people.get('isLoaded'); // true
    ```

    @property isLoaded
    @type Boolean
    */
    this.isLoaded = this.isLoaded || false;
    /**
    The flag to signal a `RecordArray` is currently loading data.

    Example

    ```javascript
    var people = store.peekAll('person');
    people.get('isUpdating'); // false
    people.update();
    people.get('isUpdating'); // true
    ```

    @property isUpdating
    @type Boolean
    */
    this.isUpdating = false;

    /**
    The store that created this record array.

    @property store
    @private
    @type DS.Store
    */
    this.store = this.store || null;
    this._updatingPromise = null;
  },

  replace() {
    throw new Error(
      `The result of a server query (for all ${
        this.modelName
      } types) is immutable. To modify contents, use toArray()`
    );
  },

  /**
   The modelClass represented by this record array.

   @property type
   @type DS.Model
   */
  type: computed('modelName', function() {
    if (!this.modelName) {
      return null;
    }
    return this.store.modelFor(this.modelName);
  }).readOnly(),

  /**
    Retrieves an object from the content by index.

    @method objectAtContent
    @private
    @param {Number} index
    @return {DS.Model} record
  */
  objectAtContent(index) {
    let internalModel = get(this, 'content').objectAt(index);
    return internalModel && internalModel.getRecord();
  },

  /**
    Used to get the latest version of all of the records in this array
    from the adapter.

    Example

    ```javascript
    var people = store.peekAll('person');
    people.get('isUpdating'); // false

    people.update().then(function() {
      people.get('isUpdating'); // false
    });

    people.get('isUpdating'); // true
    ```

    @method update
  */
  update() {
    if (get(this, 'isUpdating')) {
      return this._updatingPromise;
    }

    this.set('isUpdating', true);

    let updatingPromise = this._update().finally(() => {
      this._updatingPromise = null;
      if (this.get('isDestroying') || this.get('isDestroyed')) {
        return;
      }
      this.set('isUpdating', false);
    });

    this._updatingPromise = updatingPromise;

    return updatingPromise;
  },

  /*
    Update this RecordArray and return a promise which resolves once the update
    is finished.
   */
  _update() {
    return this.store.findAll(this.modelName, { reload: true });
  },

  /**
    Adds an internal model to the `RecordArray` without duplicates

    @method _pushInternalModels
    @private
    @param {InternalModel} internalModel
  */
  _pushInternalModels(internalModels) {
    // pushObjects because the internalModels._recordArrays set was already
    // consulted for inclusion, so addObject and its on .contains call is not
    // required.
    get(this, 'content').pushObjects(internalModels);
  },

  /**
    Removes an internalModel to the `RecordArray`.

    @method removeInternalModel
    @private
    @param {InternalModel} internalModel
  */
  _removeInternalModels(internalModels) {
    get(this, 'content').removeObjects(internalModels);
  },

  /**
    Saves all of the records in the `RecordArray`.

    Example

    ```javascript
    var messages = store.peekAll('message');
    messages.forEach(function(message) {
      message.set('hasBeenSeen', true);
    });
    messages.save();
    ```

    @method save
    @return {DS.PromiseArray} promise
  */
  save() {
    let promiseLabel = `DS: RecordArray#save ${this.modelName}`;
    let promise = Promise.all(this.invoke('save'), promiseLabel).then(
      () => this,
      null,
      'DS: RecordArray#save return RecordArray'
    );

    return PromiseArray.create({ promise });
  },

  _dissociateFromOwnRecords() {
    this.get('content').forEach(internalModel => {
      let recordArrays = internalModel.__recordArrays;

      if (recordArrays) {
        recordArrays.delete(this);
      }
    });
  },

  /**
    @method _unregisterFromManager
    @private
  */
  _unregisterFromManager() {
    this.manager.unregisterRecordArray(this);
  },

  willDestroy() {
    this._unregisterFromManager();
    this._dissociateFromOwnRecords();
    // TODO: we should not do work during destroy:
    //   * when objects are destroyed, they should simply be left to do
    //   * if logic errors do to this, that logic needs to be more careful during
    //    teardown (ember provides isDestroying/isDestroyed) for this reason
    //   * the exception being: if an dominator has a reference to this object,
    //     and must be informed to release e.g. e.g. removing itself from th
    //     recordArrayMananger
    set(this, 'content', null);
    set(this, 'length', 0);
    this._super(...arguments);
  },

  /*
    @method _createSnapshot
    @private
  */
  _createSnapshot(options) {
    // this is private for users, but public for ember-data internals
    return new SnapshotRecordArray(this, this.get('meta'), options);
  },

  /*
    @method _takeSnapshot
    @private
  */
  _takeSnapshot() {
    return get(this, 'content').map(internalModel => internalModel.createSnapshot());
  },
});
<commit_msg>[BUGFIX docs] Fix broken ArrayProxy link on api docs (#6057)<commit_after>/**
  @module ember-data
*/

import Evented from '@ember/object/evented';

import ArrayProxy from '@ember/array/proxy';
import { set, get, computed } from '@ember/object';
import { Promise } from 'rsvp';
import { PromiseArray } from '../promise-proxies';
import SnapshotRecordArray from '../snapshot-record-array';

/**
  A record array is an array that contains records of a certain modelName. The record
  array materializes records as needed when they are retrieved for the first
  time. You should not create record arrays yourself. Instead, an instance of
  `DS.RecordArray` or its subclasses will be returned by your application's store
  in response to queries.

  @class RecordArray
  @namespace DS
  @extends ArrayProxy
  @uses Ember.Evented
*/

export default ArrayProxy.extend(Evented, {
  init() {
    this._super(...arguments);

    /**
      The array of client ids backing the record array. When a
      record is requested from the record array, the record
      for the client id at the same index is materialized, if
      necessary, by the store.

      @property content
      @private
      @type Ember.Array
      */
    this.set('content', this.content || null);

    /**
    The flag to signal a `RecordArray` is finished loading data.

    Example

    ```javascript
    var people = store.peekAll('person');
    people.get('isLoaded'); // true
    ```

    @property isLoaded
    @type Boolean
    */
    this.isLoaded = this.isLoaded || false;
    /**
    The flag to signal a `RecordArray` is currently loading data.

    Example

    ```javascript
    var people = store.peekAll('person');
    people.get('isUpdating'); // false
    people.update();
    people.get('isUpdating'); // true
    ```

    @property isUpdating
    @type Boolean
    */
    this.isUpdating = false;

    /**
    The store that created this record array.

    @property store
    @private
    @type DS.Store
    */
    this.store = this.store || null;
    this._updatingPromise = null;
  },

  replace() {
    throw new Error(
      `The result of a server query (for all ${
        this.modelName
      } types) is immutable. To modify contents, use toArray()`
    );
  },

  /**
   The modelClass represented by this record array.

   @property type
   @type DS.Model
   */
  type: computed('modelName', function() {
    if (!this.modelName) {
      return null;
    }
    return this.store.modelFor(this.modelName);
  }).readOnly(),

  /**
    Retrieves an object from the content by index.

    @method objectAtContent
    @private
    @param {Number} index
    @return {DS.Model} record
  */
  objectAtContent(index) {
    let internalModel = get(this, 'content').objectAt(index);
    return internalModel && internalModel.getRecord();
  },

  /**
    Used to get the latest version of all of the records in this array
    from the adapter.

    Example

    ```javascript
    var people = store.peekAll('person');
    people.get('isUpdating'); // false

    people.update().then(function() {
      people.get('isUpdating'); // false
    });

    people.get('isUpdating'); // true
    ```

    @method update
  */
  update() {
    if (get(this, 'isUpdating')) {
      return this._updatingPromise;
    }

    this.set('isUpdating', true);

    let updatingPromise = this._update().finally(() => {
      this._updatingPromise = null;
      if (this.get('isDestroying') || this.get('isDestroyed')) {
        return;
      }
      this.set('isUpdating', false);
    });

    this._updatingPromise = updatingPromise;

    return updatingPromise;
  },

  /*
    Update this RecordArray and return a promise which resolves once the update
    is finished.
   */
  _update() {
    return this.store.findAll(this.modelName, { reload: true });
  },

  /**
    Adds an internal model to the `RecordArray` without duplicates

    @method _pushInternalModels
    @private
    @param {InternalModel} internalModel
  */
  _pushInternalModels(internalModels) {
    // pushObjects because the internalModels._recordArrays set was already
    // consulted for inclusion, so addObject and its on .contains call is not
    // required.
    get(this, 'content').pushObjects(internalModels);
  },

  /**
    Removes an internalModel to the `RecordArray`.

    @method removeInternalModel
    @private
    @param {InternalModel} internalModel
  */
  _removeInternalModels(internalModels) {
    get(this, 'content').removeObjects(internalModels);
  },

  /**
    Saves all of the records in the `RecordArray`.

    Example

    ```javascript
    var messages = store.peekAll('message');
    messages.forEach(function(message) {
      message.set('hasBeenSeen', true);
    });
    messages.save();
    ```

    @method save
    @return {DS.PromiseArray} promise
  */
  save() {
    let promiseLabel = `DS: RecordArray#save ${this.modelName}`;
    let promise = Promise.all(this.invoke('save'), promiseLabel).then(
      () => this,
      null,
      'DS: RecordArray#save return RecordArray'
    );

    return PromiseArray.create({ promise });
  },

  _dissociateFromOwnRecords() {
    this.get('content').forEach(internalModel => {
      let recordArrays = internalModel.__recordArrays;

      if (recordArrays) {
        recordArrays.delete(this);
      }
    });
  },

  /**
    @method _unregisterFromManager
    @private
  */
  _unregisterFromManager() {
    this.manager.unregisterRecordArray(this);
  },

  willDestroy() {
    this._unregisterFromManager();
    this._dissociateFromOwnRecords();
    // TODO: we should not do work during destroy:
    //   * when objects are destroyed, they should simply be left to do
    //   * if logic errors do to this, that logic needs to be more careful during
    //    teardown (ember provides isDestroying/isDestroyed) for this reason
    //   * the exception being: if an dominator has a reference to this object,
    //     and must be informed to release e.g. e.g. removing itself from th
    //     recordArrayMananger
    set(this, 'content', null);
    set(this, 'length', 0);
    this._super(...arguments);
  },

  /*
    @method _createSnapshot
    @private
  */
  _createSnapshot(options) {
    // this is private for users, but public for ember-data internals
    return new SnapshotRecordArray(this, this.get('meta'), options);
  },

  /*
    @method _takeSnapshot
    @private
  */
  _takeSnapshot() {
    return get(this, 'content').map(internalModel => internalModel.createSnapshot());
  },
});
<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';
import { select } from '@storybook/addon-knobs';

import { Player } from 'video-react';
import MediaPlayer from './';

const multipleStreams = [
  {
    protocol: 'dash',
    uri:
      'http://yt-dash-mse-test.commondatastorage.googleapis.com/media/car-20120827-manifest.mpd'
  },
  {
    protocol: 'hls',
    uri:
      'http://storage.googleapis.com/shaka-demo-assets/angel-one-hls/hls.m3u8'
  }
];
const hlsStream = [
  {
    protocol: 'hls',
    uri:
      'http://storage.googleapis.com/shaka-demo-assets/angel-one-hls/hls.m3u8'
  }
];
const dashStream = [
  {
    protocol: 'dash',
    uri:
      'http://yt-dash-mse-test.commondatastorage.googleapis.com/media/car-20120827-manifest.mpd'
  }
];
const demoMp4 = 'https://media.w3.org/2010/05/sintel/trailer_hd.mp4';
const alternateDemoMp4 =
  'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4';
const demoMp3 = 'https://www.sample-videos.com/audio/mp3/wave.mp3';
const demoPosterImage =
  '//static.veritone.com/veritone-ui/default-nullstate.svg';

storiesOf('Video', module).add('Base', () => (
  <Player autoPlay src={demoMp4}/>
));

storiesOf('Video', module).add('MP4', () => (
  <MediaPlayer streams={multipleStreams} width={500} fluid={false}/>
));

storiesOf('Video', module).add('DASH', () => (
  <MediaPlayer autoPlay streams={dashStream} width={500} fluid={false}/>
));

storiesOf('Video', module).add('HLS', () => (
  <MediaPlayer autoPlay streams={hlsStream} width={500} fluid={false}/>
));

storiesOf('Video', module).add('Multiple Streams', () => (
  <MediaPlayer autoPlay streams={multipleStreams} width={500} fluid={false}/>
));

storiesOf('Video', module).add('Switch Source', () => {
  const label = 'Video Sources';
  const options = [demoMp4, alternateDemoMp4];
  const value = select(label, options, options[0]);

  return <MediaPlayer src={value} width={500} fluid={false}/>;
});

storiesOf('Video', module).add('Audio only', () => (
  <MediaPlayer
    src={demoMp3}
    width={500}
    fluid={false}
    poster={demoPosterImage}
  />
));
<commit_msg>fix story syntax<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { select } from '@storybook/addon-knobs';

import { Player } from 'video-react';
import MediaPlayer from './';

const multipleStreams = [
  {
    protocol: 'dash',
    uri:
      'http://yt-dash-mse-test.commondatastorage.googleapis.com/media/car-20120827-manifest.mpd'
  },
  {
    protocol: 'hls',
    uri:
      'http://storage.googleapis.com/shaka-demo-assets/angel-one-hls/hls.m3u8'
  }
];
const hlsStream = [
  {
    protocol: 'hls',
    uri:
      'http://storage.googleapis.com/shaka-demo-assets/angel-one-hls/hls.m3u8'
  }
];
const dashStream = [
  {
    protocol: 'dash',
    uri:
      'http://yt-dash-mse-test.commondatastorage.googleapis.com/media/car-20120827-manifest.mpd'
  }
];
const demoMp4 = 'https://media.w3.org/2010/05/sintel/trailer_hd.mp4';
const alternateDemoMp4 =
  'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4';
const demoMp3 = 'https://www.sample-videos.com/audio/mp3/wave.mp3';
const demoPosterImage =
  '//static.veritone.com/veritone-ui/default-nullstate.svg';

storiesOf('MediaPlayer', module)
  .add('Base', () => <Player autoPlay src={demoMp4} />)

  .add('MP4', () => (
    <MediaPlayer streams={multipleStreams} width={500} fluid={false} />
  ))

  .add('DASH', () => (
    <MediaPlayer autoPlay streams={dashStream} width={500} fluid={false} />
  ))

  .add('HLS', () => (
    <MediaPlayer autoPlay streams={hlsStream} width={500} fluid={false} />
  ))

  .add('Multiple Streams', () => (
    <MediaPlayer autoPlay streams={multipleStreams} width={500} fluid={false} />
  ))

  .add('Switch Source', () => {
    const label = 'Video Sources';
    const options = [demoMp4, alternateDemoMp4];
    const value = select(label, options, options[0]);

    return <MediaPlayer src={value} width={500} fluid={false} />;
  })

  .add('Audio only', () => (
    <MediaPlayer
      src={demoMp3}
      width={500}
      fluid={false}
      poster={demoPosterImage}
    />
  ));
<|endoftext|>


<commit_before>var templates = [
    "root/externallib/text!root/plugins/myfiles/files.html"
];

define(templates, function (filesTpl) {
    var plugin = {
        settings: {
            name: "myfiles",
            type: "general",
            icon: "plugins/myfiles/icon.png",
            menuURL: "#myfiles/root",
            lang: {
                component: "core"
            }
        },

        storage: {
            file: {type: "model"},
            files: {type: "collection", model: "file"}
        },

        routes: [
            ["myfiles/:dir", "show_files", "showFiles"],
        ],

        path: [],

        wsPrefix: "",

        /**
         * Determines is the plugin is visible.
         * It may check Moodle remote site version, device OS, device type, etc...
         * This function is called when a alink to a plugin functinality is going to be rendered.
         *
         * @return {bool} True if the plugin is visible for the site and device
         */
        isPluginVisible: function() {
            if (MM.util.wsAvailable('local_mobile_core_files_get_files')) {
                MM.plugins.myfiles.wsPrefix = 'local_mobile_';
                return true;
            }

            return MM.util.wsAvailable('core_files_get_files');
        },

        /**
         * Display global and course files for all the user courses
         *
         * @param  {string} dir The directory to show
         */
        showFiles: function(dir) {
            var html;
            var pageTitle = MM.lang.s("myfiles");

            var params = {
                "contextid": 0,
                "component": "",
                "filearea": "",
                "itemid": 0,
                "filepath": "",
                "filename": ""
            };

            var data = {
                goBack: true,
                fullPath: "",
                dir: dir,
                entries: []
            };

            if (dir == "root") {
                data.goBack = false;
                var entry = {
                    isdir: 1,
                    link: "private",
                    linkId: hex_md5("private"),
                    imgpath: "img/mod/folder.png",
                    filename: MM.lang.s("privatefiles"),
                };
                data.entries.push(entry);

                entry = {
                    isdir: 1,
                    link: "site",
                    linkId: hex_md5("site"),
                    imgpath: "img/mod/folder.png",
                    filename: MM.lang.s("sitefiles"),
                };
                data.entries.push(entry);

                html = MM.tpl.render(MM.plugins.myfiles.templates.files.html, data);
                MM.panels.show('center', html, {title: pageTitle, hideRight: true});
                return;

            } else if (dir == "private") {

                params.component = "user";
                params.filearea = "private";
                params.contextid = -1;
                params.contextlevel = "user";
                params.instanceid = MM.config.current_site.userid;

            } else if (dir == "site") {
                data.fullPath = MM.lang.s("system");

            } else {
                try {
                    params = JSON.parse(dir);
                } catch(e) {
                    MM.popErrorMessage(MM.lang.s("errorlistingfiles"));
                    return;
                }
            }

            var link = hex_md5(encodeURIComponent(dir));
            $('#' + link, '#panel-center').addClass('loading-row-black');

            var wsName = MM.plugins.myfiles.wsPrefix + "core_files_get_files";

            MM.moodleWSCall(wsName,
                params,
                function(result) {
                    if (typeof result.files == "undefined") {
                        MM.popErrorMessage(MM.lang.s("errorlistingfiles"));
                        return;
                    }
                    _.each(result.files, function(entry) {
                        entry.link = {};
                        entry.link.contextid = (entry.contextid) ? entry.contextid : "";
                        entry.link.component = (entry.component) ? entry.component : "";
                        entry.link.filearea = (entry.filearea) ? entry.filearea : "";
                        entry.link.itemid = (entry.itemid) ? entry.itemid : 0;
                        entry.link.filepath = (entry.filepath) ? entry.filepath : "";
                        entry.link.filename = (entry.filename) ? entry.filename : "";
                        if (entry.component && entry.isdir) {
                            // Delete unused elements that may broke the request.
                            entry.link.filename = "";
                        }

                        if (entry.isdir) {
                            entry.imgpath = "img/mod/folder.png";
                        } else {
                            var extension = MM.util.getFileExtension(entry.filename);
                            if (typeof(MM.plugins.contents.templates.mimetypes[extension]) != "undefined") {
                                entry.imgpath = "img/files/" + MM.plugins.contents.templates.mimetypes[extension]["icon"] + "-64.png";
                            }
                        }

                        entry.link = encodeURIComponent(JSON.stringify(entry.link));
                        entry.linkId = hex_md5(entry.link);
                        entry.filename = MM.util.formatText(entry.filename, true);
                        entry.localpath = "";

                        if (!entry.isdir && entry.url) {
                            var uniqueId = MM.config.current_site.id + "-" + hex_md5(entry.url);
                            var path = MM.db.get("files", uniqueId);
                            if (path) {
                                entry.localpath = path.get("localpath");
                            }
                        }

                        data.entries.push(entry);
                    });

                    var parents = [];
                    _.each(result.parents, function(parent) {
                        parents.push(parent.filename);
                    });
                    // Push the current requested directory.
                    parents.push(params.filename ? params.filename : params.path);

                    if (dir == "site") {
                        data.fullPath = MM.lang.s("system");
                    }
                    else if (parents.length > 0) {
                        data.fullPath = parents.join(" / ");
                    }

                    html = MM.tpl.render(MM.plugins.myfiles.templates.files.html, data);
                    MM.panels.show('center', html, {title: pageTitle, hideRight: true});

                    // Bind downloads.
                    $(".myfiles-download").on(MM.clickType, function(e) {
                        e.preventDefault();
                        e.stopPropagation();

                        var url = $(this).data("url");
                        var filename = $(this).data("filename");
                        var linkId = $(this).data("linkid");

                        MM.plugins.myfiles._downloadFile(url, filename, linkId);
                    });

                    // Hack, in iPad this page is not rendered well, it needs a refresh doing a DOM change.
                    $(".nav.nav-v", "#panel-center").css("display", "block");
                },
                null,
                function (error) {
                    MM.popErrorMessage(error);
                }
            );
        },

        _downloadFile: function(url, filename, linkId) {
            // Add the token.
            var downloadURL = MM.fixPluginfile(url);
            var siteId = MM.config.current_site.id;
            var linkCssId = "#" + linkId;
            var downCssId = "#img-" + linkId;

            filename = MM.fs.normalizeFileName(filename);

            var directory = siteId + "/files/" + linkId;
            var filePath = directory + "/" + filename;

            MM.fs.init(function() {
                if (MM.deviceConnected()) {
                    MM.log("Starting download of Moodle file: " + downloadURL);
                    // All the functions are asynchronous, like createDir.
                    MM.fs.createDir(directory, function() {
                        MM.log("Downloading Moodle file to " + filePath + " from URL: " + downloadURL);

                        $(downCssId).attr("src", "img/loadingblack.gif");
                        MM.moodleDownloadFile(downloadURL, filePath,
                            function(fullpath) {
                                MM.log("Download of content finished " + fullpath + " URL: " + downloadURL);

                                var uniqueId = siteId + "-" + hex_md5(url);
                                var file = {
                                    id: uniqueId,
                                    url: url,
                                    site: siteId,
                                    localpath: fullpath
                                };
                                MM.db.insert("files", file);

                                $(downCssId).remove();
                                $(linkCssId).attr("href", fullpath);
                                $(linkCssId).attr("rel", "external");
                                // Remove class and events.
                                $(linkCssId).removeClass("myfiles-download");
                                $(linkCssId).off(MM.clickType);

                                // Android, open in new browser
                                MM.handleFiles(linkCssId);
                                MM._openFile(fullpath);
                            },
                            function(fullpath) {
                                $(downCssId).remove();
                                MM.log("Error downloading " + fullpath + " URL: " + downloadURL);
                            }
                        );
                    });
                } else {
                    MM.popErrorMessage(MM.lang.s("errornoconnectednocache"));
                }
            });
        },

        templates: {
            "files": {
                html: filesTpl
            }
        }

    };

    MM.registerPlugin(plugin);

});<commit_msg>MOBILE-771 My files: Fixes for my private files par<commit_after>var templates = [
    "root/externallib/text!root/plugins/myfiles/files.html"
];

define(templates, function (filesTpl) {
    var plugin = {
        settings: {
            name: "myfiles",
            type: "general",
            icon: "plugins/myfiles/icon.png",
            menuURL: "#myfiles/root",
            lang: {
                component: "core"
            }
        },

        storage: {
            file: {type: "model"},
            files: {type: "collection", model: "file"}
        },

        routes: [
            ["myfiles/:dir", "show_files", "showFiles"],
        ],

        path: [],

        wsPrefix: "",

        /**
         * Determines is the plugin is visible.
         * It may check Moodle remote site version, device OS, device type, etc...
         * This function is called when a alink to a plugin functinality is going to be rendered.
         *
         * @return {bool} True if the plugin is visible for the site and device
         */
        isPluginVisible: function() {
            if (MM.util.wsAvailable('local_mobile_core_files_get_files')) {
                MM.plugins.myfiles.wsPrefix = 'local_mobile_';
                return true;
            }

            return MM.util.wsAvailable('core_files_get_files');
        },

        /**
         * Display global and course files for all the user courses
         *
         * @param  {string} dir The directory to show
         */
        showFiles: function(dir) {
            var html;
            var pageTitle = MM.lang.s("myfiles");

            var params = {
                "contextid": 0,
                "component": "",
                "filearea": "",
                "itemid": 0,
                "filepath": "",
                "filename": ""
            };

            var data = {
                goBack: true,
                fullPath: "",
                dir: dir,
                entries: []
            };

            if (dir == "root") {
                data.goBack = false;
                var entry = {
                    isdir: 1,
                    link: "private",
                    linkId: hex_md5("private"),
                    imgpath: "img/mod/folder.png",
                    filename: MM.lang.s("privatefiles"),
                };
                data.entries.push(entry);

                entry = {
                    isdir: 1,
                    link: "site",
                    linkId: hex_md5("site"),
                    imgpath: "img/mod/folder.png",
                    filename: MM.lang.s("sitefiles"),
                };
                data.entries.push(entry);

                html = MM.tpl.render(MM.plugins.myfiles.templates.files.html, data);
                MM.panels.show('center', html, {title: pageTitle, hideRight: true});
                return;

            } else if (dir == "private") {

                params.component = "user";
                params.filearea = "private";
                params.contextid = -1;
                params.contextlevel = "user";
                params.instanceid = MM.config.current_site.userid;

            } else if (dir == "site") {
                data.fullPath = MM.lang.s("system");

            } else {
                try {
                    params = JSON.parse(dir);
                } catch(e) {
                    MM.popErrorMessage(MM.lang.s("errorlistingfiles"));
                    return;
                }
            }

            var link = hex_md5(encodeURIComponent(dir));
            $('#' + link, '#panel-center').addClass('loading-row-black');

            var wsName = MM.plugins.myfiles.wsPrefix + "core_files_get_files";

            MM.moodleWSCall(wsName,
                params,
                function(result) {
                    if (typeof result.files == "undefined") {
                        MM.popErrorMessage(MM.lang.s("errorlistingfiles"));
                        return;
                    }
                    _.each(result.files, function(entry) {
                        entry.link = {};
                        entry.link.contextid = (entry.contextid) ? entry.contextid : "";
                        entry.link.component = (entry.component) ? entry.component : "";
                        entry.link.filearea = (entry.filearea) ? entry.filearea : "";
                        entry.link.itemid = (entry.itemid) ? entry.itemid : 0;
                        entry.link.filepath = (entry.filepath) ? entry.filepath : "";
                        entry.link.filename = (entry.filename) ? entry.filename : "";
                        if (entry.component && entry.isdir) {
                            // Delete unused elements that may broke the request.
                            entry.link.filename = "";
                        }

                        if (entry.isdir) {
                            entry.imgpath = "img/mod/folder.png";
                        } else {
                            var extension = MM.util.getFileExtension(entry.filename);
                            if (typeof(MM.plugins.contents.templates.mimetypes[extension]) != "undefined") {
                                entry.imgpath = "img/files/" + MM.plugins.contents.templates.mimetypes[extension]["icon"] + "-64.png";
                            }
                        }

                        entry.link = encodeURIComponent(JSON.stringify(entry.link));
                        entry.linkId = hex_md5(entry.link);
                        entry.filename = MM.util.formatText(entry.filename, true);
                        entry.localpath = "";

                        if (!entry.isdir && entry.url) {
                            var uniqueId = MM.config.current_site.id + "-" + hex_md5(entry.url);
                            var path = MM.db.get("files", uniqueId);
                            if (path) {
                                entry.localpath = path.get("localpath");
                            }
                        }

                        data.entries.push(entry);
                    });

                    var parents = [];
                    _.each(result.parents, function(parent) {
                        parents.push(parent.filename);
                    });
                    // Push the current requested directory.
                    parents.push(params.filename ? params.filename : params.path);

                    if (dir == "site") {
                        data.fullPath = MM.lang.s("system");
                    }
                    else if (parents.length > 0) {
                        data.fullPath = parents.join(" / ");
                    }

                    html = MM.tpl.render(MM.plugins.myfiles.templates.files.html, data);
                    MM.panels.show('center', html, {title: pageTitle, hideRight: true});

                    // Bind downloads.
                    $(".myfiles-download").on(MM.clickType, function(e) {
                        e.preventDefault();
                        e.stopPropagation();

                        var url = $(this).data("url");
                        var filename = $(this).data("filename");
                        var linkId = $(this).data("linkid");

                        MM.plugins.myfiles._downloadFile(url, filename, linkId);
                    });

                    // Hack, in iPad this page is not rendered well, it needs a refresh doing a DOM change.
                    setTimeout(function() {
                        $(".nav.nav-v", "#panel-center").css("display", "block");
                        $("#panel-center").css("width", "99%");
                    }, 200);
                },
                null,
                function (error) {
                    MM.popErrorMessage(error);
                }
            );
        },

        _downloadFile: function(url, filename, linkId) {
            // Add the token.
            var downloadURL = MM.fixPluginfile(url);
            var siteId = MM.config.current_site.id;
            var linkCssId = "#" + linkId;
            var downCssId = "#img-" + linkId;

            filename = MM.fs.normalizeFileName(filename);

            var directory = siteId + "/files/" + linkId;
            var filePath = directory + "/" + filename;

            MM.fs.init(function() {
                if (MM.deviceConnected()) {
                    MM.log("Starting download of Moodle file: " + downloadURL);
                    // All the functions are asynchronous, like createDir.
                    MM.fs.createDir(directory, function() {
                        MM.log("Downloading Moodle file to " + filePath + " from URL: " + downloadURL);

                        $(downCssId).attr("src", "img/loadingblack.gif");
                        MM.moodleDownloadFile(downloadURL, filePath,
                            function(fullpath) {
                                MM.log("Download of content finished " + fullpath + " URL: " + downloadURL);

                                var uniqueId = siteId + "-" + hex_md5(url);
                                var file = {
                                    id: uniqueId,
                                    url: url,
                                    site: siteId,
                                    localpath: fullpath
                                };
                                MM.db.insert("files", file);

                                $(downCssId).remove();
                                $(linkCssId).attr("href", fullpath);
                                $(linkCssId).attr("rel", "external");
                                // Remove class and events.
                                $(linkCssId).removeClass("myfiles-download");
                                $(linkCssId).off(MM.clickType);

                                // Android, open in new browser
                                MM.handleFiles(linkCssId);
                                MM._openFile(fullpath);
                            },
                            function(fullpath) {
                                $(downCssId).remove();
                                MM.log("Error downloading " + fullpath + " URL: " + downloadURL);
                            }
                        );
                    });
                } else {
                    MM.popErrorMessage(MM.lang.s("errornoconnectednocache"));
                }
            });
        },

        templates: {
            "files": {
                html: filesTpl
            }
        }

    };

    MM.registerPlugin(plugin);

});<|endoftext|>


<commit_before><commit_msg>Fixed an issue where the first char is lost when you navigate to Select by Tab<commit_after><|endoftext|>


<commit_before>// const hljs = require('highlightjs'); // https://highlightjs.org/
//
// const md = require('markdown-it')({
//   highlight(str, lang) {
//     if (lang && hljs.getLanguage(lang)) {
//       try {
//         return `
${
//           hljs.highlight(lang, str, true).value
//           }
`.replace(/\n/g, '
');
//       } catch (__) {
//         console.error(__);
//       }
//     }
//
//     return `<pre class="hljs"><code>${md.utils.escapeHtml(str).replace(/\n/g, '<br>')}</code></pre>`;
//   }
// });

const md = require('markdown-it')();
const isString = require('lodash.isstring');

export default class MarkdownHelper {
  static convert(str, options) {
    if (!isString(str)) {
      return '';
    }
    let width = options.width;
    let height = width * 0.6;
    let html = md.render(str);
    html.replace(new RegExp('
', 'g'), '')
        .replace(new RegExp('
', 'g'), '')
        .replace('src="/static/media/uploads/',
          `width="${width}" height="${height}" src="https://www.wandianshenme.com/static/media/uploads/`);
    return html;
  }
}
<commit_msg>[native-html] fix width issue<commit_after>// const hljs = require('highlightjs'); // https://highlightjs.org/
//
// const md = require('markdown-it')({
//   highlight(str, lang) {
//     if (lang && hljs.getLanguage(lang)) {
//       try {
//         return `
${
//           hljs.highlight(lang, str, true).value
//           }
`.replace(/\n/g, '
');
//       } catch (__) {
//         console.error(__);
//       }
//     }
//
//     return `<pre class="hljs"><code>${md.utils.escapeHtml(str).replace(/\n/g, '<br>')}</code></pre>`;
//   }
// });

const md = require('markdown-it')();
const isString = require('lodash.isstring');

export default class MarkdownHelper {
  static convert(str, options) {
    if (!isString(str)) {
      return '';
    }
    let paddingWidth = 20;
    let width = options.width - paddingWidth;
    let height = width * 0.6;
    let html = md.render(str);
    html = html.replace(new RegExp('
', 'g'), '')
        .replace(new RegExp('
', 'g'), '')
        .replace('src="/static/media/uploads/',
          `width="${width}" height="${height}" src="https://www.wandianshenme.com/static/media/uploads/`);
    return html;
  }
}
<|endoftext|>


<commit_before>var db = require('../models');
exports.listar = function(request, reply){
  if (request.params.idEvento){
    db.Evento.findOne({_id: request.params.idEvento}, function(err, evento){
      if (err){
        reply({statusCode: 600, error: "Database", message:"Evento no encontrado"});
      } else if (evento){
        reply({statusCode:200,evento:evento});
      } else {
        reply({statusCode: 600, error: "Database", message:"Evento no encontrado"});
      }
    });
  } else {
    db.Evento.find(function(err, eventos){
      if (err){
        reply({statusCode: 600, error: "Database", message:"Evento no encontrado"});
      } else if (eventos){
        reply({statusCode:200,eventos:eventos});
      } else {
        reply({statusCode: 600, error: "Database", message:"Evento no encontrado"});
      }
    });
  }
};
exports.atletas = function(request, reply){
  db.AtletaEvento
  .find({evento: request.params.idEvento})
  .populate("atleta evento")
  .exec(function(err, atletas){
    if (err){
      reply({statusCode: 600, error: "Database", message:"Equipo no encontrado"});
    } else if (atletas_eventos){
      reply({statusCode:200,atletas:atletas});
    } else {
      reply({statusCode: 600, error: "Database", message:"Equipo no encontrado"});
    }
  });
};
exports.create = function(request, reply){
  new db.Evento(request.payload).save(function(err, evento, numberAffected){
    if(err){
      return reply({statusCode: 600, error: "Database", message: "Error de Base de datos."});
    }
    return reply({statusCode: 200, _id: evento._id});
  });
}
exports.save = function(request, reply){
  var evento = request.payload;
  evento.modified = Date.now();
  db.Evento.update({_id:request.params.idEvento}, {$set: evento}, function(err, raw){
    if (err) {
      console.log("EVENTOS_SAVE err="+JSON.stringify(err));
      return reply({statusCode:600});
    }
    return reply({statusCode: 200});
  });
}
exports.delete = function(request, reply){
  db.Evento.remove({_id:request.params.idEvento}, function(err){
    if (err) {
      console.log("ATLETAS_DELETE err="+JSON.stringify(err));
      return reply({statusCode:600});
    }
    db.AtletaEvento.remove({evento:request.params.idEvento}, function(errAE){
      if (errAE) {
        console.log("ATLETA_EVENTOS_DELETE err="+JSON.stringify(errAE));
        return reply({statusCode:600});
      }
      return reply({statusCode: 200});
    });
  });
}
<commit_msg>Corrección de nombre de variable<commit_after>var db = require('../models');
exports.listar = function(request, reply){
  if (request.params.idEvento){
    db.Evento.findOne({_id: request.params.idEvento}, function(err, evento){
      if (err){
        reply({statusCode: 600, error: "Database", message:"Evento no encontrado"});
      } else if (evento){
        reply({statusCode:200,evento:evento});
      } else {
        reply({statusCode: 600, error: "Database", message:"Evento no encontrado"});
      }
    });
  } else {
    db.Evento.find(function(err, eventos){
      if (err){
        reply({statusCode: 600, error: "Database", message:"Evento no encontrado"});
      } else if (eventos){
        reply({statusCode:200,eventos:eventos});
      } else {
        reply({statusCode: 600, error: "Database", message:"Evento no encontrado"});
      }
    });
  }
};
exports.atletas = function(request, reply){
  db.AtletaEvento
  .find({evento: request.params.idEvento})
  .populate("atleta evento")
  .exec(function(err, atletas){
    if (err){
      reply({statusCode: 600, error: "Database", message:"Equipo no encontrado"});
    } else if (atletas){
      reply({statusCode:200,atletas:atletas});
    } else {
      reply({statusCode: 600, error: "Database", message:"Equipo no encontrado"});
    }
  });
};
exports.create = function(request, reply){
  new db.Evento(request.payload).save(function(err, evento, numberAffected){
    if(err){
      return reply({statusCode: 600, error: "Database", message: "Error de Base de datos."});
    }
    return reply({statusCode: 200, _id: evento._id});
  });
}
exports.save = function(request, reply){
  var evento = request.payload;
  evento.modified = Date.now();
  db.Evento.update({_id:request.params.idEvento}, {$set: evento}, function(err, raw){
    if (err) {
      console.log("EVENTOS_SAVE err="+JSON.stringify(err));
      return reply({statusCode:600});
    }
    return reply({statusCode: 200});
  });
}
exports.delete = function(request, reply){
  db.Evento.remove({_id:request.params.idEvento}, function(err){
    if (err) {
      console.log("ATLETAS_DELETE err="+JSON.stringify(err));
      return reply({statusCode:600});
    }
    db.AtletaEvento.remove({evento:request.params.idEvento}, function(errAE){
      if (errAE) {
        console.log("ATLETA_EVENTOS_DELETE err="+JSON.stringify(errAE));
        return reply({statusCode:600});
      }
      return reply({statusCode: 200});
    });
  });
}
<|endoftext|>