<commit_before>var $body = $("#inner-body"),
    Type,
    PhoneView = false,
    Title = "纸异兽",
    supportHistory = !!(window.history.pushState && window.history.replaceState);

//alert(!!navigator.userAgent.match(/mobile/i));

$(function () {
    //load article list and cnblog list
    if (!$("#left-middle").html().trim()) {
        $.get("/", null, function (data) {
            var $data = $(data);

            $("#left-middle").replaceWith($data.find("#left-middle"));
            $("#right-middle").replaceWith($data.find("#right-middle"));
        }, "html");
    }
    init();
});

$("#aside").on({
    "mouseenter": function () {
        !PhoneView && $(this).removeClass("aside-close").addClass("aside-open");
        $("#aside .profile").scrollTop(0);
    },
    "mouseleave": function () {
        !PhoneView && $(this).removeClass("aside-open").addClass("aside-close");
    },
    "click": function(e){
        var $this = $(this);

        if(PhoneView) {
            if (e.target.className == "close") {//click close button
                $this.removeClass("aside-open").addClass("aside-close");
            }else if(!$this.hasClass("aside-open")){
                $this.removeClass("aside-close").addClass("aside-open");
                $("#aside .profile").scrollTop(0);
            }
        }
    }
});

$("#switch").on({
    "mouseenter": function(){
        !PhoneView && $(this).addClass("hover");
    },
    "mouseleave": function(){
        !PhoneView && $(this).removeClass("hover");
    },
    "click": function(){
        var $this = $(this);
        if(PhoneView){
            $body.toggleClass("right-middle");
            $("html,body").scrollTop(0);
        }else{
            //toggle hover class, if hover exists, so that this is first click after mouseenter
            //if hover not exist, so prove that this isn't.
            $this.toggleClass("hover");

            //if isn't first click, add animation to this event
            if($this.hasClass("hover")){
                setTimeout(function(){
                    $body.toggleClass("right-middle");
                    $this.removeClass("hover");
                },500);
            }else{
                $body.toggleClass("right-middle");
            }
        }
    }
});

$(window).resize(function () {
    PhoneView = $("body").width() < 900;
    doChanged();
});

$(".content").scroll(function(){
    if(!PhoneView) return;

    if($(this).scrollTop() >= 10){
        $("#aside").addClass("slideUp");
    }else{
        $("#aside").removeClass("slideUp");
    }
    fixWidthOfAside();
});

$(".contents,.profile").on("click", "a", function (e) {
    //for normal a link
    var action = $(this).attr("action"),
        title = Title;
    if (!action || !supportHistory) {
        return;
    }

    if (PhoneView && this.id == "readmore"){
        $("#aside").removeClass("aside-open").addClass("aside-close");
        e.stopPropagation();
    }

    e.preventDefault();
    var href = this.href;

    maskLoding.show();
    switch (Type = $(this).attr("action")) {
        case "article":
            $("#left-bottom").load(href + " #left-bottom>*", function () {
                $body.removeClass("left-top left-middle").addClass("left-bottom");

                if(PhoneView){
                    $("html,body").scrollTop(0);
                    playMedia();
                }else{
                    $(this).scrollTop(0);
                }

                doChanged();
                setTitle(title = $("h1.post-title").text());
                window.history.pushState({type: action, url: href}, title, href);
                maskLoding.hide();
                initDuoshuo();
            });
            break;
        case "tag":
            $("#left-top").load(href + " #left-top>*", function () {
                $body.removeClass("left-bottom left-middle").addClass("left-top");
                PhoneView ? $("html,body").scrollTop(0) : $(this).scrollTop(0);
                doChanged();
                setTitle(title = $("h1.page-title").text());
                window.history.pushState({type: action, url: href}, title, href);
                maskLoding.hide();
            });
            break;
        case "page":
            $("#left-middle").load(href + " #left-middle>*", function () {
                $body.removeClass("left-top left-bottom");
                PhoneView ? $("html,body").scrollTop(0) : $(this).scrollTop(0);
                doChanged();
                setTitle(title);
                window.history.pushState({type: action, url: href}, document.title, href);
                maskLoding.hide();
            });
            break;
        default :
            Type = "list";
            PhoneView && $("html,body").scrollTop(0);
    }
});

//zoom for picture
(function(){
    var $tag = $("原图"),
        img = document.createElement("img"),
        $img = $(img),
        $oriBox = $("

×

"),
        $close = $oriBox.children("#masker-close"),
        //store original image data for zoom smaller to recovery the location
        originalData = {
            ratio: 1,
            width: 0,
            height: 0,
            top: 0,
            left: 0,
            //for limit mousemove event
            isLock: true
        },
        url;

    $(".contents")
        .on("mouseenter",".post-content img",function(){
            var $this = $(this);

            url = this.src.replace(/-resize$/,"");
            $this.parent().css("position","relative");
            originalData.ratio = $this.width() / $this.height();

            $tag.css({
                "top": $this.position().top,
                "right": $this.parent().width() - $this.width() - $this.position().left
            });

            $this.after($tag);
        }).on("mouseleave",".post-content img",function(e){
            if(e.relatedTarget == $tag[0]){
                return;
            }
            $tag.remove();
        });

    $tag[0].onclick = function(){
        var $body = $("body"),
            width,
            height;

        //do it before get width because the scroll bar
        if(PhoneView){
            $body.css("overflow","hidden");
        }

        width = $body.width();
        height = $body.height();
        maskLoding.show();
        $oriBox.prepend($img);
        img.src = url;

        if(originalData.ratio >  width / height){
            originalData.width = width;
            originalData.height = width / originalData.ratio;
            originalData.top = (height - originalData.height)/2;
            originalData.left = 0;
        }else{
            originalData.width =  height * originalData.ratio;
            originalData.height = height;
            originalData.top = 0;
            originalData.left = (width - originalData.width)/2;
        }

        $img.css({
            height: originalData.height,
            width: originalData.width,
            top: originalData.top,
            left: originalData.left
        });

        //for sync showing image and masker
        //so we will get a better transition
        setTimeout(function(){
            $body.append($oriBox);
        },300);
    };

    //see "jquery remove() and Event" with bug tag in evernote
    img.onload = function(){
        $("#loading").fadeOut();
    };

    $close[0].onclick = function(){
        if(PhoneView){
            $("body").css("overflow","");
        }

        $oriBox.remove();
        maskLoding.hide();
    };

    img.onmousewheel = img.dommousescroll = debounce(mousewheel,20);
    img.addEventListener("DOMMouseScroll", img.onmousewheel);

    function mousewheel(e) {
        var temp;
        if (!$img[0].complete) return;
        if (e.detail ? e.detail < 0 : e.wheelDelta > 0) {
            $img.css({
                "width": function (index, value) {
                    return parseInt(value) * 1.1;
                }, "height": function (index, value) {
                    return parseInt(value) * 1.1;
                }, "left": function (index, value) {
                    return parseInt(value) - (e.offsetX || e.layerX) * 0.1;
                }, "top": function (index, value) {
                    return parseInt(value) - (e.offsetY || e.layerY) * 0.1;
                }
            });
        } else {
            $img.css({
                "width": function (index, value) {
                    value = parseInt(value);
                    temp = value / 1.1;
                    return value > originalData.width && temp > originalData.width ? temp : (temp = false, originalData.width);
                }, "height": function (index, value) {
                    value = parseInt(value);
                    temp = value / 1.1;
                    return value > originalData.height && temp > originalData.height ? temp : (temp = false, originalData.height);
                }, "left": function (index, value) {
                    return temp === false ? ($oriBox.width() - originalData.width) / 2 : parseInt(value) + (e.offsetX || e.layerX) / 11;
                }, "top": function (index, value) {
                    return temp === false ? ($oriBox.height() - originalData.height) / 2 : parseInt(value) + (e.offsetY || e.layerY) / 11;
                }
            })
        }
    }

    //open the limit of draging
    img.ondragstart = function (e) {
        e.returnValue = false;
        return false;
    };
    img.onmousedown = function (e) {
        if (!img.complete) return;
        originalData.isLock = false;
        originalData.left = e.clientX;
        originalData.top = e.clientY;
    };
    img.onmousemove = debounce(function (e) {
        e.preventDefault();
        if (!img.complete || originalData.isLock) return;
        $img.css({
            left: parseInt($img.css("left")) + e.clientX - originalData.left,
            top: parseInt($img.css("top")) + e.clientY - originalData.top
        });
        originalData.left = e.clientX;
        originalData.top = e.clientY;
    }, 20);
    img.onmouseup = function () {
        originalData.isLock = true;
    };
    img.onmouseout = function (e) {
        originalData.isLock = true;
    }
})();

$("#home-btn").click(function () {
    $body.removeClass("left-bottom left-top right-middle").addClass("left-middle");
    setTitle(Title)
    window.history.pushState({type: Type = "list", url: "/"}, Title, "/");
    doChanged();
    stopMedia();
});

window.addEventListener("popstate", function (e) {
    switch (Type = e.state.type) {
        case "article":
            $body.removeClass("left-top left-middle").addClass("left-bottom");
            break;
        case "tag":
            $body.removeClass("left-bottom left-middle").addClass("left-top");
            break;
        case "list":
            if (window.location.pathname.search(/^\/$||\/page\//) != 0) {
                $body.removeClass("left-bottom left-top").addClass("left-middle");
                break;
            }
        case "page":
            maskLoding.show();
            $("#left-middle").load(e.state.url + " #left-middle>*", function () {
                $body.removeClass("left-top left-bottom");
                doChanged();
                window.history.pushState({
                    type: "page",
                    url: window.location.href
                }, document.title, window.location.href);
                maskLoding.hide();
            });
    }
    doChanged();
    stopMedia();
});

function setTitle(t){
    $("title").text(t)
}

var masker = (function (noTransition) {
    var $mask = $("#mask-layer");

    return {
        show: function () {
            if(noTransition){
                $mask.show();
            }else{
                $mask.fadeIn();
            }
        },
        hide: function () {
            if(noTransition){
                $mask.hide();
            }else{
                $mask.fadeOut();
            }
        }
    }
})();

var maskLoding = (function (noTransition) {
    var $loading = $("#loading");

    return {
        show: function () {
            $loading.fadeIn();
            masker.show(noTransition);
        },
        hide: function () {
            $loading.fadeOut();
            masker.hide(noTransition);
        }
    }
})();

function init() {
    PhoneView = $("body").width() < 900;

    var path = window.location.pathname;

    if (path == "/") {
        Type = "list";
    } else if (path.indexOf("/tag/") == 0) {
        Type = "tag";
    } else if (path.indexOf("/page/") == 0) {
        Type = "page";
    } else {
        Type = "article";
        playMedia();
        initDuoshuo();
    }

    //remove aside-init when the DOM is ready, so we can show a perfect page even the index.js is not loaded
    $("#aside").removeClass("aside-init");
    doChanged();
    window.history.replaceState({type: Type, url: window.location.href}, document.title, window.location.href);
}

function doChanged() {
    fixWidthOfAside();
}

function stopMedia() {
    $("#left-bottom").find("audio,video").each(function () {
        this.pause();
    })
}

function playMedia(){
    $("#left-bottom").find("audio[autoplay=autoplay]").each(function(){
        setTimeout(function(){
            this.play();
        },1000)
    })
}

var fixWidthOfAside = (function() {
    /**
     * 修正浏览器bug,test.html中测试
     * 如果子节点为img，其宽度auto，高度根据父节点高度百分比变化
     * 父节点宽度为auto，在resize之后，父节点不会发生宽度变化，在所有浏览器中表现都不一样
     * 只能用js去纠正
     */
    var isPhoneViewBefore = $("body").width() < 900,
        $aside = $("#aside"),
        $title = $aside.find(".title"),
        $container = $("#container"),
        width;

    return function() {
        //do the change when convert layout
        if(isPhoneViewBefore && !PhoneView){
            //phone to pc
            $body.css("padding-top", "");
            isPhoneViewBefore = PhoneView;
        }else if(!isPhoneViewBefore && PhoneView){
            //pc to phone
            $body.css("padding-left", "");
            $title.width("auto");
            isPhoneViewBefore = PhoneView;
        }

        if (PhoneView) {
            if(Type == "article") {return $body.css("padding-top",0)};
            $body.css("padding-top", $aside.hasClass("slideUp") ? 0 : $title.height());
        }else{
            if ($body.hasClass("left-bottom")) {
                $body.css("padding-left",0);
            } else {
                width = $body.height() * 0.3;
                $title.width(width);
                $body.css("padding-left",width);
            }
        }
    }
})();

function debounce(func,delay){
    var lasttime = new Date();

    return function(){
        var now = new Date();
        if(now - lasttime > delay){
            lasttime = now;
            func.apply(this,arguments);
        }

    }
}

//duoshuo
function initDuoshuo() {
    var ds = document.getElementById("ds-thread");
    DUOSHUO.EmbedThread(ds);
}<commit_msg>fix popstate big fault<commit_after>var $body = $("#inner-body"),
    Type,
    PhoneView = false,
    Title = "纸异兽",
    supportHistory = !!(window.history.pushState && window.history.replaceState);

//alert(!!navigator.userAgent.match(/mobile/i));

$(function () {
    //load article list and cnblog list
    if (!$("#left-middle").html().trim()) {
        $.get("/", null, function (data) {
            var $data = $(data);

            $("#left-middle").replaceWith($data.find("#left-middle"));
            $("#right-middle").replaceWith($data.find("#right-middle"));
        }, "html");
    }
    init();
});

$("#aside").on({
    "mouseenter": function () {
        !PhoneView && $(this).removeClass("aside-close").addClass("aside-open");
        $("#aside .profile").scrollTop(0);
    },
    "mouseleave": function () {
        !PhoneView && $(this).removeClass("aside-open").addClass("aside-close");
    },
    "click": function (e) {
        var $this = $(this);

        if (PhoneView) {
            if (e.target.className == "close") {//click close button
                $this.removeClass("aside-open").addClass("aside-close");
            } else if (!$this.hasClass("aside-open")) {
                $this.removeClass("aside-close").addClass("aside-open");
                $("#aside .profile").scrollTop(0);
            }
        }
    }
});

$("#switch").on({
    "mouseenter": function () {
        !PhoneView && $(this).addClass("hover");
    },
    "mouseleave": function () {
        !PhoneView && $(this).removeClass("hover");
    },
    "click": function () {
        var $this = $(this);
        if (PhoneView) {
            $body.toggleClass("right-middle");
            $("html,body").scrollTop(0);
        } else {
            //toggle hover class, if hover exists, so that this is first click after mouseenter
            //if hover not exist, so prove that this isn't.
            $this.toggleClass("hover");

            //if isn't first click, add animation to this event
            if ($this.hasClass("hover")) {
                setTimeout(function () {
                    $body.toggleClass("right-middle");
                    $this.removeClass("hover");
                }, 500);
            } else {
                $body.toggleClass("right-middle");
            }
        }
    }
});

$(window).resize(function () {
    PhoneView = $("body").width() < 900;
    doChanged();
});

$(".content").scroll(function () {
    if (!PhoneView) return;

    if ($(this).scrollTop() >= 10) {
        $("#aside").addClass("slideUp");
    } else {
        $("#aside").removeClass("slideUp");
    }
    fixWidthOfAside();
});

function ATagClick(e, data) {
    //for normal a link
    var isPopstate = !e,
        action = isPopstate ? data.action : $(this).attr("action"),
        title = Title;

    if (!action || !supportHistory) {
        return;
    }

    if (!data && PhoneView && this.id == "readmore") {
        $("#aside").removeClass("aside-open").addClass("aside-close");
        e.stopPropagation();
    }

    e && e.preventDefault();
    var href = isPopstate ? data.href : this.href;

    maskLoding.show();
    switch (Type = action) {
        case "article":
            $("#left-bottom").load(href + " #left-bottom>*", function () {
                $body.removeClass("left-top left-middle").addClass("left-bottom");

                if (PhoneView) {
                    $("html,body").scrollTop(0);
                    playMedia();
                } else {
                    $(this).scrollTop(0);
                }

                doChanged();
                setTitle(title = $("h1.post-title").text());
                !isPopstate && window.history.pushState({type: action, url: href}, title, href);
                maskLoding.hide();
                initDuoshuo();
            });
            break;
        case "tag":
            $("#left-top").load(href + " #left-top>*", function () {
                $body.removeClass("left-bottom left-middle").addClass("left-top");
                PhoneView ? $("html,body").scrollTop(0) : $(this).scrollTop(0);
                doChanged();
                setTitle(title = $("h1.page-title").text());
                !isPopstate && window.history.pushState({type: action, url: href}, title, href);
                maskLoding.hide();
            });
            break;
        case "page":
            $("#left-middle").load(href + " #left-middle>*", function () {
                $body.removeClass("left-top left-bottom");
                PhoneView ? $("html,body").scrollTop(0) : $(this).scrollTop(0);
                doChanged();
                setTitle(title);
                !isPopstate && window.history.pushState({type: action, url: href}, document.title, href);
                maskLoding.hide();
            });
            break;
    }
}

$(".contents,.profile").on("click", "a", ATagClick);

//zoom for picture
(function () {
    var $tag = $("原图"),
        img = document.createElement("img"),
        $img = $(img),
        $oriBox = $("

×

"),
        $close = $oriBox.children("#masker-close"),
    //store original image data for zoom smaller to recovery the location
        originalData = {
            ratio: 1,
            width: 0,
            height: 0,
            top: 0,
            left: 0,
            //for limit mousemove event
            isLock: true
        },
        url;

    $(".contents")
        .on("mouseenter", ".post-content img", function () {
            var $this = $(this);

            url = this.src.replace(/-resize$/, "");
            $this.parent().css("position", "relative");
            originalData.ratio = $this.width() / $this.height();

            $tag.css({
                "top": $this.position().top,
                "right": $this.parent().width() - $this.width() - $this.position().left
            });

            $this.after($tag);
        }).on("mouseleave", ".post-content img", function (e) {
            if (e.relatedTarget == $tag[0]) {
                return;
            }
            $tag.remove();
        });

    $tag[0].onclick = function () {
        var $body = $("body"),
            width,
            height;

        //do it before get width because the scroll bar
        if (PhoneView) {
            $body.css("overflow", "hidden");
        }

        width = $body.width();
        height = $body.height();
        maskLoding.show();
        $oriBox.prepend($img);
        img.src = url;

        if (originalData.ratio > width / height) {
            originalData.width = width;
            originalData.height = width / originalData.ratio;
            originalData.top = (height - originalData.height) / 2;
            originalData.left = 0;
        } else {
            originalData.width = height * originalData.ratio;
            originalData.height = height;
            originalData.top = 0;
            originalData.left = (width - originalData.width) / 2;
        }

        $img.css({
            height: originalData.height,
            width: originalData.width,
            top: originalData.top,
            left: originalData.left
        });

        //for sync showing image and masker
        //so we will get a better transition
        setTimeout(function () {
            $body.append($oriBox);
        }, 300);
    };

    //see "jquery remove() and Event" with bug tag in evernote
    img.onload = function () {
        $("#loading").fadeOut();
    };

    $close[0].onclick = function () {
        if (PhoneView) {
            $("body").css("overflow", "");
        }

        $oriBox.remove();
        maskLoding.hide();
    };

    img.onmousewheel = img.dommousescroll = debounce(mousewheel, 20);
    img.addEventListener("DOMMouseScroll", img.onmousewheel);

    function mousewheel(e) {
        var temp;
        if (!$img[0].complete) return;
        if (e.detail ? e.detail < 0 : e.wheelDelta > 0) {
            $img.css({
                "width": function (index, value) {
                    return parseInt(value) * 1.1;
                }, "height": function (index, value) {
                    return parseInt(value) * 1.1;
                }, "left": function (index, value) {
                    return parseInt(value) - (e.offsetX || e.layerX) * 0.1;
                }, "top": function (index, value) {
                    return parseInt(value) - (e.offsetY || e.layerY) * 0.1;
                }
            });
        } else {
            $img.css({
                "width": function (index, value) {
                    value = parseInt(value);
                    temp = value / 1.1;
                    return value > originalData.width && temp > originalData.width ? temp : (temp = false, originalData.width);
                }, "height": function (index, value) {
                    value = parseInt(value);
                    temp = value / 1.1;
                    return value > originalData.height && temp > originalData.height ? temp : (temp = false, originalData.height);
                }, "left": function (index, value) {
                    return temp === false ? ($oriBox.width() - originalData.width) / 2 : parseInt(value) + (e.offsetX || e.layerX) / 11;
                }, "top": function (index, value) {
                    return temp === false ? ($oriBox.height() - originalData.height) / 2 : parseInt(value) + (e.offsetY || e.layerY) / 11;
                }
            })
        }
    }

    //open the limit of draging
    img.ondragstart = function (e) {
        e.returnValue = false;
        return false;
    };
    img.onmousedown = function (e) {
        if (!img.complete) return;
        originalData.isLock = false;
        originalData.left = e.clientX;
        originalData.top = e.clientY;
    };
    img.onmousemove = debounce(function (e) {
        e.preventDefault();
        if (!img.complete || originalData.isLock) return;
        $img.css({
            left: parseInt($img.css("left")) + e.clientX - originalData.left,
            top: parseInt($img.css("top")) + e.clientY - originalData.top
        });
        originalData.left = e.clientX;
        originalData.top = e.clientY;
    }, 20);
    img.onmouseup = function () {
        originalData.isLock = true;
    };
    img.onmouseout = function (e) {
        originalData.isLock = true;
    }
})();

$("#home-btn").click(function () {
    $body.removeClass("left-bottom left-top right-middle").addClass("left-middle");
    setTitle(Title)
    window.history.pushState({type: Type = "page", url: "/"}, Title, "/");
    doChanged();
    stopMedia();
});

$(window).on("popstate", function (e) {
    var state = e.originalEvent.state;

    switch (Type = state.type) {
        case "article":
            $body.removeClass("left-top left-middle").addClass("left-bottom");
            ATagClick(undefined, {action: Type, href: state.url});
            break;
        case "tag":
            $body.removeClass("left-bottom left-middle").addClass("left-top");
            break;
        case "page":
            maskLoding.show();
            ATagClick(undefined, {action: Type, href: state.url});
    }
    doChanged();
    stopMedia();
});

function setTitle(t) {
    $("title").text(t)
}

var masker = (function (noTransition) {
    var $mask = $("#mask-layer");

    return {
        show: function () {
            if (noTransition) {
                $mask.show();
            } else {
                $mask.fadeIn();
            }
        },
        hide: function () {
            if (noTransition) {
                $mask.hide();
            } else {
                $mask.fadeOut();
            }
        }
    }
})();

var maskLoding = (function (noTransition) {
    var $loading = $("#loading");

    return {
        show: function () {
            $loading.fadeIn();
            masker.show(noTransition);
        },
        hide: function () {
            $loading.fadeOut();
            masker.hide(noTransition);
        }
    }
})();

function init() {
    PhoneView = $("body").width() < 900;

    var path = window.location.pathname;

    if (path == "/") {
        Type = "page";
    } else if (path.indexOf("/tag/") == 0) {
        Type = "tag";
    } else if (path.indexOf("/page/") == 0) {
        Type = "page";
    } else {
        Type = "article";
        playMedia();
        initDuoshuo();
    }

    //remove aside-init when the DOM is ready, so we can show a perfect page even the index.js is not loaded
    $("#aside").removeClass("aside-init");
    doChanged();
    window.history.replaceState({type: Type, url: window.location.href}, document.title, window.location.href);
}

function doChanged() {
    fixWidthOfAside();
}

function stopMedia() {
    $("#left-bottom").find("audio,video").each(function () {
        this.pause();
    })
}

function playMedia() {
    $("#left-bottom").find("audio[autoplay=autoplay]").each(function () {
        setTimeout(function () {
            this.play();
        }, 1000)
    })
}

var fixWidthOfAside = (function () {
    /**
     * 修正浏览器bug,test.html中测试
     * 如果子节点为img，其宽度auto，高度根据父节点高度百分比变化
     * 父节点宽度为auto，在resize之后，父节点不会发生宽度变化，在所有浏览器中表现都不一样
     * 只能用js去纠正
     */
    var isPhoneViewBefore = $("body").width() < 900,
        $aside = $("#aside"),
        $title = $aside.find(".title"),
        $container = $("#container"),
        width;

    return function () {
        //do the change when convert layout
        if (isPhoneViewBefore && !PhoneView) {
            //phone to pc
            $body.css("padding-top", "");
            isPhoneViewBefore = PhoneView;
        } else if (!isPhoneViewBefore && PhoneView) {
            //pc to phone
            $body.css("padding-left", "");
            $title.width("auto");
            isPhoneViewBefore = PhoneView;
        }

        if (PhoneView) {
            if (Type == "article") {
                return $body.css("padding-top", 0)
            }
            ;
            $body.css("padding-top", $aside.hasClass("slideUp") ? 0 : $title.height());
        } else {
            if ($body.hasClass("left-bottom")) {
                $body.css("padding-left", 0);
            } else {
                width = $body.height() * 0.3;
                $title.width(width);
                $body.css("padding-left", width);
            }
        }
    }
})();

function debounce(func, delay) {
    var lasttime = new Date();

    return function () {
        var now = new Date();
        if (now - lasttime > delay) {
            lasttime = now;
            func.apply(this, arguments);
        }

    }
}

//duoshuo
function initDuoshuo() {
    var ds = document.getElementById("ds-thread");
    DUOSHUO.EmbedThread(ds);
}<|endoftext|>


<commit_before>import PublicationUtils from 'meteor/utilities:smart-publications';
import Posts from "meteor/nova:posts";
import Users from 'meteor/nova:users';
import Folders from "./collection.js";

Users.addField([
    /**
     Count of the user's Folders
     */
    {
        fieldName: "telescope.folderCount",
        fieldSchema: {
            type: Number,
            optional: true,
            publish: true,
            defaultValue: 0
        }
    },
    /**
     An array containing the `_id`s of folders
     */
    {
        fieldName: "telescope..folders",
        fieldSchema: {
            type: [String],
            optional: true,
            publish: true,
            join: {
                joinAs: "foldersArray",
                collection: () => Users,
                limit: 4
            }
        }
    }
]);

PublicationUtils.addToFields(Users.publishedFields.list, ["folderCount", "folders"]);

<commit_msg>add nova-tags copy from nova-categories.<commit_after>import PublicationUtils from 'meteor/utilities:smart-publications';
import Posts from "meteor/nova:posts";
import Users from 'meteor/nova:users';
import Folders from "./collection.js";

Users.addField([
    /**
     Count of the user's Folders
     */
    {
        fieldName: "telescope.folderCount",
        fieldSchema: {
            type: Number,
            optional: true,
            publish: true,
            defaultValue: 0
        }
    },
    /**
     An array containing the `_id`s of folders
     */
    {
        fieldName: "telescope.folders",
        fieldSchema: {
            type: [String],
            optional: true,
            publish: true,
            join: {
                joinAs: "foldersArray",
                collection: () => Users,
                limit: 4
            }
        }
    }
]);

PublicationUtils.addToFields(Users.publishedFields.list, ["folderCount", "folders"]);

<|endoftext|>


<commit_before>(function (angular) {
  'use strict';
  angular.module('app').factory('signInFormModel', signInFormModel);
  signInFormModel.$inject = ['AuthService', 'User', '$window', '$q', 'Facebook', 'GooglePlus'];
  function signInFormModel(AuthService, User, $window, $q, Facebook, GooglePlus) {
    var form = {
      login: '',
      password: '',
      rememberMe: true,
      signIn: signIn,
      facebook: facebook,
      google: google
    };
    return form;

    function signIn() {
      var def = $q.defer();
      AuthService.signIn(form.login, form.password).success(function (data) {
        if(form.rememberMe){
          $window.localStorage.token = data.token;
        }
        User.me(data.token).then(function(){
          def.resolve();
        });
      }).error(function(data){
        def.reject(data);
      });
      return def.promise;
    }
    function facebook() {
      var def = $q.defer();
      Facebook.getLoginStatus(function(response) {
        if(response.status == 'connected'){
          AuthService.facebook(response.authResponse.accessToken).success(function (data) {
            $window.localStorage.token = data.token;
            User.me(data.token).then(function(){
              def.resolve();
            });
          }).error(function (err) {
            def.reject(err);
          });
        } else {
          Facebook.login(function (responce) {
            AuthService.facebook(response.authResponse.accessToken).success(function (data) {
              $window.localStorage.token = data.token;
              User.me(data.token).then(function(){
                def.resolve();
              });
            }).error(function (err) {
              def.reject(err);
            });
          }, {scope: 'email, public_profile'});
        }
      });
      return def.promise;
    }
    function google() {
      var def = $q.defer();
      GooglePlus.login().then(function (authResult) {
        if(authResult.access_token){
          AuthService.google(authResult.access_token).success(function (data) {
            $window.localStorage.token = data.token;
            User.me(data.token).then(function(){
              def.resolve();
            });
          }).error(function (err) {
            def.reject(err);
          });
        } else {
          def.reject();
        }
      }, function (err) {
        def.reject(err);
      });
      return def.promise;
    }
  }
})(angular);<commit_msg>fix facebook login<commit_after>(function (angular) {
  'use strict';
  angular.module('app').factory('signInFormModel', signInFormModel);
  signInFormModel.$inject = ['AuthService', 'User', '$window', '$q', 'Facebook', 'GooglePlus'];
  function signInFormModel(AuthService, User, $window, $q, Facebook, GooglePlus) {
    var fbLoginStatus = '';
    var fbAccessToken = '';
    var form = {
      login: '',
      password: '',
      rememberMe: true,
      signIn: signIn,
      facebook: facebook,
      google: google
    };
    Facebook.getLoginStatus(function(response) {
      fbLoginStatus = response.status;
      if(fbLoginStatus == 'connected')
        fbAccessToken = response.authResponse.accessToken;
    });
    return form;

    function signIn() {
      var def = $q.defer();
      AuthService.signIn(form.login, form.password).success(function (data) {
        if(form.rememberMe){
          $window.localStorage.token = data.token;
        }
        User.me(data.token).then(function(){
          def.resolve();
        });
      }).error(function(data){
        def.reject(data);
      });
      return def.promise;
    }
    function facebook() {
      var def = $q.defer();
      if(fbLoginStatus == 'connected'){
        AuthService.facebook(fbAccessToken).success(function (data) {
          $window.localStorage.token = data.token;
          User.me(data.token).then(function(){
            def.resolve();
          });
        }).error(function (err) {
          def.reject(err);
        });
      } else {
        Facebook.login(function (response) {
          AuthService.facebook(response.authResponse.accessToken).success(function (data) {
            $window.localStorage.token = data.token;
            User.me(data.token).then(function(){
              def.resolve();
            });
          }).error(function (err) {
            def.reject(err);
          });
        }, {scope: 'email, public_profile'});
      }
      return def.promise;
    }
    function google() {
      var def = $q.defer();
      GooglePlus.login().then(function (authResult) {
        if(authResult.access_token){
          AuthService.google(authResult.access_token).success(function (data) {
            $window.localStorage.token = data.token;
            User.me(data.token).then(function(){
              def.resolve();
            });
          }).error(function (err) {
            def.reject(err);
          });
        } else {
          def.reject();
        }
      }, function (err) {
        def.reject(err);
      });
      return def.promise;
    }
  }
})(angular);<|endoftext|>


<commit_before>window.onload = function () {
    var elements = document.querySelectorAll('[data-chaffle]');

    Array.prototype.forEach.call(elements, function (el) {
        var chaffle = new Chaffle(el, {
            lang: 'ja-katakana',//ja-katakana
            speed: 10,
            delay: 60,
        })
        el.addEventListener('mouseover', function () {
            chaffle.init();
        });
    });
};

if (screen.width <= 720) {//Redirect if its a small screen (probably a phone)
    window.location = "./mobile.html";
    console.log('mobile redirect');
}<commit_msg>mobile testing<commit_after>window.onload = function () {
    var elements = document.querySelectorAll('[data-chaffle]');

    Array.prototype.forEach.call(elements, function (el) {
        var chaffle = new Chaffle(el, {
            lang: 'ja-katakana',//ja-katakana
            speed: 10,
            delay: 60,
        })
        el.addEventListener('mouseover', function () {
            chaffle.init();
        });
    });
};

if (screen.width <= 650) {//Redirect if its a small screen (probably a phone)
    window.location = "./mobile.html";
    console.log('mobile redirect');
    alert(screen.width);
}<|endoftext|>


<commit_before>import React from "react";
import moment from "moment";
import DayPicker from "react-day-picker";

import { isPastDay, isSameDay } from "../utils/DateUtils";

import "../style/DayPicker.scss";

class InputFieldExample extends React.Component {

  static displayName = "InputFieldExample"

  constructor(props) {
    super(props);
    const today = new Date();
    this.state = {
      // The value of the input field
      value: moment(today).format("L"),
      // The month to display in the calendar
      month: today
    };
  }

  render() {
    const { value, month } = this.state;

    const selectedDay = moment(value, "L", true).toDate();

    const modifiers = {

      // Add the `disabled` modifier to days in the past. The day cell will have
      // a `DayPicker-Day--disabled` CSS class
      "disabled": isPastDay,

      // Add the `selected` modifier to days corresponding to the day inserted
      // in the input field. The day cell will have a `DayPicker-Day--selected`
      // CSS class
      "selected": (day) => isSameDay(selectedDay, day)
    };

    return (

          <input
            ref="input"
            type="text"
            value={ value }
            placeholder="YYYY-MM-DD"
            onChange={ ::this.handleInputChange }
            onFocus={ ::this.showCurrentDate } />

        <DayPicker
          ref="daypicker"
          enableOutsideDays={true}
          initialMonth={ month }
          numberOfMonths={ 1 }
          modifiers={ modifiers }
          onDayTouchTap={ ::this.handleDayTouchTap } />

    );
  }

  handleInputChange(e) {

    const { value } = e.target;
    let { month } = this.state;

    // Change the current month only if the value entered by the user is a valid
    // date according to the `L` format
    if (moment(value, "L", true).isValid()) {
      month = moment(value, "L").toDate();
    }

    this.setState({
      value: value,
      month: month
    }, this.showCurrentDate);
  }

  handleDayTouchTap(e, day, modifiers) {
    if (modifiers.indexOf("disabled") > -1 ||
        modifiers.indexOf("outside") > -1) {
      return;
    }
    this.setState({
      value: moment(day).format("L"),
      month: day
    });
  }

  showCurrentDate() {
    this.refs.daypicker.showMonth(this.state.month);
  }

}

export default InputFieldExample;
<commit_msg>Enable day selection for outside days<commit_after>import React from "react";
import moment from "moment";
import DayPicker from "react-day-picker";

import { isPastDay, isSameDay } from "../utils/DateUtils";

import "../style/DayPicker.scss";

class InputFieldExample extends React.Component {

  static displayName = "InputFieldExample"

  constructor(props) {
    super(props);
    const today = new Date();
    this.state = {
      // The value of the input field
      value: moment(today).format("L"),
      // The month to display in the calendar
      month: today
    };
  }

  render() {
    const { value, month } = this.state;

    const selectedDay = moment(value, "L", true).toDate();

    const modifiers = {

      // Add the `disabled` modifier to days in the past. The day cell will have
      // a `DayPicker-Day--disabled` CSS class
      "disabled": isPastDay,

      // Add the `selected` modifier to days corresponding to the day inserted
      // in the input field. The day cell will have a `DayPicker-Day--selected`
      // CSS class
      "selected": (day) => isSameDay(selectedDay, day)
    };

    return (

          <input
            ref="input"
            type="text"
            value={ value }
            placeholder="YYYY-MM-DD"
            onChange={ ::this.handleInputChange }
            onFocus={ ::this.showCurrentDate } />

        <DayPicker
          ref="daypicker"
          enableOutsideDays={true}
          initialMonth={ month }
          numberOfMonths={ 1 }
          modifiers={ modifiers }
          onDayTouchTap={ ::this.handleDayTouchTap } />

    );
  }

  handleInputChange(e) {

    const { value } = e.target;
    let { month } = this.state;

    // Change the current month only if the value entered by the user is a valid
    // date according to the `L` format
    if (moment(value, "L", true).isValid()) {
      month = moment(value, "L").toDate();
    }

    this.setState({
      value: value,
      month: month
    }, this.showCurrentDate);
  }

  handleDayTouchTap(e, day, modifiers) {
    if (modifiers.indexOf("disabled") > -1) {
      return;
    }
    this.setState({
      value: moment(day).format("L"),
      month: day
    });
  }

  showCurrentDate() {
    this.refs.daypicker.showMonth(this.state.month);
  }

}

export default InputFieldExample;
<|endoftext|>


<commit_before>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end

var path = require('path');
var fs = require('fs');

//try to detect if user is using a custom scripts version
var custom_scripts = process.argv.indexOf('--scripts-version');

if(custom_scripts > -1 && custom_scripts + 1 <= process.argv.length){
  custom_scripts = process.argv[custom_scripts + 1];
}else{
  custom_scripts = false;
}

const scriptVersion = custom_scripts || 'react-scripts';
const projectDir = path.resolve(fs.realpathSync(process.cwd()));
const scriptVersionDir = process.env.NODE_PATH ? path.join(process.env.NODE_PATH, scriptVersion) : path.join(projectDir, 'node_modules', scriptVersion);

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
var appDirectory = fs.realpathSync(process.cwd());
function resolveApp(relativePath) {
  return path.resolve(appDirectory, relativePath);
}

// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.

// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders

// We will export `nodePaths` as an array of absolute paths.
// It will then be used by Webpack configs.
// Jest doesn’t need this because it already handles `NODE_PATH` out of the box.

// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421

var nodePaths = (process.env.NODE_PATH || '')
  .split(process.platform === 'win32' ? ';' : ':')
  .filter(Boolean)
  .filter(folder => !path.isAbsolute(folder))
  .map(resolveApp);

// config after eject: we're in ./config/
module.exports = {
  scriptVersion:scriptVersion,
  projectDir:projectDir,
  scriptVersionDir:scriptVersionDir,
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  ownNodeModules: resolveApp('node_modules'),
  nodePaths: nodePaths
};

// @remove-on-eject-begin
function resolveOwn(relativePath) {
  return path.resolve(__dirname, relativePath);
}

// config before eject: we're in ./node_modules/react-scripts/config/
module.exports = {
  scriptVersion:scriptVersion,
  projectDir:projectDir,
  scriptVersionDir:scriptVersionDir,
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  // this is empty with npm3 but node resolution searches higher anyway:
  ownNodeModules: resolveOwn('../node_modules'),
  nodePaths: nodePaths
};

// config before publish: we're in ./packages/react-scripts/config/
if (__dirname.indexOf(path.join('packages', 'react-scripts', 'config')) !== -1) {
  module.exports = {
    scriptVersion:scriptVersion,
    projectDir:projectDir,
    scriptVersionDir:scriptVersionDir,
    appBuild: resolveOwn('../../../build'),
    appPublic: resolveOwn('../template/public'),
    appHtml: resolveOwn('../template/public/index.html'),
    appIndexJs: resolveOwn('../template/src/index.js'),
    appPackageJson: resolveOwn('../package.json'),
    appSrc: resolveOwn('../template/src'),
    yarnLockFile: resolveOwn('../template/yarn.lock'),
    testsSetup: resolveOwn('../template/src/setupTests.js'),
    appNodeModules: resolveOwn('../node_modules'),
    ownNodeModules: resolveOwn('../node_modules'),
    nodePaths: nodePaths
  };
}
// @remove-on-eject-end
<commit_msg>Revert "Respect Node_path to get the scriptVersionDir"<commit_after>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end

var path = require('path');
var fs = require('fs');

//try to detect if user is using a custom scripts version
var custom_scripts = process.argv.indexOf('--scripts-version');

if(custom_scripts > -1 && custom_scripts + 1 <= process.argv.length){
  custom_scripts = process.argv[custom_scripts + 1];
}else{
  custom_scripts = false;
}

const scriptVersion = custom_scripts || 'react-scripts';
const projectDir = path.resolve(fs.realpathSync(process.cwd()));
const scriptVersionDir = path.join(projectDir, 'node_modules', scriptVersion);

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
var appDirectory = fs.realpathSync(process.cwd());
function resolveApp(relativePath) {
  return path.resolve(appDirectory, relativePath);
}

// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.

// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders

// We will export `nodePaths` as an array of absolute paths.
// It will then be used by Webpack configs.
// Jest doesn’t need this because it already handles `NODE_PATH` out of the box.

// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421

var nodePaths = (process.env.NODE_PATH || '')
  .split(process.platform === 'win32' ? ';' : ':')
  .filter(Boolean)
  .filter(folder => !path.isAbsolute(folder))
  .map(resolveApp);

// config after eject: we're in ./config/
module.exports = {
  scriptVersion:scriptVersion,
  projectDir:projectDir,
  scriptVersionDir:scriptVersionDir,
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  ownNodeModules: resolveApp('node_modules'),
  nodePaths: nodePaths
};

// @remove-on-eject-begin
function resolveOwn(relativePath) {
  return path.resolve(__dirname, relativePath);
}

// config before eject: we're in ./node_modules/react-scripts/config/
module.exports = {
  scriptVersion:scriptVersion,
  projectDir:projectDir,
  scriptVersionDir:scriptVersionDir,
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  // this is empty with npm3 but node resolution searches higher anyway:
  ownNodeModules: resolveOwn('../node_modules'),
  nodePaths: nodePaths
};

// config before publish: we're in ./packages/react-scripts/config/
if (__dirname.indexOf(path.join('packages', 'react-scripts', 'config')) !== -1) {
  module.exports = {
    scriptVersion:scriptVersion,
    projectDir:projectDir,
    scriptVersionDir:scriptVersionDir,
    appBuild: resolveOwn('../../../build'),
    appPublic: resolveOwn('../template/public'),
    appHtml: resolveOwn('../template/public/index.html'),
    appIndexJs: resolveOwn('../template/src/index.js'),
    appPackageJson: resolveOwn('../package.json'),
    appSrc: resolveOwn('../template/src'),
    yarnLockFile: resolveOwn('../template/yarn.lock'),
    testsSetup: resolveOwn('../template/src/setupTests.js'),
    appNodeModules: resolveOwn('../node_modules'),
    ownNodeModules: resolveOwn('../node_modules'),
    nodePaths: nodePaths
  };
}
// @remove-on-eject-end<|endoftext|>


<commit_before>define([
  'jquery'
], function ($) {
  function InfiniteScroll (decorated, $element, options, dataAdapter) {
    this.lastParams = {};

    decorated.call(this, $element, options, dataAdapter);

    this.$loadingMore = this.createLoadingMore();
    this.loading = false;
  }

  InfiniteScroll.prototype.append = function (decorated, data) {
    this.$loadingMore.remove();
    this.loading = false;

    decorated.call(this, data);

    if (this.showLoadingMore(data)) {
      this.$results.append(this.$loadingMore);
    }
  };

  InfiniteScroll.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    container.on('query', function (params) {
      self.lastParams = params;
      self.loading = true;
    });

    container.on('query:append', function (params) {
      self.lastParams = params;
      self.loading = true;
    });

    this.$results.on('scroll', function () {
      var isLoadMoreVisible = $.contains(
        document.documentElement,
        self.$loadingMore[0]
      );

      if (self.loading || !isLoadMoreVisible) {
        return;
      }

      var currentOffset = self.$results.offset().top +
        self.$results.outerHeight(false);
      var loadingMoreOffset = self.$loadingMore.offset().top +
        self.$loadingMore.outerHeight(false);

      if (currentOffset + 50 >= loadingMoreOffset) {
        self.loadMore();
      }
    });
  };

  InfiniteScroll.prototype.loadMore = function () {
    this.loading = true;

    var params = $.extend({}, {page: 1}, this.lastParams);

    params.page++;

    this.trigger('query:append', params);
  };

  InfiniteScroll.prototype.showLoadingMore = function (_, data) {
    return data.pagination && data.pagination.more;
  };

  InfiniteScroll.prototype.createLoadingMore = function () {
    var $option = $(
      '

'
    );

    var message = this.options.get('translations').get('loadingMore');

    $option.html(message(this.lastParams));

    return $option;
  };

  return InfiniteScroll;
});
<commit_msg>Appeased jshint "line is too long" error.<commit_after>define([
  'jquery'
], function ($) {
  function InfiniteScroll (decorated, $element, options, dataAdapter) {
    this.lastParams = {};

    decorated.call(this, $element, options, dataAdapter);

    this.$loadingMore = this.createLoadingMore();
    this.loading = false;
  }

  InfiniteScroll.prototype.append = function (decorated, data) {
    this.$loadingMore.remove();
    this.loading = false;

    decorated.call(this, data);

    if (this.showLoadingMore(data)) {
      this.$results.append(this.$loadingMore);
    }
  };

  InfiniteScroll.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    container.on('query', function (params) {
      self.lastParams = params;
      self.loading = true;
    });

    container.on('query:append', function (params) {
      self.lastParams = params;
      self.loading = true;
    });

    this.$results.on('scroll', function () {
      var isLoadMoreVisible = $.contains(
        document.documentElement,
        self.$loadingMore[0]
      );

      if (self.loading || !isLoadMoreVisible) {
        return;
      }

      var currentOffset = self.$results.offset().top +
        self.$results.outerHeight(false);
      var loadingMoreOffset = self.$loadingMore.offset().top +
        self.$loadingMore.outerHeight(false);

      if (currentOffset + 50 >= loadingMoreOffset) {
        self.loadMore();
      }
    });
  };

  InfiniteScroll.prototype.loadMore = function () {
    this.loading = true;

    var params = $.extend({}, {page: 1}, this.lastParams);

    params.page++;

    this.trigger('query:append', params);
  };

  InfiniteScroll.prototype.showLoadingMore = function (_, data) {
    return data.pagination && data.pagination.more;
  };

  InfiniteScroll.prototype.createLoadingMore = function () {
    var $option = $(
      '

'
    ).addClass('select2-results__option load-more');

    var message = this.options.get('translations').get('loadingMore');

    $option.html(message(this.lastParams));

    return $option;
  };

  return InfiniteScroll;
});
<|endoftext|>


<commit_before>/**
 * Main JS file for Casper behaviours
 */

/* globals jQuery, document */
(function ($, undefined) {
  "use strict";

  const TRIGGER_CLICK = 'click',
      TRIGGER_HOVER = 'hover',
      TRIGGER_AUTO = 'auto',
      TRIGGER_DEFAULT = TRIGGER_CLICK;

  class Ajax {
    static call (opts) {
      opts = opts || {};
      let params = opts.params || {},
        callback = opts.callback || new Function(),
        errCb = opts.err || new Function(),
        url = opts.url,
        method = opts.method || opts.type || 'GET';

      $.ajax({
        url: url,
        type: method,
        data: params
      }).done(callback).fail(errCb);
    }

    static parser (url) {
      url = url || this.url || '';
      let parser = document.createElement('a'),
          structure = {};
      parser.href = url;

      structure = {
        protocol: parser.protocol,
        hostname: parser.hostname,
        port: parser.port,
        pathname: parser.pathname,
        search: parser.search,
        hash: parser.hash,
        host: parser.host
      };

      return structure;
    }
  };

  class u {
    static rest (arr) {
      var clone = this.clone(arr, []);
      clone.splice(0, 1);
      return clone;
    };
    static clone (thing, extender) {
      extender = extender || {};
      return jQuery.extend(true, extender, thing);
    };
  };

  class J {
    constructor ($element, options) {
      if ($.isEmptyObject(options)) {

        if ($element.data('inline')) {
          options = $element.data('inline');
        }
        else {
          var args = $element.text().split(',');
          options = args[1] ? JSON.parse(u.rest(args).join(',')) || {} : {};
          options.body = args[0];
        }

      }

      options.$element =      $element || $("<div />");
      options.body =          options.body || $element.text();
      options.src =           options.src || $element.data('src') || $element.attr('href');
      options.autoplay =      options.autoplay || false;
      options.trigger =       options.trigger || TRIGGER_DEFAULT;

      this.config = options;
      this.$element = options.$element;
    };

    generate () {
      let config = this.config;

      if (config.src.match(/streamable/)) {
        this.handleStreamableMedia(config);
      }
      else if (config.src.match(/mp4/)) {
        this.handleVidFile(config);
      }
      else if (config.src.match(/gfycat/)) {
        this.handleGfyCat(config);
      }
      else if (config.src.match(/gifv/)) {
        this.handleImgur(config);
      }
      else if (config.src.match(/gif/)) {
        this.buildIMGWith(config);
      }
      else if (config.src.match(/jpg|jpeg|png/)) {
        this.buildIMGWith(config);
      }
      else if (config.src.match(/youtube/)) {
        this.handleYouTube(config);
      }
      else {
        console.log("JOE: Link doesn't have fun media.");
      }
    }

    // Various handlers
    handleStreamableMedia () {
      let uriArray = this.config.src.split('/'),
          streamableId = uriArray[uriArray.length - 1],
          src = '//streamable.com/res/' + streamableId,
          $element = this.$element;

      this.buildiFrame({
        $element: $element,
        width: '100%',
        src: src,
        scrolling: 'no'
      });
    };

    handleGfyCat () {
      let uriArray = this.config.src.split('/'),
          gfyCatDealie = uriArray[uriArray.length - 1],
          $element = this.$element,
          that = this,
          webmSrc, mp4Src;

      Ajax.call({
        url: '//gfycat.com/cajax/get/' + gfyCatDealie,
        method: 'GET',
        callback: function (response) {
          webmSrc = response.gfyItem.webmUrl;
          mp4Src = response.gfyItem.mp4Url;
          that.buildHTML5Video({
            $element: $element,
            wrapChildSources: true,
            webmSrc: webmSrc,
            mp4Src: mp4Src
          });
        },
        errCb: function () {
          console.log("Error: Failure to retrieve response for gfycat: ", gfyCatDealie);
        }
      });

    };

    handleYouTube () {
      let src = this.config.src,
          result = Ajax.parser(src),
          ytKey = result.search.split('=')[1],
          $element = this.$element;

      this.buildiFrame({
        $element: $element,
        src: '//youtube.com/embed/' + ytKey
      });
    };

    handleImgur (opts) {
      let $element = this.config.$element,
          arr = $element.data('src').split('.');
      arr.pop();
      let src = arr.join('.'),
          webmSrc = src + '.webm',
          mp4Src = src + '.mp4';

      this.buildHTML5Video({
        $element: $element,
        wrapChildSources: true,
        webmSrc: webmSrc,
        mp4Src: mp4Src
      });

    };

    handleVidFile () {
      this.buildHTML5Video(this.config);
    };

    // f()s that build html elments
    buildHTML5Video (opts) {
      opts = opts || {};
      let height = opts.height || 450,
          width = opts.width || '100%',
          $element = opts.$element || $('<div />'),
          src = opts.src || $element.data('src'),
          autoplay = opts.autoplay,
          //webmSrc = opts.webmSrc || (src + '.webm'),
          //mp4Src = opts.mp4Src || (src + '.mp4'),
          webmSrc = opts.webmSrc || false,
          mp4Src = opts.mp4Src || false,
          wrapChildSources = opts.wrapChildSources || false,
          $video = $('<video>', {
            height: height,
            width: width,
            loop: '',
            autoplay: autoplay,
            controls: '',
            muted: 'muted'
          }),
          webmID = opts.webmID || 'webmsource',
          mp4ID = opts.mp4ID || 'mp4source',
          $webmSource, $mp4Source;

      if (wrapChildSources) {
        if (webmSrc) {
          $webmSource = $('<source>', {
            id: webmID,
            src: webmSrc,
            type: 'video/webm'
          });
          $video.append($webmSource);
        }
        if (mp4Src) {
          $mp4Source = $('<source>', {
            id: mp4ID,
            src: mp4Src,
            type: 'video/mp4'
          });
          $video.append($mp4Source);
        }
      }
      else {
        $video.attr('src', src);
      }

      this.finishItUp($element, $video, this.config);
      return $element;
    };

    buildIMGWith (opts) {
      let $element = opts.$element,
          $img = $('<img>', {
            src: opts.src,
            width: "100%"
          });

      this.finishItUp($element, $img, this.config);
    };

    buildiFrame (opts) {
      opts = opts || {}
      let height = opts.height || 450,
          width = opts.width || 710,
          scrolling = opts.scrolling || 'no',
          $element = opts.$element || $('<div />'),
          src = opts.src || $element.data('src'),
          $iframe = $('<iframe>', {
            src: src,
            frameboarder: 0,
            height: height,
            width: width,
            scrolling: scrolling,
            allowfullscreen: ''
          });

      this.finishItUp($element, $iframe, this.config);

      return $element;
    };

    finishItUp ($element, $mediaElement, opts) {
      let trigger = opts.trigger;
      switch (opts.trigger) {
        case TRIGGER_CLICK:
          this.handleClick($element, $mediaElement);
        break;
        case TRIGGER_HOVER:
          this.handleHover($element, $mediaElement);
        break;
        case TRIGGER_AUTO:
          this.showMedia($element, $mediaElement);
        break;
      }

      if (opts.body) {
        $element.text(opts.body);
      }
    };

    // event handlers
    handleClick ($trigger, $ammo) {
      $trigger.on('click', e => {
        e.preventDefault();

        if ($ammo.is(':visible')) {
          $ammo.detach();
        }
        else {
          $ammo.appendTo($trigger);
        }
      });
    };

    handleHover ($trigger, $ammo) {
      $trigger.on('click', e => e.preventDefault());
      $trigger.on('mouseenter', e => {
        if (!$ammo.is(':visible')) {
          $ammo.appendTo($trigger);
        }
      });
      $trigger.on('mouseleave', e => {
        if ($ammo.is(':visible')) {
          $ammo.detach();
        }
      });
    };

    showMedia ($trigger, $ammo) {
      $ammo.appendTo($trigger);
    };

  };

  var $document = $(document),
      dealieArray = [];

  $document.ready(function () {
    checkInlineMedia();
    setArcticScroll();
  });

  var checkInlineMedia = function () {
    // $('a[data-inline]').each(function () {
    //   var $this = $(this),
    //       src = $this.data('src'),
    //       dealie = new J({
    //         $element: $this
    //       });

    //   dealieArray.push(dealie);
    // });

    $('a').each(function () {
      let $this = $(this),
          dealie = new J($this, {});

      dealie.generate();
      dealieArray.push(dealie);
    });
  };

  // Arctic Scroll Source
  var setArcticScroll = function () {
    var $postContent = $(".post-content");
    $postContent.fitVids();

    $(".scroll-down").arctic_scroll();

    $(".menu-button, .nav-cover, .nav-close").on("click", function(e){
      e.preventDefault();
      $("body").toggleClass("nav-opened nav-closed");
    });
  };
  // Arctic Scroll by Paul Adam Davis
  // https://github.com/PaulAdamDavis/Arctic-Scroll
  $.fn.arctic_scroll = function (options) {

    var defaults = {
      elem: $(this),
      speed: 500
    },

        allOptions = $.extend(defaults, options);

    allOptions.elem.click(function (event) {
      event.preventDefault();
      var $this = $(this),
          $htmlBody = $('html, body'),
          offset = ($this.attr('data-offset')) ? $this.attr('data-offset') : false,
          position = ($this.attr('data-position')) ? $this.attr('data-position') : false,
          toMove;

      if (offset) {
        toMove = parseInt(offset);
        $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top + toMove) }, allOptions.speed);
      } else if (position) {
        toMove = parseInt(position);
        $htmlBody.stop(true, false).animate({scrollTop: toMove }, allOptions.speed);
      } else {
        $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top) }, allOptions.speed);
      }
    });

  };

})(jQuery);
<commit_msg>progress on constructing the event handler to build the html element when triggered - not on page load.  So far decent progress but a bunch of reorg is necessary<commit_after>/**
 * Main JS file for Casper behaviours
 */

/* globals jQuery, document */
(function ($, undefined) {
  "use strict";

  const TRIGGER_CLICK = 'click',
      TRIGGER_HOVER = 'hover',
      TRIGGER_AUTO = 'auto',
      TRIGGER_DEFAULT = TRIGGER_CLICK;

  class Ajax {
    static call (opts) {
      opts = opts || {};
      let params = opts.params || {},
        callback = opts.callback || new Function(),
        errCb = opts.err || new Function(),
        url = opts.url,
        method = opts.method || opts.type || 'GET';

      $.ajax({
        url: url,
        type: method,
        data: params
      }).done(callback).fail(errCb);
    }

    static parser (url) {
      url = url || this.url || '';
      let parser = document.createElement('a'),
          structure = {};
      parser.href = url;

      structure = {
        protocol: parser.protocol,
        hostname: parser.hostname,
        port: parser.port,
        pathname: parser.pathname,
        search: parser.search,
        hash: parser.hash,
        host: parser.host
      };

      return structure;
    }
  };

  class u {
    static rest (arr) {
      var clone = this.clone(arr, []);
      clone.splice(0, 1);
      return clone;
    };
    static clone (thing, extender) {
      extender = extender || {};
      return jQuery.extend(true, extender, thing);
    };
  };

  class J {
    constructor ($element, options) {
      if ($.isEmptyObject(options)) {

        if ($element.data('inline')) {
          options = $element.data('inline');
        }
        else {
          var args = $element.text().split(',');
          options = args[1] ? JSON.parse(u.rest(args).join(',')) || {} : {};
          options.body = args[0];
        }

      }

      options.$element =      $element || $("<div />");
      options.body =          options.body || $element.text();
      options.src =           options.src || $element.data('src') || $element.attr('href');
      options.autoplay =      options.autoplay || false;
      options.trigger =       options.trigger || TRIGGER_DEFAULT;

      this.config = options;
      this.$element = options.$element;
      this.$mediaContainer = $('<div />');
    };

    generate () {
      // how is this flow going to work?
      // I guess have the click execute the generate?

      let config = this.config;

      if (config.src.match(/streamable/)) {
        this.handleStreamableMedia(config);
      }
      else if (config.src.match(/mp4/)) {
        this.handleVidFile(config);
      }
      else if (config.src.match(/gfycat/)) {
        this.handleGfyCat(config);
      }
      else if (config.src.match(/gifv/)) {
        this.handleImgur(config);
      }
      else if (config.src.match(/gif/)) {
        this.buildIMGWith(config);
      }
      else if (config.src.match(/jpg|jpeg|png/)) {
        this.buildIMGWith(config);
      }
      else if (config.src.match(/youtube/)) {
        this.handleYouTube(config);
      }
      else {
        console.log("JOE: Link doesn't have fun media.");
      }
    }

    handleTrigger () {
      let trigger = this.config.trigger;
      switch (trigger) {
        case TRIGGER_CLICK:
          this.generate();
          this.handleClick(this.config.$element, this.config.$mediaContainer);
        break;
        case TRIGGER_HOVER:
          this.generate();
          this.handleClick(this.config.$element, this.config.$mediaContainer);
        break;
        case TRIGGER_AUTO:
          this.generate();
          this.handleClick(this.config.$element, this.config.$mediaContainer);
        break;
      }
    }

    // Various handlers
    handleStreamableMedia () {
      let uriArray = this.config.src.split('/'),
          streamableId = uriArray[uriArray.length - 1],
          src = '//streamable.com/res/' + streamableId,
          $element = this.$element;

      this.buildiFrame({
        $element: $element,
        width: '100%',
        src: src,
        scrolling: 'no'
      });
    };

    handleGfyCat () {
      let uriArray = this.config.src.split('/'),
          gfyCatDealie = uriArray[uriArray.length - 1],
          $element = this.$element,
          that = this,
          webmSrc, mp4Src;

      Ajax.call({
        url: '//gfycat.com/cajax/get/' + gfyCatDealie,
        method: 'GET',
        callback: function (response) {
          webmSrc = response.gfyItem.webmUrl;
          mp4Src = response.gfyItem.mp4Url;
          that.buildHTML5Video({
            $element: $element,
            wrapChildSources: true,
            webmSrc: webmSrc,
            mp4Src: mp4Src
          });
        },
        errCb: function () {
          console.log("Error: Failure to retrieve response for gfycat: ", gfyCatDealie);
        }
      });

    };

    handleYouTube () {
      let src = this.config.src,
          result = Ajax.parser(src),
          ytKey = result.search.split('=')[1],
          $element = this.$element;

      this.buildiFrame({
        $element: $element,
        src: '//youtube.com/embed/' + ytKey
      });
    };

    handleImgur (opts) {
      let $element = this.config.$element,
          arr = $element.data('src').split('.');
      arr.pop();
      let src = arr.join('.'),
          webmSrc = src + '.webm',
          mp4Src = src + '.mp4';

      this.buildHTML5Video({
        $element: $element,
        wrapChildSources: true,
        webmSrc: webmSrc,
        mp4Src: mp4Src
      });

    };

    handleVidFile () {
      this.buildHTML5Video(this.config);
    };

    // f()s that build html elments
    buildHTML5Video (opts) {
      opts = opts || {};
      let height = opts.height || 450,
          width = opts.width || '100%',
          $element = opts.$element || $('<div />'),
          src = opts.src || $element.data('src'),
          autoplay = opts.autoplay,
          //webmSrc = opts.webmSrc || (src + '.webm'),
          //mp4Src = opts.mp4Src || (src + '.mp4'),
          webmSrc = opts.webmSrc || false,
          mp4Src = opts.mp4Src || false,
          wrapChildSources = opts.wrapChildSources || false,
          $video = $('<video>', {
            height: height,
            width: width,
            loop: '',
            autoplay: autoplay,
            controls: '',
            muted: 'muted'
          }),
          webmID = opts.webmID || 'webmsource',
          mp4ID = opts.mp4ID || 'mp4source',
          $webmSource, $mp4Source;

      if (wrapChildSources) {
        if (webmSrc) {
          $webmSource = $('<source>', {
            id: webmID,
            src: webmSrc,
            type: 'video/webm'
          });
          $video.append($webmSource);
        }
        if (mp4Src) {
          $mp4Source = $('<source>', {
            id: mp4ID,
            src: mp4Src,
            type: 'video/mp4'
          });
          $video.append($mp4Source);
        }
      }
      else {
        $video.attr('src', src);
      }

      this.finishItUp($element, $video);
      return $element;
    };

    buildIMGWith (opts) {
      let $element = opts.$element,
          $img = $('<img>', {
            src: opts.src,
            width: "100%"
          });

      this.finishItUp($element, $img);
    };

    buildiFrame (opts) {
      opts = opts || {}
      let height = opts.height || 450,
          width = opts.width || 710,
          scrolling = opts.scrolling || 'no',
          $element = opts.$element || $('<div />'),
          src = opts.src || $element.data('src'),
          $iframe = $('<iframe>', {
            src: src,
            frameboarder: 0,
            height: height,
            width: width,
            scrolling: scrolling,
            allowfullscreen: ''
          });

      this.finishItUp($element, $iframe);

      return $element;
    };

    finishItUp ($element, $mediaElement) {
      if (this.config.body) {
        $element.text(this.config.body);
      }

      this.$mediaContainer.append($mediaElement);
    };

    // event handlers
    handleClick ($trigger, $ammo) {
      $trigger.on('click', e => {
        e.preventDefault();

        if ($ammo.is(':visible')) {
          $ammo.detach();
        }
        else {
          $ammo.appendTo($trigger);
        }
      });
    };

    handleHover ($trigger, $ammo) {
      $trigger.on('click', e => e.preventDefault());
      $trigger.on('mouseenter', e => {
        if (!$ammo.is(':visible')) {
          $ammo.appendTo($trigger);
        }
      });
      $trigger.on('mouseleave', e => {
        if ($ammo.is(':visible')) {
          $ammo.detach();
        }
      });
    };

    showMedia ($trigger, $ammo) {
      $ammo.appendTo($trigger);
    };

  };

  var $document = $(document),
      dealieArray = [];

  $document.ready(function () {
    checkInlineMedia();
    setArcticScroll();
  });

  var checkInlineMedia = function () {
    // $('a[data-inline]').each(function () {
    //   var $this = $(this),
    //       src = $this.data('src'),
    //       dealie = new J({
    //         $element: $this
    //       });

    //   dealieArray.push(dealie);
    // });

    $('a').each(function () {
      let $this = $(this),
          dealie = new J($this, {});

      dealie.generate();
      dealieArray.push(dealie);
    });
  };

  // Arctic Scroll Source
  var setArcticScroll = function () {
    var $postContent = $(".post-content");
    $postContent.fitVids();

    $(".scroll-down").arctic_scroll();

    $(".menu-button, .nav-cover, .nav-close").on("click", function(e){
      e.preventDefault();
      $("body").toggleClass("nav-opened nav-closed");
    });
  };
  // Arctic Scroll by Paul Adam Davis
  // https://github.com/PaulAdamDavis/Arctic-Scroll
  $.fn.arctic_scroll = function (options) {

    var defaults = {
      elem: $(this),
      speed: 500
    },

        allOptions = $.extend(defaults, options);

    allOptions.elem.click(function (event) {
      event.preventDefault();
      var $this = $(this),
          $htmlBody = $('html, body'),
          offset = ($this.attr('data-offset')) ? $this.attr('data-offset') : false,
          position = ($this.attr('data-position')) ? $this.attr('data-position') : false,
          toMove;

      if (offset) {
        toMove = parseInt(offset);
        $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top + toMove) }, allOptions.speed);
      } else if (position) {
        toMove = parseInt(position);
        $htmlBody.stop(true, false).animate({scrollTop: toMove }, allOptions.speed);
      } else {
        $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top) }, allOptions.speed);
      }
    });

  };

})(jQuery);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import $ from 'jquery';
import fullCalendar from 'fullcalendar';
import moment from 'moment';
import RaisedButton from 'material-ui/RaisedButton';

export default class Calendar extends Component {
  constructor() {
    super();
    this.state = { period: 1 };
  }
  componentWillReceiveProps(newProps) {
    const { courses } = this.props;
    if (newProps.courses !== courses && newProps.courses.length > 0) {
      this.updateView(newProps.courses);
    }
  }
  componentDidMount() {
    $(this.refs.calendar).fullCalendar({
      header: false,
      columnFormat: 'ddd',
			editable: true,
      defaultView: 'agendaWeek',
      hiddenDays: [ 0, 6 ], // hide Sundays and Saturdays
      contentHeight: 519,
      allDaySlot: false,
      minTime: "08:00:00",
      maxTime: "18:00:00",
    });
  }
  componentDidUpdate(oldProps, oldState) {
    if (oldState.period !== this.state.period) {
      this.updateView(this.props.courses);
    }
  }
  changePeriod(i) {
    this.setState({ period: i });
  }
  renderButtons() {
    return Array(4).fill(0).map((v, i) =>
      <RaisedButton key={i}
        style={{margin: '5px'}}
        label={i+1}
        primary={true}
        onTouchTap={this.changePeriod.bind(this, i+1)}/>
    );
  }
  updateView(courses) {
    $(this.refs.calendar).fullCalendar('removeEvents');
    courses.forEach((course, i) => {
      if(course.period==this.state.period){
        course.lessons.forEach((lesson, j) => {
          // console.log(lesson);
          console.log(lesson);
          const startTime = moment().startOf('isoweek').add(lesson.day-1, 'days').add(lesson.startTime, 'hours').toDate();
          const endTime = moment().startOf('isoweek').add(lesson.day-1, 'days').add(lesson.endTime, 'hours').toDate();
          console.log(startTime);
          $(this.refs.calendar).fullCalendar('renderEvent',
            {
              id: course.id,
              title: course.name,
              start: startTime, // lesson.startTime
              end: endTime,
            },
          );
        });
      }
    });
  }
  render() {
    return

      {this.renderButtons()}

;
  }
}

Calendar.propTypes = {
  courses: React.PropTypes.array,
}
<commit_msg>Small layout changes to Calendar.js<commit_after>import React, { Component } from 'react';
import $ from 'jquery';
import fullCalendar from 'fullcalendar';
import moment from 'moment';
import RaisedButton from 'material-ui/RaisedButton';

export default class Calendar extends Component {
  constructor() {
    super();
    this.state = { period: 1 };
  }
  componentWillReceiveProps(newProps) {
    const { courses } = this.props;
    if (newProps.courses !== courses && newProps.courses.length > 0) {
      this.updateView(newProps.courses);
    }
  }
  componentDidMount() {
    $(this.refs.calendar).fullCalendar({
      header: false,
      columnFormat: 'ddd',
			editable: true,
      defaultView: 'agendaWeek',
      hiddenDays: [ 0, 6 ], // hide Sundays and Saturdays
      contentHeight: 519,
      allDaySlot: false,
      minTime: "08:00:00",
      maxTime: "18:00:00",
    });
  }
  componentDidUpdate(oldProps, oldState) {
    if (oldState.period !== this.state.period) {
      this.updateView(this.props.courses);
    }
  }
  changePeriod(i) {
    this.setState({ period: i });
  }
  renderButtons() {
    const { period } = this.state;
    return Array(4).fill(0).map((v, i) => {
      return (
        <RaisedButton key={i}
          style={{margin: '0px 5px'}}
          label={i+1}
          primary={period !== i+1}
          secondary={period === i+1}
          onTouchTap={this.changePeriod.bind(this, i+1)}/>
      );
    });
  }
  updateView(courses) {
    $(this.refs.calendar).fullCalendar('removeEvents');
    courses.forEach((course, i) => {
      if(course.period==this.state.period){
        course.lessons.forEach((lesson, j) => {
          // console.log(lesson);
          console.log(lesson);
          const startTime = moment().startOf('isoweek').add(lesson.day-1, 'days').add(lesson.startTime, 'hours').toDate();
          const endTime = moment().startOf('isoweek').add(lesson.day-1, 'days').add(lesson.endTime, 'hours').toDate();
          console.log(startTime);
          $(this.refs.calendar).fullCalendar('renderEvent',
            {
              id: course.id,
              title: course.name,
              start: startTime, // lesson.startTime
              end: endTime,
            },
          );
        });
      }
    });
  }
  render() {
    return

Periods

      {this.renderButtons()}

;
  }
}

Calendar.propTypes = {
  courses: React.PropTypes.array,
}
<|endoftext|>


<commit_before>let dot = require("dot");
let fs = require("fs");
let eol = require("os").EOL;

/* Below are the templates used by react-atlas to generate files for themeing.
 * The templating library used by react-atlas is dot.js. More info about dot.js
 * can be found here: http://olado.github.io/doT/index.html . Dot.js was chosen
 * because it has no dependencies, is MIT licensed and works.
 *
 * Dot.js templates are just strings of text. To print out a variable with dot.js
 * Use double curly brackets, followed by the variable name. You will need to put =it.
 * on the begining of the variable you pass dot.js. Then make sure to close the double
 * curly brackets. Here's an example using a variable called component:
 *
 * {{=it.component.name}}
 *
 * Here's a full example:
 *
 * let dot = require("dot");
 *
 * let component = { 'name': 'input'};
 * let template = "{{=it.component.name}}";
 *
 * let tempFn = dot.template(template);
 * let resultText = tempFn({ component: component });
 *
 * The variable resultText will contain the rendered component, so
 * you will have to use fs.writeFileSync() or something similar to
 * actually write the template to disk or somewhere else.
 *
 * The example above only evaluates a single variable, to render an array
 * you will have to change a few things. First use ~it. instead of =it. like
 * before. The ~ means evaluate an array, use {{~}} to tell dot.js to stop repeating
 * over. Here's an example of the template:
 *
 * "{{~it.components :value:index}}" +
 *  eol +
 * "export {{=value.name}} from './{{=value.name}}';" +
 *  eol +
 * "{{~}}";
 *
 */

/* The warning message appended to the top of every machine generated file.
 * This warning informs developers not to make changes to machine generated files
 * and to instead change the code generator. */
const warningMessage =
  "/* WARNING, THIS FILE WAS MACHINE GENERATED. DO NOT MODIFY THIS FILE DIRECTLY " +
  eol +
  "BECAUSE YOUR CHANGES WILL BE OVERWRITTEN WHEN THIS FILE IS GENERATED AGAIN. " +
  eol +
  "IF YOU WAN'T TO MODIFY THIS FILE YOU SHOULD BE MODIFYING THE GENERATOR IT'S SELF " +
  eol +
  "AND REGENERATE THIS FILE. */" +
  eol;

/* The template used for generating production react-atlas components. */
let template = warningMessage;
template +=
  "import CSSModules from 'react-css-modules';" +
  eol +
  "import { {{=it.component.name}}Core } from 'react-atlas-core';" +
  eol +
  "import { {{=it.component.name}}Style } from '{{=it.component.theme}}';" +
  eol +
  "export const {{=it.component.name}} = CSSModules({{=it.component.name}}Core, {{=it.component.name}}Style, {allowMultiple: true, errorWhenNotFound: true});";

/* The template used to generate the development react-atlas components. The
 * development component is actually a wrapper around the "real" component
 * so that react-styleguidist can recognize the component and generate a docsite. */
let devTemplate = warningMessage;
devTemplate +=
  "import CSSModules from 'react-css-modules';" +
  eol +
  "import React from 'react';" +
  eol +
  "import PropTypes from 'prop-types';" +
  eol +
  "import { {{=it.component.name}}Core } from 'react-atlas-core';" +
  eol +
  "import { {{=it.component.name}}Style } from '{{=it.component.theme}}';" +
  eol +
  "const {{=it.component.name}}Comp = CSSModules({{=it.component.name}}Core, {{=it.component.name}}Style, {allowMultiple: true, errorWhenNotFound: true});" +
  eol +
  "export default class {{=it.component.name}} extends React.Component {" +
  eol +
  "constructor(props){" +
  eol +
  "super(props)" +
  eol +
  "}" +
  eol +
  "render() {" +
  eol +
  "return (" +
  eol +
  "<{{=it.component.name}}Comp {...this.props}></{{=it.component.name}}Comp>" +
  eol +
  ")" +
  eol +
  "}" +
  eol +
  "}" +
  eol +
  "{{=it.component.name}}.propTypes = {" +
  eol +
  "{{~it.component.propTypes :value:index}}" +
  eol +
  "/** {{=value.description}} */" +
  eol +
  "{{=value.type}}," +
  eol +
  "{{~}}" +
  eol +
  "};";

let indexTemplate = warningMessage;
indexTemplate +=
  "{{~it.components :value:index}}" +
  eol +
  "export {{{=value.name}}} from './{{=value.name}}';" +
  eol +
  "{{~}}" +
  eol;

let compIndexTemplate = warningMessage;
compIndexTemplate +=
  "export {{=it.component.name}} from './{{=it.component.name}}.js';";

/* Dot template settings. Keep defaults except turn off stripping newlines feature
 * of dot.js. */
dot.templateSettings = {
  evaluate: /\{\{([\s\S]+?)\}\}/g,
  interpolate: /\{\{=([\s\S]+?)\}\}/g,
  encode: /\{\{!([\s\S]+?)\}\}/g,
  use: /\{\{#([\s\S]+?)\}\}/g,
  define: /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,
  conditional: /\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,
  iterate: /\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,
  varname: "it",
  strip: false,
  append: true,
  selfcontained: false
};

/* TODO: Replace hardcoded array with a dynamic solution. */
let components = [
  "avatar",
  "button",
  "checkbox",
  "checkboxGroup",
  "dropdown",
  "form",
  "input",
  "radio",
  "radioGroup",
  "switch",
  "table",
  "tooltip",
  "hint",
  "textArea",
  "textField"
];

module.exports = {
  warningMessage: warningMessage,
  template: template,
  components: components,
  indexTemplate: indexTemplate,
  compIndexTemplate: compIndexTemplate,
  devTemplate: devTemplate
};
<commit_msg>Remove deperecated option from react-css-modules.<commit_after>let dot = require("dot");
let fs = require("fs");
let eol = require("os").EOL;

/* Below are the templates used by react-atlas to generate files for themeing.
 * The templating library used by react-atlas is dot.js. More info about dot.js
 * can be found here: http://olado.github.io/doT/index.html . Dot.js was chosen
 * because it has no dependencies, is MIT licensed and works.
 *
 * Dot.js templates are just strings of text. To print out a variable with dot.js
 * Use double curly brackets, followed by the variable name. You will need to put =it.
 * on the begining of the variable you pass dot.js. Then make sure to close the double
 * curly brackets. Here's an example using a variable called component:
 *
 * {{=it.component.name}}
 *
 * Here's a full example:
 *
 * let dot = require("dot");
 *
 * let component = { 'name': 'input'};
 * let template = "{{=it.component.name}}";
 *
 * let tempFn = dot.template(template);
 * let resultText = tempFn({ component: component });
 *
 * The variable resultText will contain the rendered component, so
 * you will have to use fs.writeFileSync() or something similar to
 * actually write the template to disk or somewhere else.
 *
 * The example above only evaluates a single variable, to render an array
 * you will have to change a few things. First use ~it. instead of =it. like
 * before. The ~ means evaluate an array, use {{~}} to tell dot.js to stop repeating
 * over. Here's an example of the template:
 *
 * "{{~it.components :value:index}}" +
 *  eol +
 * "export {{=value.name}} from './{{=value.name}}';" +
 *  eol +
 * "{{~}}";
 *
 */

/* The warning message appended to the top of every machine generated file.
 * This warning informs developers not to make changes to machine generated files
 * and to instead change the code generator. */
const warningMessage =
  "/* WARNING, THIS FILE WAS MACHINE GENERATED. DO NOT MODIFY THIS FILE DIRECTLY " +
  eol +
  "BECAUSE YOUR CHANGES WILL BE OVERWRITTEN WHEN THIS FILE IS GENERATED AGAIN. " +
  eol +
  "IF YOU WAN'T TO MODIFY THIS FILE YOU SHOULD BE MODIFYING THE GENERATOR IT'S SELF " +
  eol +
  "AND REGENERATE THIS FILE. */" +
  eol;

/* The template used for generating production react-atlas components. */
let template = warningMessage;
template +=
  "import CSSModules from 'react-css-modules';" +
  eol +
  "import { {{=it.component.name}}Core } from 'react-atlas-core';" +
  eol +
  "import { {{=it.component.name}}Style } from '{{=it.component.theme}}';" +
  eol +
  "export const {{=it.component.name}} = CSSModules({{=it.component.name}}Core, {{=it.component.name}}Style, {allowMultiple: true});";

/* The template used to generate the development react-atlas components. The
 * development component is actually a wrapper around the "real" component
 * so that react-styleguidist can recognize the component and generate a docsite. */
let devTemplate = warningMessage;
devTemplate +=
  "import CSSModules from 'react-css-modules';" +
  eol +
  "import React from 'react';" +
  eol +
  "import PropTypes from 'prop-types';" +
  eol +
  "import { {{=it.component.name}}Core } from 'react-atlas-core';" +
  eol +
  "import { {{=it.component.name}}Style } from '{{=it.component.theme}}';" +
  eol +
  "const {{=it.component.name}}Comp = CSSModules({{=it.component.name}}Core, {{=it.component.name}}Style, {allowMultiple: true});" +
  eol +
  "export default class {{=it.component.name}} extends React.Component {" +
  eol +
  "constructor(props){" +
  eol +
  "super(props)" +
  eol +
  "}" +
  eol +
  "render() {" +
  eol +
  "return (" +
  eol +
  "<{{=it.component.name}}Comp {...this.props}></{{=it.component.name}}Comp>" +
  eol +
  ")" +
  eol +
  "}" +
  eol +
  "}" +
  eol +
  "{{=it.component.name}}.propTypes = {" +
  eol +
  "{{~it.component.propTypes :value:index}}" +
  eol +
  "/** {{=value.description}} */" +
  eol +
  "{{=value.type}}," +
  eol +
  "{{~}}" +
  eol +
  "};";

let indexTemplate = warningMessage;
indexTemplate +=
  "{{~it.components :value:index}}" +
  eol +
  "export {{{=value.name}}} from './{{=value.name}}';" +
  eol +
  "{{~}}" +
  eol;

let compIndexTemplate = warningMessage;
compIndexTemplate +=
  "export {{=it.component.name}} from './{{=it.component.name}}.js';";

/* Dot template settings. Keep defaults except turn off stripping newlines feature
 * of dot.js. */
dot.templateSettings = {
  evaluate: /\{\{([\s\S]+?)\}\}/g,
  interpolate: /\{\{=([\s\S]+?)\}\}/g,
  encode: /\{\{!([\s\S]+?)\}\}/g,
  use: /\{\{#([\s\S]+?)\}\}/g,
  define: /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,
  conditional: /\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,
  iterate: /\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,
  varname: "it",
  strip: false,
  append: true,
  selfcontained: false
};

/* TODO: Replace hardcoded array with a dynamic solution. */
let components = [
  "avatar",
  "button",
  "checkbox",
  "checkboxGroup",
  "dropdown",
  "form",
  "input",
  "radio",
  "radioGroup",
  "switch",
  "table",
  "tooltip",
  "hint",
  "textArea",
  "textField"
];

module.exports = {
  warningMessage: warningMessage,
  template: template,
  components: components,
  indexTemplate: indexTemplate,
  compIndexTemplate: compIndexTemplate,
  devTemplate: devTemplate
};
<|endoftext|>


<commit_before>import { exec } from 'child_process';

import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import localResolve from 'rollup-plugin-local-resolve';
import { terser } from 'rollup-plugin-terser';
import copy from 'rollup-plugin-copy';

import pkg from './package.json';

/** @type {import('rollup').RollupOptions.globals} */
const globals = {
  react: 'React',
  dateFns: 'date-dns'
};

/** Custom rollup plugin to exec tsc-alias over the built files */
function tscAliasPlugin() {
  return {
    name: 'tsc-alias',
    writeBundle: () => {
      return new Promise((resolve, reject) => {
        exec('tsc-alias', function callback(error, stdout, stderr) {
          if (stderr || error) {
            reject(stderr || error);
          } else {
            resolve(stdout);
          }
        });
      });
    }
  };
}

/** @type {import('rollup').RollupOptions} */
const buildConfig = {
  input: 'src/index.ts',
  output: [
    {
      file: pkg.module,
      format: 'esm',
      sourcemap: true
    },
    {
      file: pkg.main,
      format: 'cjs',
      sourcemap: true
    }
  ],
  plugins: [
    peerDepsExternal(),
    resolve(),
    commonjs(),
    typescript({
      tsconfig: './tsconfig.build.json',
      sourceMap: true
    }),
    localResolve(),
    tscAliasPlugin(),
    copy({
      targets: [
        {
          src: ['./src/style.css', './src/style.css.d.ts'],
          dest: './dist'
        },
        {
          src: './src/style.css',
          dest: './dist',
          rename: 'style.module.css',
          transform: (contents) => contents.toString().replace(/\.rdp-/g, '.')
        },
        {
          src: './src/style.css.d.ts',
          dest: './dist',
          rename: 'style.module.css.d.ts',
          transform: (contents) => contents.toString().replace(/rdp-/g, '')
        }
      ]
    })
  ]
};

/** @type {import('rollup').RollupOptions} */
const browserConfig = {
  input: 'dist/index.js',
  output: [
    {
      file: pkg.browser,
      format: 'umd',
      name: 'DatePicker',
      globals
    }
  ],
  plugins: [terser()]
};

export default [buildConfig, browserConfig];
<commit_msg>chore: fix umd file in rollup<commit_after>import { exec } from 'child_process';

import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import localResolve from 'rollup-plugin-local-resolve';
import { terser } from 'rollup-plugin-terser';
import copy from 'rollup-plugin-copy';

import pkg from './package.json';

/** @type {import('rollup').RollupOptions.globals} */
const globals = {
  react: 'React',
  dateFns: 'date-dns'
};

/** Custom rollup plugin to exec tsc-alias over the built files */
function tscAliasPlugin() {
  return {
    name: 'tsc-alias',
    writeBundle: () => {
      return new Promise((resolve, reject) => {
        exec('tsc-alias', function callback(error, stdout, stderr) {
          if (stderr || error) {
            reject(stderr || error);
          } else {
            resolve(stdout);
          }
        });
      });
    }
  };
}

/** @type {import('rollup').RollupOptions} */
const buildConfig = {
  input: 'src/index.ts',
  output: [
    {
      file: pkg.module,
      format: 'esm',
      sourcemap: true
    },
    {
      file: pkg.main,
      format: 'cjs',
      sourcemap: true
    }
  ],
  plugins: [
    peerDepsExternal(),
    resolve(),
    commonjs(),
    typescript({
      tsconfig: './tsconfig.build.json',
      sourceMap: true
    }),
    localResolve(),
    tscAliasPlugin(),
    copy({
      targets: [
        {
          src: ['./src/style.css', './src/style.css.d.ts'],
          dest: './dist'
        },
        {
          src: './src/style.css',
          dest: './dist',
          rename: 'style.module.css',
          transform: (contents) => contents.toString().replace(/\.rdp-/g, '.')
        },
        {
          src: './src/style.css.d.ts',
          dest: './dist',
          rename: 'style.module.css.d.ts',
          transform: (contents) => contents.toString().replace(/rdp-/g, '')
        }
      ]
    })
  ]
};

/** @type {import('rollup').RollupOptions} */
const browserConfig = {
  input: 'dist/index.js',
  output: [
    {
      file: pkg.unpkg,
      format: 'umd',
      name: 'DatePicker',
      globals
    }
  ],
  plugins: [terser()]
};

export default [buildConfig, browserConfig];
<|endoftext|>