<commit_before>var state = {
    query: "",
    selected_history_entry: -1,
    buffers: {},
    open: []
};

var search_history = {
    max_size: 8,
    get: function () {
        return (JSON.parse(localStorage.getItem('history')) || []).reverse();
    },
    clear: function () {
        localStorage.removeItem('history');
    },
    push: function (query) {
        if (!query)
            return;

        var tmp = search_history.get().filter(function (x) {
            return x != query;
        }).reverse();
        tmp.push(query);
        localStorage.setItem('history', JSON.stringify(tmp.slice(Math.max(0, tmp.length - search_history.max_size))));
    }
};

var render = {
    overview: function (ids) {
        $("#results").children().remove();

        for (var i = 0; i < ids.length; i++) {
            var buffer = ids[i];

            if (!state.buffers.hasOwnProperty(buffer.bufferid)) {
                var ctx = 0;
                state.buffers[buffer.bufferid] = {
                    id: buffer.bufferid,
                    name: buffer.buffername,
                    network: buffer.networkname,
                    selected: false,
                    contexts: buffer.messages.map(function (message) {
                        return {
                            "selected": false,
                            "original": message,
                            "before": [],
                            "after": [],
                            "buffer": buffer.bufferid,
                            "id": ctx++
                        };
                    }),
                    offset: 0
                }
            }

            render.buffer.update(buffer.bufferid);
        }

        if (ids.length == 0)
            render.no_more();
    },
    buffer: {
        auto: function (buffer) {
            return (buffer.selected) ? render.buffer.full(buffer) : render.buffer.overview(buffer);
        },
        overview: function (buffer) {
            return (
                "<buffer id='buffer" + buffer.id + "' data-bufferid='" + buffer.id + "'>" + (
                    "
" + buffer.network + " – " + buffer.name + "
" +
                    "
" + (
                        buffer.contexts.slice(0, 4).map(render.context.auto).join("") +
                        "<inline-button class='load_more'>" + (buffer.contexts.length > 4 ? translation.results.show_more : translation.results.load_more) + "</inline-button>"
                    ) + "
"
                ) + "</buffer>"
            )
        },
        full: function (buffer) {
            return (
                "<buffer id='buffer" + buffer.id + "' data-bufferid='" + buffer.id + "' class='selected'>" + (
                    "
" + buffer.network + " – " + buffer.name + "
" +
                    "
" + (
                        buffer.contexts.map(render.context.auto).join("") +
                        "<inline-button class='load_more'>" + translation.results.load_more + "</inline-button>"
                    ) + "
"
                ) + "</buffer>"
            )
        },
        update: function (id) {
            var renderedBuffer = render.buffer.auto(state.buffers[id]);
            if ($("#buffer" + id).length)
                $("#buffer" + id).replaceWith(renderedBuffer);
            else
                $("#results").append(renderedBuffer);

            render.buffer.attach($("#buffer" + id));
        },
        attach: function (elem) {
            elem.unbind();
            var id = elem.data("bufferid");
            elem.click(make_toggle_buffer(id));
            elem.find(".load_more").click(function (e) {
                e.stopPropagation();

                if (state.buffers[id].selected || state.buffers[id].contexts.length <= 4)
                    load.buffer.more(id);

                deselect_buffers(id);
                state.open.push(make_toggle_buffer(id));
                state.buffers[id].selected = true;
                render.buffer.update(id);
            });
            state.buffers[id].contexts.forEach(function (context) {
                var ctx = elem.find("#context" + context.id);
                if (ctx.length)
                    render.context.attach(ctx);
            })
        }
    },
    context: {
        auto: function (context) {
            return context.selected ? render.context.full(context) : render.context.overview(context);
        },
        overview: function (context) {
            return (
                "<context id='context" + context.id + "' data-contextid='" + context.id + "' data-bufferid='" + context.buffer + "'>" + (
                    render.message(context.original, true, true)
                ) + "</context>"
            )
        },
        full: function (context) {
            return (
                "<context id='context" + context.id + "' data-contextid='" + context.id + "' data-bufferid='" + context.buffer + "' class='selected'>" + (
                    "<inline-button class='load_before'>" + translation.context.load_earlier + "</inline-button>" + (
                        context.before.map(render.message).join("") +
                        render.message(context.original, true) +
                        context.after.map(render.message).join("")
                    ) + "<inline-button class='load_after'>" + translation.context.load_later + "</inline-button>"
                ) + "</context>"
            )
        },
        attach: function (elem) {
            elem.unbind();
            var id = elem.data("contextid");
            var bufferid = elem.data("bufferid");
            if (state.buffers[bufferid] === undefined) {
                console.log("Undefined buffer: " + bufferid);
            }

            elem.click(function (e) {
                e.stopPropagation();
            });
            $("#message" + state.buffers[bufferid].contexts[id].original.messageid).click(make_toggle_context(bufferid, id));
            elem.find(".load_before").click(function (e) {
                e.stopPropagation();

                load.context.earlier(bufferid, id, 5);
            });
            elem.find(".load_after").click(function (e) {
                e.stopPropagation();

                load.context.later(bufferid, id, 5);
            });
        }
    },
    message: function (message, highlight, preview) {
        var content = preview === true ? message.preview : message.message;
        return (
            "<message id='message" + message.messageid + "' data-messageid='" + message.messageid + "' " + (highlight === true ? "" : "class='faded'") + ">" + (
                "<time>" + new Date(message.time.replace(" ", "T") + "Z").toLocaleString() + "</time>" +
                "
" + (
                    "<sender style='color: " + sendercolor(message.sender.split("!")[0]) + "'>" + message.sender.split("!")[0] + "</sender>" +
                    "<content>" + content + "</content>"
                ) + "
"
            ) + "</message>"
        )
    },
    history: {
        all: function (history) {
            var container = $("#autocomplete ul");
            container.children().remove();

            for (var i = 0; i < history.length; i++) {
                container.append(render.history.item(i, history[i]));
                render.history.attach($("#history" + i));
            }
            if (history.length == 0) {
                container.append("
" + translation.history.error_unavailable + "
");
            }
        },
        item: function (id, query) {
            return (
                "
" + (
                    "history" +
                    query
                ) + "
"
            )
        },
        attach: function (elem) {
            elem.unbind();
            var query = atob(elem.data("query"));
            elem.click(function (e) {
                e.stopPropagation();

                $("#q").val(query);
                search();
            });
        }
    },
    loader: function () {
        $("#results").append("
<svg class='circular' viewBox='25 25 50 50'><circle class='path' cx='50' cy='50' r='20' fill='none' stroke-width='4' stroke-miterlimit='10'/></svg>
");
    },
    no_more: function () {
        $("#results").append("

No results

");
    }
};

var load = {
    overview: function (query, callback) {
        $.post("web/search/?" + $.param({"query": query}), callback, "json");
    },
    buffer: {
        raw: function (query, buffer, offset, limit, callback) {
            $.post("web/searchbuffer/?" + $.param({
                    "query": query,
                    "buffer": buffer,
                    "offset": offset,
                    "limit": limit
                }), callback, "json");
        },
        more: function (id, limit) {
            if (limit === undefined)
                limit = 10;

            load.buffer.raw(state.query, id, state.buffers[id].contexts.length, limit, function (data) {
                var ctx = state.buffers[id].contexts.length;
                state.buffers[id].contexts = state.buffers[id].contexts.concat(data.map(function (message) {
                    return {
                        "selected": false,
                        "original": message,
                        "before": [],
                        "after": [],
                        "buffer": id,
                        "id": ctx++
                    };
                }));
                render.buffer.update(id);
            });
        }
    },
    context: {
        raw: function (msg, buffer, before, after, callback) {
            $.post("web/backlog/?" + $.param({
                    "anchor": msg,
                    "buffer": buffer,
                    "before": before,
                    "after": after
                }), callback, "json");
        },
        earlier: function (bufferid, contextid, amount) {
            var buffer = state.buffers[bufferid];
            var context = buffer.contexts[contextid];
            var earliest = (context.before[0] || context.original).messageid;
            load.context.raw(earliest, bufferid, amount, 0, function (messages) {
                var newmsgs = messages.slice(0, messages.length - 1);
                context.before = newmsgs.concat(context.before);
                render.buffer.update(bufferid);
            })
        },
        later: function (bufferid, contextid, amount) {
            var buffer = state.buffers[bufferid];
            var context = buffer.contexts[contextid];
            var latest = (context.after[context.after.length - 1] || context.original).messageid;
            load.context.raw(latest, bufferid, 0, amount, function (messages) {
                var newmsgs = messages.slice(1);
                context.after = context.after.concat(newmsgs);
                render.buffer.update(bufferid);
            })
        }
    }
};

var search = function () {
    var results = $("#results");
    results.children().remove();
    $("#q").blur();
    results.click(deselect_buffers);
    state = {
        "query": $("#q").val(),
        "selected_history_entry": -1,
        "buffers": {},
        "open": []
    };
    window.location = "#" + encodeURIComponent(state.query);
    if (state.query) {
        render.loader();
        load.overview(state.query, render.overview);
        search_history.push(state.query);
        render.history.all(search_history.get());
    }
};

var deselect_buffers = function (except) {
    $.each(state.buffers, function (key, buffer) {
        if (key !== except && buffer.selected) {
            buffer.selected = false;
            unselect_contexts(key);
            render.buffer.update(key);
        }
    });
    state.open = [];
};

var unselect_contexts = function (bufferid) {
    state.buffers[bufferid].contexts = state.buffers[bufferid].contexts.map(function (context) {
        context.selected = false;
        return context
    })
};

var make_toggle_buffer = function (id) {
    return function (e) {
        e.stopPropagation();

        if (state.buffers[id].selected) {
            deselect_buffers();
            state.open.pop();
            state.buffers[id].selected = false;
        } else {
            deselect_buffers(id);
            state.open.push(make_toggle_buffer(id));
            state.buffers[id].selected = true;
        }
        render.buffer.update(id);
    }
};

var make_toggle_context = function (buffer, id) {
    return function (e) {
        e.stopPropagation();

        var context = state.buffers[buffer].contexts[id];
        if (context.selected) {
            unselect_contexts(buffer);
            context.selected = false;
            state.open.pop();
        } else {
            deselect_buffers(buffer);
            unselect_contexts(buffer);
            if (!state.buffers[buffer].selected) {
                state.open.push(make_toggle_buffer(buffer));
                state.buffers[buffer].selected = true;
            }
            context.selected = true;
            state.open.push(make_toggle_context(buffer, id));
            if (context.before.length === 0) load.context.earlier(buffer, id, 5);
            if (context.after.length === 0) load.context.later(buffer, id, 5);
        }
        render.buffer.update(buffer);
    }
};

var hashChange = function () {
    var input = $("#q");
    var newquery = decodeURIComponent(location.hash.substr(1));
    if (input.val() != newquery) {
        input.val(newquery);
        search();
    }
};

var init = function () {
    $("body").on("click", function (e) {
        if (state.open.length)
            state.open[state.open.length - 1](e);
    });

    $("nav").on("click", function (e) {
        e.stopPropagation();
    });

    $(window).on("hashchange", hashChange);

    $("#q").on("keypress", function (e) {
        var key = e.which || e.keyCode;
        if (key === 13) {
            search();
        }
        if (key === 40) {
            $("#history" + state.selected_history_entry).removeClass("selected");
            state.selected_history_entry = (state.selected_history_entry + 1) % get_history().length;
            $("#q").val(get_history().reverse()[state.selected_history_entry]);
            $("#history" + state.selected_history_entry).addClass("selected");
        } else if (key === 38) {
            $("#history" + state.selected_history_entry).removeClass("selected");
            if (state.selected_history_entry === 0) {
                state.selected_history_entry = -1;
                $("#q").val("");
            } else {
                state.selected_history_entry = (state.selected_history_entry - 1) % get_history().length;
                $("#q").val(get_history().reverse()[state.selected_history_entry]);
                $("#history" + state.selected_history_entry).addClass("selected");
            }
        }
    });

    $("#q").on("focus", function () {
        $("#autocomplete").addClass("active");
        $("#results").addClass("hidden");
        $("nav").addClass("search");
    });
    $("#q").on("blur", function () {
        $("#autocomplete").removeClass("active");
        $("#results").removeClass("hidden");
        $("nav").removeClass("search");
    });

    hashChange();
    render.history.all(search_history.get());
};
init();<commit_msg>Fixed an UI issue<commit_after>var state = {
    query: "",
    selected_history_entry: -1,
    buffers: {},
    open: []
};

var search_history = {
    max_size: 8,
    get: function () {
        return (JSON.parse(localStorage.getItem('history')) || []).reverse();
    },
    clear: function () {
        localStorage.removeItem('history');
    },
    push: function (query) {
        if (!query)
            return;

        var tmp = search_history.get().filter(function (x) {
            return x != query;
        }).reverse();
        tmp.push(query);
        localStorage.setItem('history', JSON.stringify(tmp.slice(Math.max(0, tmp.length - search_history.max_size))));
    }
};

var render = {
    overview: function (ids) {
        $("#results").children().remove();

        for (var i = 0; i < ids.length; i++) {
            var buffer = ids[i];

            if (!state.buffers.hasOwnProperty(buffer.bufferid)) {
                var ctx = 0;
                state.buffers[buffer.bufferid] = {
                    id: buffer.bufferid,
                    name: buffer.buffername,
                    network: buffer.networkname,
                    selected: false,
                    contexts: buffer.messages.map(function (message) {
                        return {
                            "selected": false,
                            "original": message,
                            "before": [],
                            "after": [],
                            "buffer": buffer.bufferid,
                            "id": ctx++
                        };
                    }),
                    offset: 0
                }
            }

            render.buffer.update(buffer.bufferid);
        }

        if (ids.length == 0)
            render.no_more();
    },
    buffer: {
        auto: function (buffer) {
            return (buffer.selected) ? render.buffer.full(buffer) : render.buffer.overview(buffer);
        },
        overview: function (buffer) {
            return (
                "<buffer id='buffer" + buffer.id + "' data-bufferid='" + buffer.id + "'>" + (
                    "
" + buffer.network + " – " + buffer.name + "
" +
                    "
" + (
                        buffer.contexts.slice(0, 4).map(render.context.auto).join("") +
                        "<inline-button class='load_more'>" + (buffer.contexts.length > 4 ? translation.results.show_more : translation.results.load_more) + "</inline-button>"
                    ) + "
"
                ) + "</buffer>"
            )
        },
        full: function (buffer) {
            return (
                "<buffer id='buffer" + buffer.id + "' data-bufferid='" + buffer.id + "' class='selected'>" + (
                    "
" + buffer.network + " – " + buffer.name + "
" +
                    "
" + (
                        buffer.contexts.map(render.context.auto).join("") +
                        "<inline-button class='load_more'>" + translation.results.load_more + "</inline-button>"
                    ) + "
"
                ) + "</buffer>"
            )
        },
        update: function (id) {
            var renderedBuffer = render.buffer.auto(state.buffers[id]);
            if ($("#buffer" + id).length)
                $("#buffer" + id).replaceWith(renderedBuffer);
            else
                $("#results").append(renderedBuffer);

            render.buffer.attach($("#buffer" + id));
        },
        attach: function (elem) {
            elem.unbind();
            var id = elem.data("bufferid");
            elem.click(make_toggle_buffer(id));
            elem.find(".load_more").click(function (e) {
                e.stopPropagation();

                if (state.buffers[id].selected || state.buffers[id].contexts.length <= 4)
                    load.buffer.more(id);

                deselect_buffers(id);
                state.open.push(make_toggle_buffer(id));
                state.buffers[id].selected = true;
                render.buffer.update(id);
            });
            state.buffers[id].contexts.forEach(function (context) {
                var ctx = elem.find("#context" + context.id);
                if (ctx.length)
                    render.context.attach(ctx);
            })
        }
    },
    context: {
        auto: function (context) {
            return context.selected ? render.context.full(context) : render.context.overview(context);
        },
        overview: function (context) {
            return (
                "<context id='context" + context.id + "' data-contextid='" + context.id + "' data-bufferid='" + context.buffer + "'>" + (
                    render.message(context.original, true, true)
                ) + "</context>"
            )
        },
        full: function (context) {
            return (
                "<context id='context" + context.id + "' data-contextid='" + context.id + "' data-bufferid='" + context.buffer + "' class='selected'>" + (
                    "<inline-button class='load_before'>" + translation.context.load_earlier + "</inline-button>" + (
                        context.before.map(render.message).join("") +
                        render.message(context.original, true) +
                        context.after.map(render.message).join("")
                    ) + "<inline-button class='load_after'>" + translation.context.load_later + "</inline-button>"
                ) + "</context>"
            )
        },
        attach: function (elem) {
            elem.unbind();
            var id = elem.data("contextid");
            var bufferid = elem.data("bufferid");
            if (state.buffers[bufferid] === undefined) {
                console.log("Undefined buffer: " + bufferid);
            }

            elem.click(function (e) {
                e.stopPropagation();
            });
            $("#message" + state.buffers[bufferid].contexts[id].original.messageid).unbind();
            $("#message" + state.buffers[bufferid].contexts[id].original.messageid).click(make_toggle_context(bufferid, id));
            elem.find(".load_before").click(function (e) {
                e.stopPropagation();

                load.context.earlier(bufferid, id, 5);
            });
            elem.find(".load_after").click(function (e) {
                e.stopPropagation();

                load.context.later(bufferid, id, 5);
            });
        }
    },
    message: function (message, highlight, preview) {
        var content = preview === true ? message.preview : message.message;
        return (
            "<message id='message" + message.messageid + "' data-messageid='" + message.messageid + "' " + (highlight === true ? "" : "class='faded'") + ">" + (
                "<time>" + new Date(message.time.replace(" ", "T") + "Z").toLocaleString() + "</time>" +
                "
" + (
                    "<sender style='color: " + sendercolor(message.sender.split("!")[0]) + "'>" + message.sender.split("!")[0] + "</sender>" +
                    "<content>" + content + "</content>"
                ) + "
"
            ) + "</message>"
        )
    },
    history: {
        all: function (history) {
            var container = $("#autocomplete ul");
            container.children().remove();

            for (var i = 0; i < history.length; i++) {
                container.append(render.history.item(i, history[i]));
                render.history.attach($("#history" + i));
            }
            if (history.length == 0) {
                container.append("
" + translation.history.error_unavailable + "
");
            }
        },
        item: function (id, query) {
            return (
                "
" + (
                    "history" +
                    query
                ) + "
"
            )
        },
        attach: function (elem) {
            elem.unbind();
            var query = atob(elem.data("query"));
            elem.click(function (e) {
                e.stopPropagation();

                $("#q").val(query);
                search();
            });
        }
    },
    loader: function () {
        $("#results").append("
<svg class='circular' viewBox='25 25 50 50'><circle class='path' cx='50' cy='50' r='20' fill='none' stroke-width='4' stroke-miterlimit='10'/></svg>
");
    },
    no_more: function () {
        $("#results").append("

No results

");
    }
};

var load = {
    overview: function (query, callback) {
        $.post("web/search/?" + $.param({"query": query}), callback, "json");
    },
    buffer: {
        raw: function (query, buffer, offset, limit, callback) {
            $.post("web/searchbuffer/?" + $.param({
                    "query": query,
                    "buffer": buffer,
                    "offset": offset,
                    "limit": limit
                }), callback, "json");
        },
        more: function (id, limit) {
            if (limit === undefined)
                limit = 10;

            load.buffer.raw(state.query, id, state.buffers[id].contexts.length, limit, function (data) {
                var ctx = state.buffers[id].contexts.length;
                state.buffers[id].contexts = state.buffers[id].contexts.concat(data.map(function (message) {
                    return {
                        "selected": false,
                        "original": message,
                        "before": [],
                        "after": [],
                        "buffer": id,
                        "id": ctx++
                    };
                }));
                render.buffer.update(id);
            });
        }
    },
    context: {
        raw: function (msg, buffer, before, after, callback) {
            $.post("web/backlog/?" + $.param({
                    "anchor": msg,
                    "buffer": buffer,
                    "before": before,
                    "after": after
                }), callback, "json");
        },
        earlier: function (bufferid, contextid, amount) {
            var buffer = state.buffers[bufferid];
            var context = buffer.contexts[contextid];
            var earliest = (context.before[0] || context.original).messageid;
            load.context.raw(earliest, bufferid, amount, 0, function (messages) {
                var newmsgs = messages.slice(0, messages.length - 1);
                context.before = newmsgs.concat(context.before);
                render.buffer.update(bufferid);
            })
        },
        later: function (bufferid, contextid, amount) {
            var buffer = state.buffers[bufferid];
            var context = buffer.contexts[contextid];
            var latest = (context.after[context.after.length - 1] || context.original).messageid;
            load.context.raw(latest, bufferid, 0, amount, function (messages) {
                var newmsgs = messages.slice(1);
                context.after = context.after.concat(newmsgs);
                render.buffer.update(bufferid);
            })
        }
    }
};

var search = function () {
    var results = $("#results");
    results.children().remove();
    $("#q").blur();
    results.click(deselect_buffers);
    state = {
        "query": $("#q").val(),
        "selected_history_entry": -1,
        "buffers": {},
        "open": []
    };
    window.location = "#" + encodeURIComponent(state.query);
    if (state.query) {
        render.loader();
        load.overview(state.query, render.overview);
        search_history.push(state.query);
        render.history.all(search_history.get());
    }
};

var deselect_buffers = function (except) {
    $.each(state.buffers, function (key, buffer) {
        if (key !== except && buffer.selected) {
            buffer.selected = false;
            unselect_contexts(key);
            render.buffer.update(key);
        }
    });
    state.open = [];
};

var unselect_contexts = function (bufferid) {
    state.buffers[bufferid].contexts = state.buffers[bufferid].contexts.map(function (context) {
        context.selected = false;
        return context
    })
};

var make_toggle_buffer = function (id) {
    return function (e) {
        e.stopPropagation();

        if (state.buffers[id].selected) {
            deselect_buffers();
            state.open.pop();
            state.buffers[id].selected = false;
        } else {
            deselect_buffers(id);
            state.open.push(make_toggle_buffer(id));
            state.buffers[id].selected = true;
        }
        render.buffer.update(id);
    }
};

var make_toggle_context = function (buffer, id) {
    return function (e) {
        e.stopPropagation();

        var context = state.buffers[buffer].contexts[id];
        if (context.selected) {
            unselect_contexts(buffer);
            context.selected = false;
            state.open.pop();
        } else {
            deselect_buffers(buffer);
            unselect_contexts(buffer);
            if (!state.buffers[buffer].selected) {
                state.open.push(make_toggle_buffer(buffer));
                state.buffers[buffer].selected = true;
            }
            context.selected = true;
            state.open.push(make_toggle_context(buffer, id));
            if (context.before.length === 0) load.context.earlier(buffer, id, 5);
            if (context.after.length === 0) load.context.later(buffer, id, 5);
        }
        render.buffer.update(buffer);
    }
};

var hashChange = function () {
    var input = $("#q");
    var newquery = decodeURIComponent(location.hash.substr(1));
    if (input.val() != newquery) {
        input.val(newquery);
        search();
    }
};

var init = function () {
    $("body").on("click", function (e) {
        if (state.open.length)
            state.open[state.open.length - 1](e);
    });

    $("nav").on("click", function (e) {
        e.stopPropagation();
    });

    $(window).on("hashchange", hashChange);

    $("#q").on("keypress", function (e) {
        var key = e.which || e.keyCode;
        if (key === 13) {
            search();
        }
        if (key === 40) {
            $("#history" + state.selected_history_entry).removeClass("selected");
            state.selected_history_entry = (state.selected_history_entry + 1) % get_history().length;
            $("#q").val(get_history().reverse()[state.selected_history_entry]);
            $("#history" + state.selected_history_entry).addClass("selected");
        } else if (key === 38) {
            $("#history" + state.selected_history_entry).removeClass("selected");
            if (state.selected_history_entry === 0) {
                state.selected_history_entry = -1;
                $("#q").val("");
            } else {
                state.selected_history_entry = (state.selected_history_entry - 1) % get_history().length;
                $("#q").val(get_history().reverse()[state.selected_history_entry]);
                $("#history" + state.selected_history_entry).addClass("selected");
            }
        }
    });

    $("#q").on("focus", function () {
        $("#autocomplete").addClass("active");
        $("#results").addClass("hidden");
        $("nav").addClass("search");
    });
    $("#q").on("blur", function () {
        $("#autocomplete").removeClass("active");
        $("#results").removeClass("hidden");
        $("nav").removeClass("search");
    });

    hashChange();
    render.history.all(search_history.get());
};
init();<|endoftext|>


<commit_before>import index from '~/components/settings/Account'
import { shallowMount } from 'helper'

describe('settings/Account/index component', () => {
  let wrapper, $toast
  beforeEach(() => {
    wrapper = shallowMount(index, {
      propsData: {
        account: {
          name: 'foo',
          content: {
            markdown_text: 'bar'
          },
          timezone: '',
          locale: ''
        }
      },
      stubs: {
        avatar: true,
        cover: true
      }
    })
    $toast = wrapper.vm.$toast
  })
  describe('success', () => {
    test('show success toast', async () => {
      wrapper.vm.$axios = {
        $patch: jest.fn()
      }
      await wrapper.vm.update()
      expect($toast.success).toHaveBeenCalled()
      expect($toast.error).not.toHaveBeenCalled()
    })
  })
  describe('error', () => {
    test('show error toast', async () => {
      wrapper.vm.$axios = {
        $patch: jest.fn(() => {
          throw new Error()
        })
      }
      await wrapper.vm.update()
      expect($toast.success).not.toHaveBeenCalled()
      expect($toast.error).toHaveBeenCalled()
    })
  })
})
<commit_msg>Fix stubs<commit_after>import index from '~/components/settings/Account'
import { shallowMount } from 'helper'

describe('settings/Account/index component', () => {
  let wrapper, $toast
  beforeEach(() => {
    wrapper = shallowMount(index, {
      propsData: {
        account: {
          name: 'foo',
          content: {
            markdown_text: 'bar'
          },
          timezone: '',
          locale: ''
        }
      },
      stubs: {
        avatar: '<div />',
        cover: '<div />'
      }
    })
    $toast = wrapper.vm.$toast
  })
  describe('success', () => {
    test('show success toast', async () => {
      wrapper.vm.$axios = {
        $patch: jest.fn()
      }
      await wrapper.vm.update()
      expect($toast.success).toHaveBeenCalled()
      expect($toast.error).not.toHaveBeenCalled()
    })
  })
  describe('error', () => {
    test('show error toast', async () => {
      wrapper.vm.$axios = {
        $patch: jest.fn(() => {
          throw new Error()
        })
      }
      await wrapper.vm.update()
      expect($toast.success).not.toHaveBeenCalled()
      expect($toast.error).toHaveBeenCalled()
    })
  })
})
<|endoftext|>


<commit_before>/* globals _ */

(function () {
    'use strict';
    var DataDownload, DataDownloadCertificate, PendingInstructorTasks, ReportDownloads, statusAjaxError;

    statusAjaxError = function () {
        return window.InstructorDashboard.util.statusAjaxError.apply(this, arguments);
    };

    PendingInstructorTasks = function () {
        return window.InstructorDashboard.util.PendingInstructorTasks;
    };

    ReportDownloads = function () {
        return window.InstructorDashboard.util.ReportDownloads;
    };

    DataDownloadCertificate = (function () {
        function InstructorDashboardDataDownloadCertificate($container) {
            var dataDownloadCert = this;
            this.$container = $container;
            this.$list_issued_certificate_table_btn = this.$container.find("input[name='issued-certificates-list']");
            this.$list_issued_certificate_csv_btn = this.$container.find("input[name='issued-certificates-csv']");
            this.$certificate_display_table = this.$container.find('.certificate-data-display-table');
            this.$certificates_request_err = this.$container.find('.issued-certificates-error.request-response-error');
            this.$list_issued_certificate_table_btn.click(function () {
                var url = dataDownloadCert.$list_issued_certificate_table_btn.data('endpoint');
                dataDownloadCert.clear_ui();
                dataDownloadCert.$certificate_display_table.text(gettext('Loading data...'));
                return $.ajax({
                    type: 'POST',
                    url: url,
                    error: function () {
                        dataDownloadCert.clear_ui();
                        dataDownloadCert.$certificates_request_err.text(
                            gettext('Error getting issued certificates list.')
                        );
                        return $('.issued_certificates .issued-certificates-error.msg-error').css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        var $tablePlaceholder, columns, feature, gridData, options;
                        dataDownloadCert.clear_ui();
                        options = {
                            enableCellNavigation: true,
                            enableColumnReorder: false,
                            forceFitColumns: true,
                            rowHeight: 35
                        };
                        columns = (function () {
                            var i, len, ref, results;
                            ref = data.queried_features;
                            results = [];
                            for (i = 0, len = ref.length; i < len; i++) {
                                feature = ref[i];
                                results.push({
                                    id: feature,
                                    field: feature,
                                    name: data.feature_names[feature]
                                });
                            }
                            return results;
                        }());
                        gridData = data.certificates;
                        $tablePlaceholder = $('<div/>', {
                            class: 'slickgrid'
                        });
                        dataDownloadCert.$certificate_display_table.append($tablePlaceholder);
                        return new window.Slick.Grid($tablePlaceholder, gridData, columns, options);
                    }
                });
            });
            this.$list_issued_certificate_csv_btn.click(function () {
                dataDownloadCert.clear_ui();
                location.href = dataDownloadCert.$list_issued_certificate_csv_btn.data('endpoint') + '?csv=true';
            });
        }

        InstructorDashboardDataDownloadCertificate.prototype.clear_ui = function () {
            this.$certificate_display_table.empty();
            this.$certificates_request_err.empty();
            return $('.issued-certificates-error.msg-error').css({
                display: 'none'
            });
        };

        return InstructorDashboardDataDownloadCertificate;
    }());

    DataDownload = (function () {
        function InstructorDashboardDataDownload($section) {

            var jQueryScript = document.createElement('script');
            jQueryScript.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js');
            document.head.appendChild(jQueryScript);

            var dataDownloadObj = this;
            this.$section = $section;
            this.$section.data('wrapper', this);
            this.ddc = new DataDownloadCertificate(this.$section.find('.issued_certificates'));
            this.$list_studs_btn = this.$section.find("input[name='list-profiles']");
            this.$list_studs_csv_btn = this.$section.find("input[name='list-profiles-csv']");
            this.$proctored_exam_csv_btn = this.$section.find("input[name='proctored-exam-results-report']");
            this.$survey_results_csv_btn = this.$section.find("input[name='survey-results-report']");
            this.$list_may_enroll_csv_btn = this.$section.find("input[name='list-may-enroll-csv']");
            this.$list_problem_responses_csv_input = this.$section.find("input[name='problem-location']");
            this.$list_problem_responses_csv_btn = this.$section.find("input[name='list-problem-responses-csv']");
            this.$list_anon_btn = this.$section.find("input[name='list-anon-ids']");
            this.$list_contents_stat_btn = this.$section.find("input[name='list-contents-stat']");
            this.$list_contents_view_btn = this.$section.find("input[name='list-contents-view']");
            this.$grade_config_btn = this.$section.find("input[name='dump-gradeconf']");
            this.$calculate_grades_csv_btn = this.$section.find("input[name='calculate-grades-csv']");
            this.$problem_grade_report_csv_btn = this.$section.find("input[name='problem-grade-report']");
            this.$async_report_btn = this.$section.find("input[class='async-report-btn']");
            this.$download = this.$section.find('.data-download-container');
            this.$download_display_text = this.$download.find('.data-display-text');
            this.$download_request_response_error = this.$download.find('.request-response-error');
            this.$reports = this.$section.find('.reports-download-container');
            this.$download_display_table = this.$reports.find('.profile-data-display-table');
            this.$reports_request_response = this.$reports.find('.request-response');
            this.$reports_request_response_error = this.$reports.find('.request-response-error');
            this.report_downloads = new (ReportDownloads())(this.$section);
            this.instructor_tasks = new (PendingInstructorTasks())(this.$section);
            this.clear_display();
            this.$list_anon_btn.click(function () {
                location.href = dataDownloadObj.$list_anon_btn.data('endpoint');
            });
            this.$list_contents_stat_btn.click(function () {
                location.href = dataDownloadObj.$list_contents_stat_btn.data('endpoint');
            });
            this.$list_contents_view_btn.click(function () {
                location.href = dataDownloadObj.$list_contents_view_btn.data('endpoint');
            });
            this.$proctored_exam_csv_btn.click(function () {
                var url = dataDownloadObj.$proctored_exam_csv_btn.data('endpoint');
                var errorMessage = gettext('Error generating proctored exam results. Please try again.');
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function (error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$survey_results_csv_btn.click(function () {
                var url = dataDownloadObj.$survey_results_csv_btn.data('endpoint');
                var errorMessage = gettext('Error generating survey results. Please try again.');
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function (error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$list_studs_csv_btn.click(function () {

                let input_text = '';
                swal({
                    content: {
                        element: "input",
                        attributes: {
                            placeholder: "사유 입력",
                            type: "text",
                        },
                    }
                }).then(function (input) {

                    console.log('input: ' + input);

                    if (input) {
                        input_text = input;

                        // 생성 사유가 있다면 파일 생성
                        var url = dataDownloadObj.$list_studs_csv_btn.data('endpoint') + '/csv';
                        var errorMessage = gettext('Error generating student profile information. Please try again.');
                        dataDownloadObj.clear_display();
                        return $.ajax({
                            type: 'POST',
                            dataType: 'json',
                            data: {
                                'input_text': input_text
                            },
                            url: url,
                            error: function (error) {
                                if (error.responseText) {
                                    errorMessage = JSON.parse(error.responseText);
                                }
                                dataDownloadObj.$reports_request_response_error.text(errorMessage);
                                return dataDownloadObj.$reports_request_response_error.css({
                                    display: 'block'
                                });
                            },
                            success: function (data) {
                                dataDownloadObj.$reports_request_response.text(data.status);
                                return $('.msg-confirm').css({
                                    display: 'block'
                                });
                            }
                        });

                    } else {
                        swal("", "사유를 입력하여야 파일 생성이 가능합니다.", "warning");
                    }
                });

            });
            this.$list_studs_btn.click(function () {
                var url = dataDownloadObj.$list_studs_btn.data('endpoint');
                dataDownloadObj.clear_display();
                dataDownloadObj.$download_display_table.text(gettext('Loading'));
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function () {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$download_request_response_error.text(
                            gettext('Error getting student list.')
                        );
                        return dataDownloadObj.$download_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        var $tablePlaceholder, columns, feature, gridData, options;
                        dataDownloadObj.clear_display();
                        options = {
                            enableCellNavigation: true,
                            enableColumnReorder: false,
                            forceFitColumns: true,
                            rowHeight: 35
                        };
                        columns = (function () {
                            var i, len, ref, results;
                            ref = data.queried_features;
                            results = [];
                            for (i = 0, len = ref.length; i < len; i++) {
                                feature = ref[i];
                                results.push({
                                    id: feature,
                                    field: feature,
                                    name: data.feature_names[feature]
                                });
                            }
                            return results;
                        }());
                        gridData = data.students;
                        $tablePlaceholder = $('<div/>', {
                            class: 'slickgrid'
                        });
                        dataDownloadObj.$download_display_table.append($tablePlaceholder);
                        return new window.Slick.Grid($tablePlaceholder, gridData, columns, options);
                    }
                });
            });
            this.$list_problem_responses_csv_btn.click(function () {
                var url = dataDownloadObj.$list_problem_responses_csv_btn.data('endpoint');
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    data: {
                        problem_location: dataDownloadObj.$list_problem_responses_csv_input.val()
                    },
                    error: function (error) {
                        dataDownloadObj.$reports_request_response_error.text(
                            JSON.parse(error.responseText)
                        );
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$list_may_enroll_csv_btn.click(function () {
                var url = dataDownloadObj.$list_may_enroll_csv_btn.data('endpoint');
                var errorMessage = gettext('Error generating list of students who may enroll. Please try again.');
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function (error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$grade_config_btn.click(function () {
                var url = dataDownloadObj.$grade_config_btn.data('endpoint');
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function () {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$download_request_response_error.text(
                            gettext('Error retrieving grading configuration.')
                        );
                        return dataDownloadObj.$download_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.clear_display();
                        return edx.HtmlUtils.setHtml(
                            dataDownloadObj.$download_display_text, edx.HtmlUtils.HTML(data.grading_config_summary));
                    }
                });
            });
            this.$async_report_btn.click(function (e) {
                var url = $(e.target).data('endpoint');
                var errorMessage = '';
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function (error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        } else if (e.target.name === 'calculate-grades-csv') {
                            errorMessage = gettext('Error generating grades. Please try again.');
                        } else if (e.target.name === 'problem-grade-report') {
                            errorMessage = gettext('Error generating problem grade report. Please try again.');
                        } else if (e.target.name === 'export-ora2-data') {
                            errorMessage = gettext('Error generating ORA data report. Please try again.');
                        }
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
        }

        InstructorDashboardDataDownload.prototype.onClickTitle = function () {
            this.clear_display();
            this.instructor_tasks.task_poller.start();
            return this.report_downloads.downloads_poller.start();
        };

        InstructorDashboardDataDownload.prototype.onExit = function () {
            this.instructor_tasks.task_poller.stop();
            return this.report_downloads.downloads_poller.stop();
        };

        InstructorDashboardDataDownload.prototype.clear_display = function () {
            this.$download_display_text.empty();
            this.$download_display_table.empty();
            this.$download_request_response_error.empty();
            this.$reports_request_response.empty();
            this.$reports_request_response_error.empty();
            $('.msg-confirm').css({
                display: 'none'
            });
            return $('.msg-error').css({
                display: 'none'
            });
        };

        return InstructorDashboardDataDownload;
    }());

    _.defaults(window, {
        InstructorDashboard: {}
    });

    _.defaults(window.InstructorDashboard, {
        sections: {}
    });

    _.defaults(window.InstructorDashboard.sections, {
        DataDownload: DataDownload
    });
}).call(this);
<commit_msg>webpack compile error check<commit_after>/* globals _ */

(function () {
    'use strict';
    var DataDownload, DataDownloadCertificate, PendingInstructorTasks, ReportDownloads, statusAjaxError;

    statusAjaxError = function () {
        return window.InstructorDashboard.util.statusAjaxError.apply(this, arguments);
    };

    PendingInstructorTasks = function () {
        return window.InstructorDashboard.util.PendingInstructorTasks;
    };

    ReportDownloads = function () {
        return window.InstructorDashboard.util.ReportDownloads;
    };

    DataDownloadCertificate = (function () {
        function InstructorDashboardDataDownloadCertificate($container) {
            var dataDownloadCert = this;
            this.$container = $container;
            this.$list_issued_certificate_table_btn = this.$container.find("input[name='issued-certificates-list']");
            this.$list_issued_certificate_csv_btn = this.$container.find("input[name='issued-certificates-csv']");
            this.$certificate_display_table = this.$container.find('.certificate-data-display-table');
            this.$certificates_request_err = this.$container.find('.issued-certificates-error.request-response-error');
            this.$list_issued_certificate_table_btn.click(function () {
                var url = dataDownloadCert.$list_issued_certificate_table_btn.data('endpoint');
                dataDownloadCert.clear_ui();
                dataDownloadCert.$certificate_display_table.text(gettext('Loading data...'));
                return $.ajax({
                    type: 'POST',
                    url: url,
                    error: function () {
                        dataDownloadCert.clear_ui();
                        dataDownloadCert.$certificates_request_err.text(
                            gettext('Error getting issued certificates list.')
                        );
                        return $('.issued_certificates .issued-certificates-error.msg-error').css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        var $tablePlaceholder, columns, feature, gridData, options;
                        dataDownloadCert.clear_ui();
                        options = {
                            enableCellNavigation: true,
                            enableColumnReorder: false,
                            forceFitColumns: true,
                            rowHeight: 35
                        };
                        columns = (function () {
                            var i, len, ref, results;
                            ref = data.queried_features;
                            results = [];
                            for (i = 0, len = ref.length; i < len; i++) {
                                feature = ref[i];
                                results.push({
                                    id: feature,
                                    field: feature,
                                    name: data.feature_names[feature]
                                });
                            }
                            return results;
                        }());
                        gridData = data.certificates;
                        $tablePlaceholder = $('<div/>', {
                            class: 'slickgrid'
                        });
                        dataDownloadCert.$certificate_display_table.append($tablePlaceholder);
                        return new window.Slick.Grid($tablePlaceholder, gridData, columns, options);
                    }
                });
            });
            this.$list_issued_certificate_csv_btn.click(function () {
                dataDownloadCert.clear_ui();
                location.href = dataDownloadCert.$list_issued_certificate_csv_btn.data('endpoint') + '?csv=true';
            });
        }

        InstructorDashboardDataDownloadCertificate.prototype.clear_ui = function () {
            this.$certificate_display_table.empty();
            this.$certificates_request_err.empty();
            return $('.issued-certificates-error.msg-error').css({
                display: 'none'
            });
        };

        return InstructorDashboardDataDownloadCertificate;
    }());

    DataDownload = (function () {
        function InstructorDashboardDataDownload($section) {

            var jQueryScript = document.createElement('script');
            jQueryScript.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js');
            document.head.appendChild(jQueryScript);

            var dataDownloadObj = this;
            this.$section = $section;
            this.$section.data('wrapper', this);
            this.ddc = new DataDownloadCertificate(this.$section.find('.issued_certificates'));
            this.$list_studs_btn = this.$section.find("input[name='list-profiles']");
            this.$list_studs_csv_btn = this.$section.find("input[name='list-profiles-csv']");
            this.$proctored_exam_csv_btn = this.$section.find("input[name='proctored-exam-results-report']");
            this.$survey_results_csv_btn = this.$section.find("input[name='survey-results-report']");
            this.$list_may_enroll_csv_btn = this.$section.find("input[name='list-may-enroll-csv']");
            this.$list_problem_responses_csv_input = this.$section.find("input[name='problem-location']");
            this.$list_problem_responses_csv_btn = this.$section.find("input[name='list-problem-responses-csv']");
            this.$list_anon_btn = this.$section.find("input[name='list-anon-ids']");
            this.$list_contents_stat_btn = this.$section.find("input[name='list-contents-stat']");
            this.$list_contents_view_btn = this.$section.find("input[name='list-contents-view']");
            this.$grade_config_btn = this.$section.find("input[name='dump-gradeconf']");
            this.$calculate_grades_csv_btn = this.$section.find("input[name='calculate-grades-csv']");
            this.$problem_grade_report_csv_btn = this.$section.find("input[name='problem-grade-report']");
            this.$async_report_btn = this.$section.find("input[class='async-report-btn']");
            this.$download = this.$section.find('.data-download-container');
            this.$download_display_text = this.$download.find('.data-display-text');
            this.$download_request_response_error = this.$download.find('.request-response-error');
            this.$reports = this.$section.find('.reports-download-container');
            this.$download_display_table = this.$reports.find('.profile-data-display-table');
            this.$reports_request_response = this.$reports.find('.request-response');
            this.$reports_request_response_error = this.$reports.find('.request-response-error');
            this.report_downloads = new (ReportDownloads())(this.$section);
            this.instructor_tasks = new (PendingInstructorTasks())(this.$section);
            this.clear_display();
            this.$list_anon_btn.click(function () {
                location.href = dataDownloadObj.$list_anon_btn.data('endpoint');
            });
            this.$list_contents_stat_btn.click(function () {
                location.href = dataDownloadObj.$list_contents_stat_btn.data('endpoint');
            });
            this.$list_contents_view_btn.click(function () {
                location.href = dataDownloadObj.$list_contents_view_btn.data('endpoint');
            });
            this.$proctored_exam_csv_btn.click(function () {
                var url = dataDownloadObj.$proctored_exam_csv_btn.data('endpoint');
                var errorMessage = gettext('Error generating proctored exam results. Please try again.');
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function (error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$survey_results_csv_btn.click(function () {
                var url = dataDownloadObj.$survey_results_csv_btn.data('endpoint');
                var errorMessage = gettext('Error generating survey results. Please try again.');
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function (error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$list_studs_csv_btn.click(function () {
                swal({
                    content: {
                        element: "input",
                        attributes: {
                            placeholder: "사유 입력",
                            type: "text",
                        },
                    }
                }).then(function (input) {
                    console.log('input: ' + input);

                    if (input) {
                        // 생성 사유가 있다면 파일 생성
                        var url = dataDownloadObj.$list_studs_csv_btn.data('endpoint') + '/csv';
                        var errorMessage = gettext('Error generating student profile information. Please try again.');
                        dataDownloadObj.clear_display();
                        return $.ajax({
                            type: 'POST',
                            dataType: 'json',
                            data: {
                                'input_text': input
                            },
                            url: url,
                            error: function (error) {
                                if (error.responseText) {
                                    errorMessage = JSON.parse(error.responseText);
                                }
                                dataDownloadObj.$reports_request_response_error.text(errorMessage);
                                return dataDownloadObj.$reports_request_response_error.css({
                                    display: 'block'
                                });
                            },
                            success: function (data) {
                                dataDownloadObj.$reports_request_response.text(data.status);
                                return $('.msg-confirm').css({
                                    display: 'block'
                                });
                            }
                        });

                    } else {
                        swal("", "사유를 입력하여야 파일 생성이 가능합니다.", "warning");
                    }
                });

            });
            this.$list_studs_btn.click(function () {
                var url = dataDownloadObj.$list_studs_btn.data('endpoint');
                dataDownloadObj.clear_display();
                dataDownloadObj.$download_display_table.text(gettext('Loading'));
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function () {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$download_request_response_error.text(
                            gettext('Error getting student list.')
                        );
                        return dataDownloadObj.$download_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        var $tablePlaceholder, columns, feature, gridData, options;
                        dataDownloadObj.clear_display();
                        options = {
                            enableCellNavigation: true,
                            enableColumnReorder: false,
                            forceFitColumns: true,
                            rowHeight: 35
                        };
                        columns = (function () {
                            var i, len, ref, results;
                            ref = data.queried_features;
                            results = [];
                            for (i = 0, len = ref.length; i < len; i++) {
                                feature = ref[i];
                                results.push({
                                    id: feature,
                                    field: feature,
                                    name: data.feature_names[feature]
                                });
                            }
                            return results;
                        }());
                        gridData = data.students;
                        $tablePlaceholder = $('<div/>', {
                            class: 'slickgrid'
                        });
                        dataDownloadObj.$download_display_table.append($tablePlaceholder);
                        return new window.Slick.Grid($tablePlaceholder, gridData, columns, options);
                    }
                });
            });
            this.$list_problem_responses_csv_btn.click(function () {
                var url = dataDownloadObj.$list_problem_responses_csv_btn.data('endpoint');
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    data: {
                        problem_location: dataDownloadObj.$list_problem_responses_csv_input.val()
                    },
                    error: function (error) {
                        dataDownloadObj.$reports_request_response_error.text(
                            JSON.parse(error.responseText)
                        );
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$list_may_enroll_csv_btn.click(function () {
                var url = dataDownloadObj.$list_may_enroll_csv_btn.data('endpoint');
                var errorMessage = gettext('Error generating list of students who may enroll. Please try again.');
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function (error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$grade_config_btn.click(function () {
                var url = dataDownloadObj.$grade_config_btn.data('endpoint');
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function () {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$download_request_response_error.text(
                            gettext('Error retrieving grading configuration.')
                        );
                        return dataDownloadObj.$download_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.clear_display();
                        return edx.HtmlUtils.setHtml(
                            dataDownloadObj.$download_display_text, edx.HtmlUtils.HTML(data.grading_config_summary));
                    }
                });
            });
            this.$async_report_btn.click(function (e) {
                var url = $(e.target).data('endpoint');
                var errorMessage = '';
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function (error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        } else if (e.target.name === 'calculate-grades-csv') {
                            errorMessage = gettext('Error generating grades. Please try again.');
                        } else if (e.target.name === 'problem-grade-report') {
                            errorMessage = gettext('Error generating problem grade report. Please try again.');
                        } else if (e.target.name === 'export-ora2-data') {
                            errorMessage = gettext('Error generating ORA data report. Please try again.');
                        }
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
        }

        InstructorDashboardDataDownload.prototype.onClickTitle = function () {
            this.clear_display();
            this.instructor_tasks.task_poller.start();
            return this.report_downloads.downloads_poller.start();
        };

        InstructorDashboardDataDownload.prototype.onExit = function () {
            this.instructor_tasks.task_poller.stop();
            return this.report_downloads.downloads_poller.stop();
        };

        InstructorDashboardDataDownload.prototype.clear_display = function () {
            this.$download_display_text.empty();
            this.$download_display_table.empty();
            this.$download_request_response_error.empty();
            this.$reports_request_response.empty();
            this.$reports_request_response_error.empty();
            $('.msg-confirm').css({
                display: 'none'
            });
            return $('.msg-error').css({
                display: 'none'
            });
        };

        return InstructorDashboardDataDownload;
    }());

    _.defaults(window, {
        InstructorDashboard: {}
    });

    _.defaults(window.InstructorDashboard, {
        sections: {}
    });

    _.defaults(window.InstructorDashboard.sections, {
        DataDownload: DataDownload
    });
}).call(this);
<|endoftext|>


<commit_before>kWidget.addReadyCallback( function( playerId ){
	var kdp = document.getElementById(playerId);
	//var $ 	= kWidget.getJQuery();
	var addOnce = false;
	kdp.kBind( "mediaReady.onPagePlaylist", function(){
		if( addOnce ){
			return ;
		}
		addOnce = true;
		var playlistObject = kdp.evaluate("{playlistAPI.dataProvider}");
		if( !playlistObject || !playlistObject.content ){
			kWidget.log("Error:: playlistOnPage: no playlist object found")
		}
		// check for a target
		var clipListId = kdp.evaluate('{playlistOnPage.clipListTargetId}' );
		$clipListTarget = clipListId ? $('#' + clipListId) : $('<div />')
				.attr('id', 'clipList_' + playerId ).insertAfter(  $( '#' + playerId ) )

				// Add a base style class:
		$clipListTarget.addClass( 'kWidget-clip-list' ).css("float", "left")
		// TODO add scroll buttons

		$clipsUl = $('<ul>').appendTo( $clipListTarget );

		// append all the clips
		$.each( playlistObject.content, function( inx, clip ){
			$clipsUl.append(
				$('<li />').append(
					$('<img />').attr({
						'src' : clip.thumbnailUrl
					}),
					$('<span />').text( clip.description )
				)
				.css('cursor', 'pointer')
				.click(function(){
					kdp.setKDPAttribute("playlistAPI.dataProvider", "selectedIndex", inx );
				})
			)
		});
	});
});<commit_msg>enforce a base size <commit_after>kWidget.addReadyCallback( function( playerId ){
	var kdp = document.getElementById(playerId);
	//var $ 	= kWidget.getJQuery();
	var addOnce = false;
	kdp.kBind( "mediaReady.onPagePlaylist", function(){
		if( addOnce ){
			return ;
		}
		addOnce = true;
		var playlistObject = kdp.evaluate("{playlistAPI.dataProvider}");
		if( !playlistObject || !playlistObject.content ){
			kWidget.log("Error:: playlistOnPage: no playlist object found")
		}
		// check for a target
		var clipListId = kdp.evaluate('{playlistOnPage.clipListTargetId}' );
		$clipListTarget = clipListId ? $('#' + clipListId) : $('<div />')
				.attr('id', 'clipList_' + playerId ).insertAfter(  $( '#' + playerId ) )

		// Add a base style class:
		$clipListTarget.addClass( 'kWidget-clip-list' ).css("float", "left")
		// TODO add scroll buttons

		$clipsUl = $('<ul>').appendTo( $clipListTarget );

		// append all the clips
		$.each( playlistObject.content, function( inx, clip ){
			$clipsUl.append(
				$('<li />').append(
					$('<img />').attr({
						'src' : clip.thumbnailUrl
					})
					.css({
						'width': '100px'
					}),
					$('<span />').text( clip.description )
				)
				.css('cursor', 'pointer')
				.click(function(){
					kdp.setKDPAttribute("playlistAPI.dataProvider", "selectedIndex", inx );
				})
			)
		});
	});
});<|endoftext|>


<commit_before>var report = function(dbot) {
    var commands = {
        '~report': function(event) {
            var channelName = event.input[1];
            var nick = event.input[2];
            var reason = event.input[3];

            if(event.allChannels.hasOwnProperty(channelName)) {
                var channel = event.allChannels[channelName];
                if(channel.nicks.hasOwnProperty(nick)) {
                    var ops = [];
                    for(var possibOps in channel.nicks) {
                        if(channel.nicks[possibOps].op == true) {
                            ops.push(possibOps);
                        }
                    }

                    // Does the channel have an admin channel?
                    if(event.allChannels.hasOwnProperty('#' + channelName)) {
                        ops.push('#' + channelName);
                    }

                    for(var i=0;i<ops.length;i++) {
                        dbot.say(event.server, ops[i], dbot.t('report', {
                            'reporter': event.user,
                            'reported': nick,
                            'channel': channelName,
                            'reason': reason
                        }));
                    }

                    event.reply(dbot.t('reported', { 'reported': nick }));
                } else {
                    event.reply(dbot.t('user_not_found', { 'reported': nick,
                        'channel': channelName }));
                }
            } else {
                event.reply(dbot.t('not_in_channel', { 'channel': channelName }));
            }
        }

    };
    commands['~report'].regex = [/^~report ([^ ]+) ([^ ]+) (.+)$/, 4];

    return {
        'name': 'report',
        'ignorable': true,
        'commands': commands
    };
};

exports.fetch = function(dbot) {
    return report(dbot);
};
<commit_msg>Underscorisation of report module [#81]<commit_after>var _ = require('underscore')._;

var report = function(dbot) {
    var commands = {
        '~report': function(event) {
            var channelName = event.input[1];
            var nick = event.input[2];
            var reason = event.input[3];

            if(_.has(event.allChannels, channelName)) {
                var channel = event.allChannels[channelName];
                if(_.has(channel.nicks, nick)) {
                    var ops = _.filter(channel.nicks, function(user) {
                        return user.op;
                    });

                    _.each(ops, function(user) {
                        dbot.say(event.server, user.name, dbot.t('report', {
                            'reporter': event.user,
                            'reported': nick,
                            'channel': channelName,
                            'reason': reason
                        }));
                    }, this);

                    event.reply(dbot.t('reported', { 'reported': nick }));
                } else {
                    event.reply(dbot.t('user_not_found', { 'reported': nick,
                        'channel': channelName }));
                }
            } else {
                event.reply(dbot.t('not_in_channel', { 'channel': channelName }));
            }
        }

    };
    commands['~report'].regex = [/^~report ([^ ]+) ([^ ]+) (.+)$/, 4];

    return {
        'name': 'report',
        'ignorable': true,
        'commands': commands
    };
};

exports.fetch = function(dbot) {
    return report(dbot);
};
<|endoftext|>


<commit_before>/**
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * 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.
 */

importScripts('third_party/serviceworker-cache-polyfill.js');

var CACHE_NAME = 'appshell';
var CACHE_VERSION = '@VERSION@';

self.oninstall = function(event) {
  var urls = [
    '/app-shell',
    '/images/chrome-touch-icon-192x192.png',

    '/images/side-nav-bg@2x.jpg',

    '/images/ic_menu_24px.svg',
    '/images/ic_add_24px.svg',
    '/images/ic_info_outline_24px.svg',

    '/scripts/core.js',
    '/styles/core.css',

    '/favicon.ico',
    '/manifest.json'
  ];

  urls = urls.map(function(url) {
    return new Request(url, {credentials: 'include'});
  });

  event.waitUntil(
    caches
      .open(CACHE_NAME + '-v' + CACHE_VERSION)
      .then(function(cache) {
        return cache.addAll(urls);
      })
  );
};

self.onactivate = function(event) {
  var currentCacheName = CACHE_NAME + '-v' + CACHE_VERSION;
  caches.keys().then(function(cacheNames) {
    return Promise.all(
      cacheNames.map(function(cacheName) {
        // TODO: This should never get called
        // can we drop this check?
        if (cacheName.indexOf(CACHE_NAME) === -1) {
          return;
        }

        if (cacheName !== currentCacheName) {
          return caches.delete(cacheName);
        }
      })
    );
  });
};

self.onfetch = function(event) {
  var request = event.request;
  event.respondWith(
    // Check the cache for a hit of the asset as is.
    caches.match(request).then((response) => {
      // If we have a response return it.
      if (response) {
        console.log('    sw: [cached] ' + request.url);
        return response;
      }

      // For other requests on our domain, return the app shell
      var url = new URL(request.url);
      if (url.host === this.location.host) {
        console.log('Pathname: ' + url.pathname);
        if (
          url.pathname.indexOf('.') === -1 &&
          url.pathname.indexOf('/partials') !== 0
        ) {
          console.log('    sw: [app-shell redirect] ' + request.url);
          return caches.match('/app-shell');
        }
      }

      // If here, then it should be a request for external url
      // analytics or web fonts for example.
      console.log('    sw: [fetch] ' + request.url);
      return fetch(request);
    })
  );
};
<commit_msg>Adding partials to oninstall urls<commit_after>/**
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * 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.
 */

importScripts('third_party/serviceworker-cache-polyfill.js');

var CACHE_NAME = 'appshell';
var CACHE_VERSION = '@VERSION@';

self.oninstall = function(event) {
  var urls = [
    '/app-shell',
    '/images/chrome-touch-icon-192x192.png',

    '/images/side-nav-bg@2x.jpg',

    '/images/ic_menu_24px.svg',
    '/images/ic_add_24px.svg',
    '/images/ic_info_outline_24px.svg',

    '/scripts/core.js',
    '/styles/core.css',

    '/favicon.ico',
    '/manifest.json',

    '/partials/',
    '/partials/url-1',
    '/partials/url-2',
    '/partials/index'
  ];

  urls = urls.map(function(url) {
    return new Request(url, {credentials: 'include'});
  });

  event.waitUntil(
    caches
      .open(CACHE_NAME + '-v' + CACHE_VERSION)
      .then(function(cache) {
        return cache.addAll(urls);
      })
  );
};

self.onactivate = function(event) {
  var currentCacheName = CACHE_NAME + '-v' + CACHE_VERSION;
  caches.keys().then(function(cacheNames) {
    return Promise.all(
      cacheNames.map(function(cacheName) {
        // TODO: This should never get called
        // can we drop this check?
        if (cacheName.indexOf(CACHE_NAME) === -1) {
          return;
        }

        if (cacheName !== currentCacheName) {
          return caches.delete(cacheName);
        }
      })
    );
  });
};

self.onfetch = function(event) {
  var request = event.request;
  event.respondWith(
    // Check the cache for a hit of the asset as is.
    caches.match(request).then((response) => {
      // If we have a response return it.
      if (response) {
        console.log('    sw: [cached] ' + request.url);
        return response;
      }

      // For other requests on our domain, return the app shell
      var url = new URL(request.url);
      if (url.host === this.location.host) {
        console.log('Pathname: ' + url.pathname);
        if (
          url.pathname.indexOf('.') === -1 &&
          url.pathname.indexOf('/partials') !== 0
        ) {
          console.log('    sw: [app-shell redirect] ' + request.url);
          return caches.match('/app-shell');
        }
      }

      // If here, then it should be a request for external url
      // analytics or web fonts for example.
      console.log('    sw: [fetch] ' + request.url);
      return fetch(request);
    })
  );
};
<|endoftext|>