<commit_before>// 工程配置
BI.prepares.push(function () {
    // 注册布局
    // adapt类布局优先级规则
    // 1、在非IE且支持flex的浏览器下使用flex布局
    // 2、IE或者不支持flex的浏览器下使用inline布局
    // 3、在2的情况下如果布局的items大于1的话使用display:table的布局
    // 4、在3的情况下如果IE版本低于8使用table标签布局
    var _isSupportFlex;
    var isSupportFlex = function () {
        if (_isSupportFlex == null) {
            _isSupportFlex = !!(BI.isSupportCss3 && BI.isSupportCss3("flex"));
        }
        return _isSupportFlex;
    };
    BI.Plugin.configWidget("bi.horizontal", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), isLessIE8 = isIE && BI.getIEVersion() < 8;
        if (isLessIE8) {
            return ob;
        }
        // 在横向自适应场景下我们需要使用table的自适应撑出滚动条的特性（flex处理不了这种情况）
        // 主要出现在center_adapt或者horizontal_adapt的场景，或者主动设置horizontalAlign的场景
        if (ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch) {
            return BI.extend(ob, {type: "bi.table_adapt"});
        }
        if (!isIE && supportFlex) {
            return BI.extend(ob, {type: "bi.flex_horizontal"});
        }
        // 解决使用inline_vertical_adapt的顺序问题
        // 从右往左放置时，为了兼容，我们统一采用从右到左的放置方式
        if (ob.horizontalAlign === BI.HorizontalAlign.Right) {
            return BI.extend(ob, {type: "bi.inline_vertical_adapt", items: ob.items && ob.items.reverse()});
        }
        return BI.extend(ob, {type: "bi.table_adapt"});
    });
    BI.Plugin.configWidget("bi.center_adapt", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), justOneItem = (ob.items && ob.items.length <= 1);
        var isAdapt = !ob.horizontalAlign || ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        if (!isIE && supportFlex) {
            if (!isAdapt || justOneItem) {
                return BI.extend(ob, {type: "bi.flex_center_adapt"});
            }
        }
        if (!isAdapt || justOneItem) {
            return BI.extend(ob, {type: "bi.inline_center_adapt"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.vertical_adapt", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), justOneItem = (ob.items && ob.items.length <= 1);
        var isAdapt = ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        if (!isIE && supportFlex) {
            if (!isAdapt || justOneItem) {
                return BI.extend(ob, {type: "bi.flex_vertical_center_adapt"});
            }
        }
        if (!isAdapt || justOneItem) {
            return BI.extend(ob, {type: "bi.inline_vertical_adapt"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.horizontal_adapt", function (ob) {
        if (!ob.verticalAlign || ob.verticalAlign === BI.VerticalAlign.TOP) {
            if (ob.items && ob.items.length <= 1) {
                return BI.extend(ob, {type: "bi.horizontal_auto"});
            }
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.horizontal_float", function (ob) {
        if (!BI.isIE() && isSupportFlex()) {
            return BI.extend(ob, {type: "bi.flex_horizontal_adapt"});
        }
        return BI.extend(ob, {type: "bi.inline_horizontal_adapt"});
    });

    BI.Plugin.configWidget("bi.flex_horizontal", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_horizontal"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_vertical"});
        }
    });
    BI.Plugin.configWidget("bi.flex_horizontal_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_horizontal_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_vertical_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_horizontal_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_horizontal_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_vertical_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true || ob.scrollx === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_center_adapt"});
        }
    });

    BI.Plugin.configWidget("bi.radio", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return BI.extend(ob, {type: "bi.image_radio"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.checkbox", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return BI.extend(ob, {type: "bi.image_checkbox"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.half_icon_button", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return ob;
        }
        return BI.extend(ob, {type: "bi.half_button"});
    });
});
<commit_msg>bugfix<commit_after>// 工程配置
BI.prepares.push(function () {
    // 注册布局
    // adapt类布局优先级规则
    // 1、在非IE且支持flex的浏览器下使用flex布局
    // 2、IE或者不支持flex的浏览器下使用inline布局
    // 3、在2的情况下如果布局的items大于1的话使用display:table的布局
    // 4、在3的情况下如果IE版本低于8使用table标签布局
    var _isSupportFlex;
    var isSupportFlex = function () {
        if (_isSupportFlex == null) {
            _isSupportFlex = !!(BI.isSupportCss3 && BI.isSupportCss3("flex"));
        }
        return _isSupportFlex;
    };
    BI.Plugin.configWidget("bi.horizontal", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), isLessIE8 = isIE && BI.getIEVersion() < 8;
        if (isLessIE8) {
            return ob;
        }
        // 在横向自适应场景下我们需要使用table的自适应撑出滚动条的特性（flex处理不了这种情况）
        // 主要出现在center_adapt或者horizontal_adapt的场景，或者主动设置horizontalAlign的场景
        if (ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch) {
            return BI.extend(ob, {type: "bi.table_adapt"});
        }
        if (!isIE && supportFlex) {
            return BI.extend(ob, {type: "bi.flex_horizontal"});
        }
        // 解决使用inline_vertical_adapt的顺序问题
        // 从右往左放置时，为了兼容，我们统一采用从右到左的放置方式
        if (ob.horizontalAlign === BI.HorizontalAlign.Right) {
            return BI.extend(ob, {type: "bi.inline_vertical_adapt", items: ob.items && ob.items.reverse()});
        }
        return BI.extend(ob, {type: "bi.table_adapt"});
    });
    BI.Plugin.configWidget("bi.center_adapt", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), justOneItem = (ob.items && ob.items.length <= 1);
        var isAdapt = !ob.horizontalAlign || ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        if (!isAdapt || justOneItem) {
            if (!isIE && supportFlex) {
                return BI.extend(ob, {type: "bi.flex_center_adapt"});
            }
            return BI.extend(ob, {type: "bi.inline_center_adapt"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.vertical_adapt", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), justOneItem = (ob.items && ob.items.length <= 1);
        var isAdapt = ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        if (!isAdapt || justOneItem) {
            if (!isIE && supportFlex) {
                return BI.extend(ob, {type: "bi.flex_vertical_center_adapt"});
            }
            return BI.extend(ob, {type: "bi.inline_vertical_adapt"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.horizontal_adapt", function (ob) {
        var justOneItem = (ob.items && ob.items.length <= 1);
        if (!ob.verticalAlign || ob.verticalAlign === BI.VerticalAlign.TOP) {
            if (justOneItem) {
                return BI.extend(ob, {type: "bi.horizontal_auto"});
            }
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.horizontal_float", function (ob) {
        if (!BI.isIE() && isSupportFlex()) {
            return BI.extend(ob, {type: "bi.flex_horizontal_adapt"});
        }
        return BI.extend(ob, {type: "bi.inline_horizontal_adapt"});
    });

    BI.Plugin.configWidget("bi.flex_horizontal", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_horizontal"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_vertical"});
        }
    });
    BI.Plugin.configWidget("bi.flex_horizontal_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_horizontal_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_vertical_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_horizontal_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_horizontal_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_vertical_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true || ob.scrollx === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_center_adapt"});
        }
    });

    BI.Plugin.configWidget("bi.radio", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return BI.extend(ob, {type: "bi.image_radio"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.checkbox", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return BI.extend(ob, {type: "bi.image_checkbox"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.half_icon_button", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return ob;
        }
        return BI.extend(ob, {type: "bi.half_button"});
    });
});
<|endoftext|>


<commit_before>// 工程配置
BI.prepares.push(function () {
    // 注册布局
    // adapt类布局优先级规则
    // 1、在非IE且支持flex的浏览器下使用flex布局
    // 2、IE或者不支持flex的浏览器下使用inline布局
    // 3、在2的情况下如果布局的items大于1的话使用display:table的布局
    // 4、在3的情况下如果IE版本低于8使用table标签布局
    var _isSupportFlex;
    var isSupportFlex = function () {
        if (_isSupportFlex == null) {
            _isSupportFlex = !!(BI.isSupportCss3 && BI.isSupportCss3("flex"));
        }
        return _isSupportFlex;
    };
    BI.Plugin.configWidget("bi.horizontal", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), isLessIE8 = isIE && BI.getIEVersion() < 8;
        if (isLessIE8) {
            return ob;
        }
        // 在横向自适应场景下我们需要使用table的自适应撑出滚动条的特性（flex处理不了这种情况）
        // 主要出现在center_adapt或者horizontal_adapt的场景，或者主动设置horizontalAlign的场景
        if (ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch) {
            return BI.extend(ob, {type: "bi.table_adapt"});
        }
        if (!IE && supportFlex) {
            return BI.extend(ob, {type: "bi.flex_horizontal"});
        }
        // 解决使用inline_vertical_adapt的顺序问题
        // 从右往左放置时，为了兼容，我们统一采用从右到左的放置方式
        if (ob.horizontalAlign === BI.HorizontalAlign.Right) {
            return BI.extend(ob, {type: "bi.inline_vertical_adapt", items: ob.items && ob.items.reverse()});
        }
        return BI.extend(ob, {type: "bi.table_adapt"});
    });
    BI.Plugin.configWidget("bi.center_adapt", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), justOneItem = (ob.items && ob.items.length <= 1);
        var isAdapt = ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        if (!isIE && supportFlex) {
            if (!isAdapt || justOneItem) {
                return BI.extend(ob, {type: "bi.flex_center_adapt"});
            }
        }
        if (!isAdapt || justOneItem) {
            return BI.extend(ob, {type: "bi.inline_center_adapt"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.vertical_adapt", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), justOneItem = (ob.items && ob.items.length <= 1);
        var isAdapt = ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        if (!isIE && supportFlex) {
            if (!isAdapt || justOneItem) {
                return BI.extend(ob, {type: "bi.flex_vertical_center_adapt"});
            }
        }
        if (!isAdapt || justOneItem) {
            return BI.extend(ob, {type: "bi.inline_vertical_adapt"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.horizontal_adapt", function (ob) {
        if (ob.verticalAlign === BI.VerticalAlign.TOP && ob.items && ob.items.length <= 1) {
            return BI.extend(ob, {type: "bi.horizontal_auto"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.horizontal_float", function (ob) {
        if (!BI.isIE() && isSupportFlex()) {
            return BI.extend(ob, {type: "bi.flex_horizontal_adapt"});
        }
        return BI.extend(ob, {type: "bi.inline_horizontal_adapt"});
    });

    BI.Plugin.configWidget("bi.flex_horizontal", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_horizontal"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_vertical"});
        }
    });
    BI.Plugin.configWidget("bi.flex_horizontal_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_horizontal_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_vertical_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_horizontal_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_horizontal_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_vertical_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true || ob.scrollx === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_center_adapt"});
        }
    });

    BI.Plugin.configWidget("bi.radio", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return BI.extend(ob, {type: "bi.image_radio"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.checkbox", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return BI.extend(ob, {type: "bi.image_checkbox"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.half_icon_button", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return ob;
        }
        return BI.extend(ob, {type: "bi.half_button"});
    });
});
<commit_msg>Pull request #1470: 无JIRA任务 整理一下<commit_after>// 工程配置
BI.prepares.push(function () {
    // 注册布局
    // adapt类布局优先级规则
    // 1、在非IE且支持flex的浏览器下使用flex布局
    // 2、IE或者不支持flex的浏览器下使用inline布局
    // 3、在2的情况下如果布局的items大于1的话使用display:table的布局
    // 4、在3的情况下如果IE版本低于8使用table标签布局
    var _isSupportFlex;
    var isSupportFlex = function () {
        if (_isSupportFlex == null) {
            _isSupportFlex = !!(BI.isSupportCss3 && BI.isSupportCss3("flex"));
        }
        return _isSupportFlex;
    };
    BI.Plugin.configWidget("bi.horizontal", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), isLessIE8 = isIE && BI.getIEVersion() < 8;
        if (isLessIE8) {
            return ob;
        }
        // 在横向自适应场景下我们需要使用table的自适应撑出滚动条的特性（flex处理不了这种情况）
        // 主要出现在center_adapt或者horizontal_adapt的场景，或者主动设置horizontalAlign的场景
        if (ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch) {
            return BI.extend(ob, {type: "bi.table_adapt"});
        }
        if (!IE && supportFlex) {
            return BI.extend(ob, {type: "bi.flex_horizontal"});
        }
        // 解决使用inline_vertical_adapt的顺序问题
        // 从右往左放置时，为了兼容，我们统一采用从右到左的放置方式
        if (ob.horizontalAlign === BI.HorizontalAlign.Right) {
            return BI.extend(ob, {type: "bi.inline_vertical_adapt", items: ob.items && ob.items.reverse()});
        }
        return BI.extend(ob, {type: "bi.table_adapt"});
    });
    BI.Plugin.configWidget("bi.center_adapt", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), justOneItem = (ob.items && ob.items.length <= 1);
        var isAdapt = !ob.horizontalAlign || ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        if (!isIE && supportFlex) {
            if (!isAdapt || justOneItem) {
                return BI.extend(ob, {type: "bi.flex_center_adapt"});
            }
        }
        if (!isAdapt || justOneItem) {
            return BI.extend(ob, {type: "bi.inline_center_adapt"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.vertical_adapt", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), justOneItem = (ob.items && ob.items.length <= 1);
        var isAdapt = ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        if (!isIE && supportFlex) {
            if (!isAdapt || justOneItem) {
                return BI.extend(ob, {type: "bi.flex_vertical_center_adapt"});
            }
        }
        if (!isAdapt || justOneItem) {
            return BI.extend(ob, {type: "bi.inline_vertical_adapt"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.horizontal_adapt", function (ob) {
        if (!ob.verticalAlign || ob.verticalAlign === BI.VerticalAlign.TOP) {
            if (ob.items && ob.items.length <= 1) {
                return BI.extend(ob, {type: "bi.horizontal_auto"});
            }
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.horizontal_float", function (ob) {
        if (!BI.isIE() && isSupportFlex()) {
            return BI.extend(ob, {type: "bi.flex_horizontal_adapt"});
        }
        return BI.extend(ob, {type: "bi.inline_horizontal_adapt"});
    });

    BI.Plugin.configWidget("bi.flex_horizontal", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_horizontal"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_vertical"});
        }
    });
    BI.Plugin.configWidget("bi.flex_horizontal_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_horizontal_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_vertical_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_horizontal_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_horizontal_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_vertical_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true || ob.scrollx === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_center_adapt"});
        }
    });

    BI.Plugin.configWidget("bi.radio", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return BI.extend(ob, {type: "bi.image_radio"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.checkbox", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return BI.extend(ob, {type: "bi.image_checkbox"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.half_icon_button", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return ob;
        }
        return BI.extend(ob, {type: "bi.half_button"});
    });
});
<|endoftext|>


<commit_before>import { invariant, isFunction } from './utils';
import enhanceReducer from './enhanceReducer';
import AppStateWithEffects from './AppStateWithEffects';

/**
 * Wraps Store `getState` method. Instead of returning just plain old state,
 * it's assumed that the returned state is instance of `AppStateWithEffects`,
 * therefore it proxies the call to `getAppState`.
 *
 * @param {Object} Original Store
 * @returns {Function} Wrapped `getState`
 */
export const wrapGetState = store => () => {
  const state = store.getState();

  if (state instanceof AppStateWithEffects) {
    return state.getAppState();
  } else {
    return state;
  }
};

/**
 * Wraps Store `dispatch` method. The original `dispatch` is called first, then
 * it iterates over all the effects returned from the `getState` function.
 * Every effect is then executed and dispatch is passed as the first argument.
 *
 * @param {Object} Original Store
 * @returns {Function} Wrapped `dispatch`
 */
export const wrapDispatch = store => action => {
  // Let's just dispatch original action,
  // the original dispatch might actually be
  // enhanced by some middlewares.
  const result = store.dispatch(action);

  const effects = store.getState().getEffects();

  invariant(effects.every(isFunction),
    `It's allowed to yield only functions (side effect)`);

  // Effects are executed after action is dispatched
  effects.forEach(effect => effect(wrapDispatch(store)));

  return result;
};

/**
 * Wraps Store `replaceReducer` method. The implementation just calls
 * the original `replaceReducer` method but the provided next reducer
 * is enhanced.
 *
 * @param {Object} Original Store
 * @returns {Function} Wrapped `replaceReducer`
 */
export const wrapReplaceReducer = store => nextReducer =>
  store.replaceReducer(enhanceReducer(nextReducer));

/**
 * Creates enhanced store factory, which takes original `createStore` as argument.
 * The store's `dispatch` and `getState` methods are wrapped with custom implementation.
 *
 * wrappedDispatch calls the original dispatch and executes all the side effects.
 *
 * wrappedGetState unwraps original applicaiton state from `AppStateWithEffects`
 *
 * @param {Function} Original createStore implementation to be enhanced
 * @returns {Function} Store factory
 */
export default createStore => (rootReducer, initialState) => {
  const store = createStore(enhanceReducer(rootReducer), new AppStateWithEffects(initialState, []));

  return {
    ...store,
    dispatch: wrapDispatch(store),
    getState: wrapGetState(store),
    liftGetState: () => store.getState(),
    replaceReducer: wrapReplaceReducer(store)
  };
};
<commit_msg>passing args<commit_after>import { invariant, isFunction } from './utils';
import enhanceReducer from './enhanceReducer';
import AppStateWithEffects from './AppStateWithEffects';

/**
 * Wraps Store `getState` method. Instead of returning just plain old state,
 * it's assumed that the returned state is instance of `AppStateWithEffects`,
 * therefore it proxies the call to `getAppState`.
 *
 * @param {Object} Original Store
 * @returns {Function} Wrapped `getState`
 */
export const wrapGetState = store => () => {
  const state = store.getState();

  if (state instanceof AppStateWithEffects) {
    return state.getAppState();
  } else {
    return state;
  }
};

/**
 * Wraps Store `dispatch` method. The original `dispatch` is called first, then
 * it iterates over all the effects returned from the `getState` function.
 * Every effect is then executed and dispatch is passed as the first argument.
 *
 * @param {Object} Original Store
 * @returns {Function} Wrapped `dispatch`
 */
export const wrapDispatch = store => (...args) => {
  // Let's just dispatch original action,
  // the original dispatch might actually be
  // enhanced by some middlewares.
  const result = store.dispatch(...args);

  const effects = store.getState().getEffects();

  invariant(effects.every(isFunction),
    `It's allowed to yield only functions (side effect)`);

  // Effects are executed after action is dispatched
  effects.forEach(effect => effect(wrapDispatch(store)));

  return result;
};

/**
 * Wraps Store `replaceReducer` method. The implementation just calls
 * the original `replaceReducer` method but the provided next reducer
 * is enhanced.
 *
 * @param {Object} Original Store
 * @returns {Function} Wrapped `replaceReducer`
 */
export const wrapReplaceReducer = store => nextReducer =>
  store.replaceReducer(enhanceReducer(nextReducer));

/**
 * Creates enhanced store factory, which takes original `createStore` as argument.
 * The store's `dispatch` and `getState` methods are wrapped with custom implementation.
 *
 * wrappedDispatch calls the original dispatch and executes all the side effects.
 *
 * wrappedGetState unwraps original applicaiton state from `AppStateWithEffects`
 *
 * @param {Function} Original createStore implementation to be enhanced
 * @returns {Function} Store factory
 */
export default createStore => (rootReducer, initialState) => {
  const store = createStore(enhanceReducer(rootReducer), new AppStateWithEffects(initialState, []));

  return {
    ...store,
    dispatch: wrapDispatch(store),
    getState: wrapGetState(store),
    liftGetState: () => store.getState(),
    replaceReducer: wrapReplaceReducer(store)
  };
};
<|endoftext|>


<commit_before>'use strict';

const utils = require('./utils');
const jwt = require('jsonwebtoken');

/*
 Mimicks the request context object
 http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html
 */
module.exports = function createLambdaProxyContext(request, options, stageVariables) {
  const authPrincipalId = request.auth && request.auth.credentials && request.auth.credentials.user;
  const authContext = (request.auth && request.auth.credentials && request.auth.credentials.context) || {};
  let authAuthorizer;

  if (process.env.AUTHORIZER) {
    try {
      authAuthorizer = JSON.parse(process.env.AUTHORIZER);
    }
    catch (error) {
      console.error('Serverless-offline: Could not parse process.env.AUTHORIZER, make sure it is correct JSON.');
    }
  }

  let body = request.payload;

  const headers = request.unprocessedHeaders;

  if (body) {
    if (typeof body !== 'string') {
      // JSON.stringify(JSON.parse(request.payload)) is NOT the same as the rawPayload
      body = request.rawPayload;
    }

    if (!headers['Content-Length'] && !headers['content-length'] && !headers['Content-length']) {
      headers['Content-Length'] = Buffer.byteLength(body);
    }

    // Set a default Content-Type if not provided.
    if (!headers['Content-Type'] && !headers['content-type'] && !headers['Content-type']) {
      headers['Content-Type'] = 'application/json';
    }
  }
  else if (typeof body === 'undefined' || body === '') {
    body = null;
  }

  const pathParams = {};

  Object.keys(request.params).forEach(key => {
    // aws doesn't auto decode path params - hapi does
    pathParams[key] = encodeURIComponent(request.params[key]);
  });

  let token = headers.Authorization || headers.authorization;

  if (token && token.split(' ')[0] === 'Bearer') {
    token = token.split(' ')[1];
  }

  let claims;

  if (token) {
    try {
      claims = jwt.decode(token) || undefined;
    } catch (err) {
      // Do nothing
    }
  }

  return {
    headers,
    multiValueHeaders: request.multiValueHeaders,
    path: request.path,
    pathParameters: utils.nullIfEmpty(pathParams),
    requestContext: {
      accountId: 'offlineContext_accountId',
      resourceId: 'offlineContext_resourceId',
      apiId: 'offlineContext_apiId',
      stage: options.stage,
      requestId: `offlineContext_requestId_${utils.randomId()}`,
      identity: {
        cognitoIdentityPoolId: 'offlineContext_cognitoIdentityPoolId',
        accountId: 'offlineContext_accountId',
        cognitoIdentityId: request.headers['cognito-identity-id'] || 'offlineContext_cognitoIdentityId',
        caller: 'offlineContext_caller',
        apiKey: 'offlineContext_apiKey',
        sourceIp: request.info.remoteAddress,
        cognitoAuthenticationType: 'offlineContext_cognitoAuthenticationType',
        cognitoAuthenticationProvider: request.headers['cognito-authentication-provider'] || 'offlineContext_cognitoAuthenticationProvider',
        userArn: 'offlineContext_userArn',
        userAgent: request.headers['user-agent'] || '',
        user: 'offlineContext_user',
      },
      authorizer: authAuthorizer || Object.assign(authContext, { // 'principalId' should have higher priority
        principalId: authPrincipalId || process.env.PRINCIPAL_ID || 'offlineContext_authorizer_principalId', // See #24
        claims,
      }),
      protocol: 'HTTP/1.1',
      resourcePath: request.route.path,
      httpMethod: request.method.toUpperCase(),
    },
    resource: request.route.path,
    httpMethod: request.method.toUpperCase(),
    queryStringParameters: utils.nullIfEmpty(utils.normalizeQuery(request.query)),
    multiValueQueryStringParameters: utils.nullIfEmpty(utils.normalizeMultiValueQuery(request.query)),
    stageVariables: utils.nullIfEmpty(stageVariables),
    body,
  };
};
<commit_msg>Fix code style<commit_after>'use strict';

const utils = require('./utils');
const jwt = require('jsonwebtoken');

/*
 Mimicks the request context object
 http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html
 */
module.exports = function createLambdaProxyContext(request, options, stageVariables) {
  const authPrincipalId = request.auth && request.auth.credentials && request.auth.credentials.user;
  const authContext = (request.auth && request.auth.credentials && request.auth.credentials.context) || {};
  let authAuthorizer;

  if (process.env.AUTHORIZER) {
    try {
      authAuthorizer = JSON.parse(process.env.AUTHORIZER);
    }
    catch (error) {
      console.error('Serverless-offline: Could not parse process.env.AUTHORIZER, make sure it is correct JSON.');
    }
  }

  let body = request.payload;

  const headers = request.unprocessedHeaders;

  if (body) {
    if (typeof body !== 'string') {
      // JSON.stringify(JSON.parse(request.payload)) is NOT the same as the rawPayload
      body = request.rawPayload;
    }

    if (!headers['Content-Length'] && !headers['content-length'] && !headers['Content-length']) {
      headers['Content-Length'] = Buffer.byteLength(body);
    }

    // Set a default Content-Type if not provided.
    if (!headers['Content-Type'] && !headers['content-type'] && !headers['Content-type']) {
      headers['Content-Type'] = 'application/json';
    }
  }
  else if (typeof body === 'undefined' || body === '') {
    body = null;
  }

  const pathParams = {};

  Object.keys(request.params).forEach(key => {
    // aws doesn't auto decode path params - hapi does
    pathParams[key] = encodeURIComponent(request.params[key]);
  });

  let token = headers.Authorization || headers.authorization;

  if (token && token.split(' ')[0] === 'Bearer') {
    token = token.split(' ')[1];
  }

  let claims;

  if (token) {
    try {
      claims = jwt.decode(token) || undefined;
    }
    catch (err) {
      // Do nothing
    }
  }

  return {
    headers,
    multiValueHeaders: request.multiValueHeaders,
    path: request.path,
    pathParameters: utils.nullIfEmpty(pathParams),
    requestContext: {
      accountId: 'offlineContext_accountId',
      resourceId: 'offlineContext_resourceId',
      apiId: 'offlineContext_apiId',
      stage: options.stage,
      requestId: `offlineContext_requestId_${utils.randomId()}`,
      identity: {
        cognitoIdentityPoolId: 'offlineContext_cognitoIdentityPoolId',
        accountId: 'offlineContext_accountId',
        cognitoIdentityId: request.headers['cognito-identity-id'] || 'offlineContext_cognitoIdentityId',
        caller: 'offlineContext_caller',
        apiKey: 'offlineContext_apiKey',
        sourceIp: request.info.remoteAddress,
        cognitoAuthenticationType: 'offlineContext_cognitoAuthenticationType',
        cognitoAuthenticationProvider: request.headers['cognito-authentication-provider'] || 'offlineContext_cognitoAuthenticationProvider',
        userArn: 'offlineContext_userArn',
        userAgent: request.headers['user-agent'] || '',
        user: 'offlineContext_user',
      },
      authorizer: authAuthorizer || Object.assign(authContext, { // 'principalId' should have higher priority
        principalId: authPrincipalId || process.env.PRINCIPAL_ID || 'offlineContext_authorizer_principalId', // See #24
        claims,
      }),
      protocol: 'HTTP/1.1',
      resourcePath: request.route.path,
      httpMethod: request.method.toUpperCase(),
    },
    resource: request.route.path,
    httpMethod: request.method.toUpperCase(),
    queryStringParameters: utils.nullIfEmpty(utils.normalizeQuery(request.query)),
    multiValueQueryStringParameters: utils.nullIfEmpty(utils.normalizeMultiValueQuery(request.query)),
    stageVariables: utils.nullIfEmpty(stageVariables),
    body,
  };
};
<|endoftext|>


<commit_before>//书籍渲染库

var _ = require('underscore');
var shell = require('./shell');
var fse = require('co-fs-extra');
var fs = require('co-fs');
var marked = require('marked');
var Gitbook = require('gitbook').Book;
var moment = require('moment');
//生成封面
var cover = require('./cover/index');

//默认配置
var defaultConfig = {
    src: 'book-md/',
    dest: 'book-html/',
    themes:{
        apebook:'./theme/apebook',
        blog:'./theme/blog'
    },
    //默认启用的插件
    "plugins": []
};

var Book = module.exports = function (config) {
    var self = this;
    config = _.extend(defaultConfig,config);
    if (config) {
        _.each(config, function (value, key) {
            self[key] = value;
        });
    }
};

Book.prototype = {
    //渲染md成html
    render: function *(config) {
        var self = this;
        var ctx = self.ctx;
        var user = this.user;
        var book = this.book;
        var src = self.bookPath();
        var hasSrc = yield fs.exists(src);
        if(!hasSrc){
            return {'success':false,'msg':'不存在 '+book+' 目录'};
        }
        //确定绑定的仓库是否符合gitbook规范
        var isBook = yield this.isBook();
        if(!isBook){
            return {'success':false,'msg':'仓库缺少 SUMMARY.md 或者 README.md'};
        }
        yield fse.ensureDir(self.dest+user);
        var path = self.dest+user+'/'+book;
        yield fse.ensureDir(path);
        //图书配置
        var bookJson = {};
        bookJson.theme = config && config.theme || self.themes['apebook'];
        bookJson.output = path;
        var data = this.data;
        bookJson.githubUser = data.githubUser;
        bookJson.githubRepo = data.githubRepo;
        bookJson.bookId = data.id;
        bookJson.bookName = book;
        bookJson.apebookHost = this.apebookHost;
        bookJson.assetHost = this.assetHost;
        bookJson.desc = data.desc;
        //本地调试环境
        if(process.env.NODE_ENV !== 'local'){
            bookJson.localAssetHost = bookJson.assetHost;
        }

        bookJson.plugins = this.plugins;
        yield fse.writeFile(src+'/book.json',JSON.stringify(bookJson));
        ctx.log(bookJson);
        ctx.log('src ' + src);
        ctx.log('dest ' + path);
        var gitbook = new Gitbook(src, {
            'config': {
                'output': path
            }
        });
        var output = yield this.generate(gitbook);
        ctx.log(output);
        yield shell.exec('cd '+src+' && ' +'git reset --hard');
        //删除生成的无用的gitbook目录
        yield shell.exec('cd '+path+' && ' +'rm -rf -r gitbook');
        if(output === true){
            ctx.log('build ok!');
            return {'success':true};
        }else{
            ctx.error(output);
            return {'success':false,'error':output};
        }
    },
    generate: function(gitbook){
        return new Promise(function(resolve){
            gitbook.parse().then(function() {
                return gitbook.generate('website');
            }).then(function(){
                resolve(true);
            }).catch(function(err){
                resolve(err);
            });
        });
    },
    //将文件push到oss存储
    pushOss: function*(){
        var user = this.user;
        var book = this.book;
        var oss = this.oss;
        var bucket = this.bucket;
        var path = this.dest+user+'/'+book;
        return yield oss.dir(path,'./'+user+'/'+book,bucket);
    },
    //拉取代码
    pull: function *(){
        var self = this;
        var user = this.user;
        var output;
        //不存在目录用户，先予以创建
        yield fse.ensureDir(this.src+user);
        //不存在仓库目录，先予以创建，并clone 代码
        var src = self.bookPath();
        var isExist = yield fse.exists(src);
        yield fse.ensureDir(src);
        if(!isExist){
            //克隆仓库
            output = yield this.clone(this.githubUrl,src);
        }else{
            output = yield shell.exec('cd '+src+' && git pull origin master');
        }

        //已经是最新
        if(/Already up-to-date/.test(output)){
            return {'success':true,'change':false,'msg':'不存在变更的内容',output:output};
        }else{
            return {'success':true,'change':true,output:output};
        }
    },
    //克隆仓库
    clone: function *(githubUrl, src){
        var result = yield shell.exec('cd '+src+' && git init && git remote add origin '+githubUrl);
        console.log(result);
        var output = yield shell.exec('cd '+src+' && git pull origin master');
        console.log(output);
        return output;
    },
    //github仓库是否符合book规范
    isBook: function *(){
        var self = this;
        var src = self.bookPath();
        var hasReadme = yield fs.exists(src + '/README.md');
        var hasSummary = yield fs.exists(src + '/SUMMARY.md');
        return hasReadme && hasSummary;
    },
    bookPath: function(){
        var user = this.user;
        var book = this.book;
        var path = user + '/'+book;
        return this.src + path;
    },
    //书籍介绍
    readMe: function*(){
        var src = this.bookPath();
        var url = src + '/' + 'README.md';
        return yield this.renderMd(url);
    },
    //书籍章节
    summary: function*(format){
        var src = this.bookPath();
        var url = src + '/' + 'SUMMARY.md';
        if(format && format === 'json'){
            return yield Summary.json(url);
        }else{
            return yield this.renderMd(url);
        }
    },
    /**
     * 图书更新的章节内容
     * @param updateLog
     * @param oldSummary
     */
    updateChapters: function*(updateLog,oldSummary){
        //var newSummary = yield this.summary('json');
        //yield Summary.updateData(updateLog,newSummary,oldSummary);
    },
    //章节数
    chapterCount: function*(){
        var src = this.bookPath();
        var url = src + '/' + 'SUMMARY.md';
        var exist = yield fs.exists(url);
        if(!exist) return 0;
        var content = yield fs.readFile(url);
        content = content.toString();
        return content.split('*').length-1;
    },
    //渲染md文件成html
    renderMd: function*(url){
        if(!url) return '';
        var exist = yield fs.exists(url);
        if(!exist) return '';
        var data = yield fs.readFile(url);
        data = data.toString();
        var tokens = marked.lexer(data);
        return marked.parser(tokens);
    },
    /**
     * 封面
     *
     */
    cover: function*(coverinfo,bookData,userData){
        var data = bookData;
        var user = data.userName;
        var book = data.uri;
        var output = this.dest+user+'/'+book+'/cover.jpg';
        var config = {
            title: data.name,
            author:userData && userData.nick || data.userName,
            bg:{},
            "size": {
                "w": 400,
                "h": 540
            }
        };

        //更新时间
        //不存在，使用创建时间
        if(data.updateTime){
            config.update = moment(Number(data.updateTime)).format('YYYY-MM-DD')+ ' update';
        }else{
            config.update = moment(Number(data.create)).format('YYYY-MM-DD')+ ' create';
        }

        if(coverinfo){
            //背景颜色
            if(coverinfo.color){
                config.bg.color = coverinfo.color;
            }

        }else{

            var bgColors = ['#7c8577','#999d9c','#9d9087','#74787c','#4f5555',
                '#6c4c49','#563624','#3e4145','#3c3645','#281f1d','#2f271d',
                '#1b315e','#596032','#ad8b3d'];

            var colorIndex = (parseInt(Math.random()*(14-1)+1))-1;
            config.bg.color = bgColors[colorIndex];
        }

        //是否存在封面背景图片
        var coverBg = this.src +user+'/'+book + '/' +'cover-bg.jpg';
        var existCoverBg = yield fse.exists(coverBg);
        if(existCoverBg){
            config.bg.image = coverBg;
        }
        try{
             yield cover.render(output,config);
        }catch(e){
            console.log(e);
            return false;
        }

        var path = user+'/'+book+'/cover.jpg';

        //返回封面数据
        return {
            ossPath: path,
            color: config.bg.color
        };
    }
};<commit_msg>暂时去掉搜索<commit_after>//书籍渲染库

var _ = require('underscore');
var shell = require('./shell');
var fse = require('co-fs-extra');
var fs = require('co-fs');
var marked = require('marked');
var Gitbook = require('gitbook').Book;
var moment = require('moment');
//生成封面
var cover = require('./cover/index');

//默认配置
var defaultConfig = {
    src: 'book-md/',
    dest: 'book-html/',
    themes:{
        apebook:'./theme/apebook',
        blog:'./theme/blog'
    },
    //默认启用的插件
    "plugins": ['-search']
};

var Book = module.exports = function (config) {
    var self = this;
    config = _.extend(defaultConfig,config);
    if (config) {
        _.each(config, function (value, key) {
            self[key] = value;
        });
    }
};

Book.prototype = {
    //渲染md成html
    render: function *(config) {
        var self = this;
        var ctx = self.ctx;
        var user = this.user;
        var book = this.book;
        var src = self.bookPath();
        var hasSrc = yield fs.exists(src);
        if(!hasSrc){
            return {'success':false,'msg':'不存在 '+book+' 目录'};
        }
        //确定绑定的仓库是否符合gitbook规范
        var isBook = yield this.isBook();
        if(!isBook){
            return {'success':false,'msg':'仓库缺少 SUMMARY.md 或者 README.md'};
        }
        yield fse.ensureDir(self.dest+user);
        var path = self.dest+user+'/'+book;
        yield fse.ensureDir(path);
        //图书配置
        var bookJson = {};
        bookJson.theme = config && config.theme || self.themes['apebook'];
        bookJson.output = path;
        var data = this.data;
        bookJson.githubUser = data.githubUser;
        bookJson.githubRepo = data.githubRepo;
        bookJson.bookId = data.id;
        bookJson.bookName = book;
        bookJson.apebookHost = this.apebookHost;
        bookJson.assetHost = this.assetHost;
        bookJson.desc = data.desc;
        //本地调试环境
        if(process.env.NODE_ENV !== 'local'){
            bookJson.localAssetHost = bookJson.assetHost;
        }

        bookJson.plugins = this.plugins;
        yield fse.writeFile(src+'/book.json',JSON.stringify(bookJson));
        ctx.log(bookJson);
        ctx.log('src ' + src);
        ctx.log('dest ' + path);
        var gitbook = new Gitbook(src, {
            'config': {
                'output': path
            }
        });
        var output = yield this.generate(gitbook);
        ctx.log(output);
        yield shell.exec('cd '+src+' && ' +'git reset --hard');
        //删除生成的无用的gitbook目录
        yield shell.exec('cd '+path+' && ' +'rm -rf -r gitbook');
        if(output === true){
            ctx.log('build ok!');
            return {'success':true};
        }else{
            ctx.error(output);
            return {'success':false,'error':output};
        }
    },
    generate: function(gitbook){
        return new Promise(function(resolve){
            gitbook.parse().then(function() {
                return gitbook.generate('website');
            }).then(function(){
                resolve(true);
            }).catch(function(err){
                resolve(err);
            });
        });
    },
    //将文件push到oss存储
    pushOss: function*(){
        var user = this.user;
        var book = this.book;
        var oss = this.oss;
        var bucket = this.bucket;
        var path = this.dest+user+'/'+book;
        return yield oss.dir(path,'./'+user+'/'+book,bucket);
    },
    //拉取代码
    pull: function *(){
        var self = this;
        var user = this.user;
        var output;
        //不存在目录用户，先予以创建
        yield fse.ensureDir(this.src+user);
        //不存在仓库目录，先予以创建，并clone 代码
        var src = self.bookPath();
        var isExist = yield fse.exists(src);
        yield fse.ensureDir(src);
        if(!isExist){
            //克隆仓库
            output = yield this.clone(this.githubUrl,src);
        }else{
            output = yield shell.exec('cd '+src+' && git pull origin master');
        }

        //已经是最新
        if(/Already up-to-date/.test(output)){
            return {'success':true,'change':false,'msg':'不存在变更的内容',output:output};
        }else{
            return {'success':true,'change':true,output:output};
        }
    },
    //克隆仓库
    clone: function *(githubUrl, src){
        var result = yield shell.exec('cd '+src+' && git init && git remote add origin '+githubUrl);
        console.log(result);
        var output = yield shell.exec('cd '+src+' && git pull origin master');
        console.log(output);
        return output;
    },
    //github仓库是否符合book规范
    isBook: function *(){
        var self = this;
        var src = self.bookPath();
        var hasReadme = yield fs.exists(src + '/README.md');
        var hasSummary = yield fs.exists(src + '/SUMMARY.md');
        return hasReadme && hasSummary;
    },
    bookPath: function(){
        var user = this.user;
        var book = this.book;
        var path = user + '/'+book;
        return this.src + path;
    },
    //书籍介绍
    readMe: function*(){
        var src = this.bookPath();
        var url = src + '/' + 'README.md';
        return yield this.renderMd(url);
    },
    //书籍章节
    summary: function*(format){
        var src = this.bookPath();
        var url = src + '/' + 'SUMMARY.md';
        if(format && format === 'json'){
            return yield Summary.json(url);
        }else{
            return yield this.renderMd(url);
        }
    },
    /**
     * 图书更新的章节内容
     * @param updateLog
     * @param oldSummary
     */
    updateChapters: function*(updateLog,oldSummary){
        //var newSummary = yield this.summary('json');
        //yield Summary.updateData(updateLog,newSummary,oldSummary);
    },
    //章节数
    chapterCount: function*(){
        var src = this.bookPath();
        var url = src + '/' + 'SUMMARY.md';
        var exist = yield fs.exists(url);
        if(!exist) return 0;
        var content = yield fs.readFile(url);
        content = content.toString();
        return content.split('*').length-1;
    },
    //渲染md文件成html
    renderMd: function*(url){
        if(!url) return '';
        var exist = yield fs.exists(url);
        if(!exist) return '';
        var data = yield fs.readFile(url);
        data = data.toString();
        var tokens = marked.lexer(data);
        return marked.parser(tokens);
    },
    /**
     * 封面
     *
     */
    cover: function*(coverinfo,bookData,userData){
        var data = bookData;
        var user = data.userName;
        var book = data.uri;
        var output = this.dest+user+'/'+book+'/cover.jpg';
        var config = {
            title: data.name,
            author:userData && userData.nick || data.userName,
            bg:{},
            "size": {
                "w": 400,
                "h": 540
            }
        };

        //更新时间
        //不存在，使用创建时间
        if(data.updateTime){
            config.update = moment(Number(data.updateTime)).format('YYYY-MM-DD')+ ' update';
        }else{
            config.update = moment(Number(data.create)).format('YYYY-MM-DD')+ ' create';
        }

        if(coverinfo){
            //背景颜色
            if(coverinfo.color){
                config.bg.color = coverinfo.color;
            }

        }else{

            var bgColors = ['#7c8577','#999d9c','#9d9087','#74787c','#4f5555',
                '#6c4c49','#563624','#3e4145','#3c3645','#281f1d','#2f271d',
                '#1b315e','#596032','#ad8b3d'];

            var colorIndex = (parseInt(Math.random()*(14-1)+1))-1;
            config.bg.color = bgColors[colorIndex];
        }

        //是否存在封面背景图片
        var coverBg = this.src +user+'/'+book + '/' +'cover-bg.jpg';
        var existCoverBg = yield fse.exists(coverBg);
        if(existCoverBg){
            config.bg.image = coverBg;
        }
        try{
             yield cover.render(output,config);
        }catch(e){
            console.log(e);
            return false;
        }

        var path = user+'/'+book+'/cover.jpg';

        //返回封面数据
        return {
            ossPath: path,
            color: config.bg.color
        };
    }
};<|endoftext|>


<commit_before>var Architect = {};

Architect.action = function(name, cb){
  elements = Architect.find(name);
  values = Architect.getValue(name);
  for (var i = 0; i < elements.length; i ++){
    cb(elements[i], values[i]);
  }
};

Architect.find = function(name){
  return document.querySelectorAll('*[data-' + name + ']') || [];
};

Architect.getValue = function(name){
  ret = [];
  elements = Architect.find(name);
  for (var i = 0; i < elements.length; i ++){
    ret.push(elements[i].attributes[0].value);
  }
  return ret;
}

<commit_msg>Added removeAttribute method and documentation<commit_after>var Architect = {};

Architect.action = function(name, cb){
  elements = Architect.find(name);
  values = Architect.getValue(name);
  for (var i = 0; i < elements.length; i ++){
    cb(elements[i], values[i]);
  }
  return elements;
};

Architect.find = function(name){
  return document.querySelectorAll('*[data-' + name + ']') || [];
};

Architect.getValue = function(name){
  ret = [];
  elements = Architect.find(name);
  for (var i = 0; i < elements.length; i ++){
    ret.push(elements[i].attributes[0].value);
  }
  return ret;
}

Architect.removeAttribute = function(element, name){
  for (var i = 0; i < element.attributes.length; i++){
    if (element.attributes[i].name === 'data-' + name){
      element.removeAttribute(element.attributes[i].name);
    }
  }
  return element;
}
<|endoftext|>


<commit_before>const models = require('../../../models');
const _ = require('lodash');
const async = require('async');
const log = require('../../../utils/logger');
const importDomain = require('./utils').importDomain;
const importCommunity = require('./utils').importCommunity;
const importGroup = require('./utils').importGroup;
const importPost = require('./utils').importPost;
const importPoint = require('./utils').importPoint;

let updateAsyncLimit = 16;

let lineCrCounter = 0;

const processDots = () => {
  if (lineCrCounter>250) {
    process.stdout.write("\n");
    lineCrCounter = 1;
  } else {
    process.stdout.write(".");
    lineCrCounter += 1;
  }
};

const importAllDomains = (done) => {
  log.info('AcSimilarityDomainImport', {});

  models.Domain.unscoped().findAll({
        attributes: ['id','name','default_locale'],
        order: [
          ['id', 'asc' ]
        ]
      }).then((domains) => {
    lineCrCounter = 0;
    async.eachOfLimit(domains, updateAsyncLimit, (domain, index, callback) => {
      importDomain(domain, callback);
    }, () => {
      console.log("Finished updating domains");
      done();
    });
  }).catch(function (error) {
    done(error);
  });
};

const importAllCommunities = (done) => {
  log.info('AcSimilarityCommunityImport', {});

  models.Community.unscoped().findAll({
    include: [
      {
        model: models.Domain,
        attributes: ['id','default_locale'],
        required: true
      }
    ],
    attributes: ['id','name','default_locale'],
    order: [
      ['id', 'asc' ]
    ]
  }).then((communities) => {
    lineCrCounter = 0;
    async.eachOfLimit(communities, updateAsyncLimit, (community, index, callback) => {
      importCommunity(community, callback);
    }, () => {
      console.log("Finished updating communities");
      done();
    });
  }).catch(function (error) {
    done(error);
  });
};

const importAllGroups = (done) => {
  log.info('AcSimilarityGroupImport', {});

  models.Group.unscoped().findAll({
    include: [
      {
        model: models.Community,
        attributes: ['id','access','status','default_locale'],
        required: true,
        include: [
          {
            model: models.Domain,
            attributes: ['id','default_locale'],
            required: true
          }
        ]
      }
    ],
    attributes: ['id','name'],
    order: [
      ['id', 'asc' ]
    ]
  }).then((groups) => {
    lineCrCounter = 0;
    async.eachOfLimit(groups, updateAsyncLimit, (group, index, callback) => {
      importGroup(group, callback);
    }, () => {
      console.log("Finished updating communities");
      done();
    });
  }).catch(function (error) {
    done(error);
  });
};

const importAllPosts = (done) => {
  log.info('AcSimilarityImport', {});

  models.Post.unscoped().findAll(
    {
      include: [
        {
          model: models.Point,
          required: false,
          attributes: ['id','content'],
        },
        {
          model: models.Group,
          required: true,
          attributes: ['id','access','status','configuration'],
          include: [
            {
              attributes: ['id','formats'],
              model: models.Image, as: 'GroupLogoImages',
              required: false
            },
            {
              model: models.Community,
              attributes: ['id','access','status','default_locale'],
              required: true,
              include: [
                {
                  attributes: ['id','formats'],
                  model: models.Image, as: 'CommunityLogoImages',
                  required: false
                },
                {
                  model: models.Domain,
                  attributes: ['id','default_locale'],
                  required: true
                }
              ]
            }
          ]
        },
        {
          model: models.Image,
          required: false,
          as: 'PostHeaderImages',
          attributes: ['id','formats']
        },
        {
          model: models.Video,
          required: false,
          attributes: ['id','formats','updated_at','viewable','public_meta'],
          as: 'PostVideos',
          include: [
            {
              model: models.Image,
              as: 'VideoImages',
              attributes:["formats",'updated_at'],
              required: false
            },
          ]
        },
        {
          model: models.Audio,
          required: false,
          attributes: ['id','formats','updated_at','listenable'],
          as: 'PostAudios',
        }
      ],
      order: [
        ['id', 'desc' ],
        [ { model: models.Image, as: 'PostHeaderImages' } ,'updated_at', 'asc' ],
        [ { model: models.Group }, { model: models.Image, as: 'GroupLogoImages' } , 'created_at', 'desc' ],
        [ { model: models.Group }, { model: models.Community }, { model: models.Image, as: 'CommunityLogoImages' } , 'created_at', 'desc' ]
      ],
      attributes: ['id','name','description','group_id','category_id','status','deleted','language','created_at',
                   'user_id','official_status','public_data','cover_media_type',
                   'counter_endorsements_up','counter_endorsements_down','counter_points','counter_flags']
    }).then((posts) => {
    lineCrCounter = 0;
    async.eachOfLimit(posts, updateAsyncLimit, (post, index, callback) => {
      importPost(post, callback);
    }, () => {
      console.log("Finished updating posts");
      done();
    });
  }).catch(function (error) {
    done(error);
  });
};

const importAllPoints = (done) => {
  models.Point.unscoped().findAll({
    attributes: ['id', 'name', 'content', 'user_id', 'post_id', 'value', 'status', 'counter_quality_up', 'counter_quality_down', 'language', 'created_at'],
    order: [
      [models.PointRevision, 'created_at', 'asc'],
      [{model: models.Video, as: "PointVideos"}, 'updated_at', 'desc'],
      [{model: models.Audio, as: "PointAudios"}, 'updated_at', 'desc'],
    ],
    include: [
      {
        model: models.PointRevision,
        attributes: ['content', 'value', 'created_at'],
        required: false
      },
      {
        model: models.Video,
        required: false,
        attributes: ['id', 'formats'],
        as: 'PointVideos'
      },
      {
        model: models.Audio,
        required: false,
        attributes: ['id', 'formats'],
        as: 'PointAudios'
      },
      {
        model: models.Post,
        attributes: ['id', 'group_id','created_at','category_id','official_status','status'],
        required: true,
        include: [
          {
            model: models.Group,
            attributes: ['id','access','status','configuration'],
            required: true,
            include: [
              {
                model: models.Community,
                attributes: ['id','access','status','default_locale'],
                required: true,
                include: [
                  {
                    model: models.Domain,
                    attributes: ['id','default_locale'],
                    required: true
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }).then(function (points) {
    lineCrCounter = 0;
    async.eachOfLimit(points, updateAsyncLimit, (point, index, callback) => {
      importPoint(point, callback);
    }, () => {
      console.log("Finished updating posts");
      done();
    });
  }).catch(function (error) {
    done(error);
  });
};

const importAll = (done) => {
  async.series([
    (callback) => {
      importAllDomains((error) => {
        callback(error);
      });
    },
    (callback) => {
      importAllCommunities((error) => {
        callback(error);
      });
    },
    (callback) => {
      importAllGroups((error) => {
        callback(error);
      });
    },
    /*
    (callback) => {
      importAllPosts((error) => {
        callback(error);
      });
    },
    (callback) => {
      importAllPoints((error) => {
        callback(error);
      });
    }*/
  ], (error) => {
    console.log("Finished importing all");
    if (error)
      console.error(error);
    done();
  });
};

if (process.env["AC_ANALYTICS_KEY"] && process.env["AC_ANALYTICS_BASE_URL"] ) {
  log.info('AcSimilarityImportStarting', {});
  if (process.argv[2] && process.argv[2]==="onlyUpdatePosts") {
    updateAsyncLimit = 8;
    importAllPosts(() => {
      console.log("Done updating posts");
      process.exit();
    });
  } else {
    importAll(() => {
      console.log("Done importing all");
      process.exit();
    });
  }
} else {
  console.error("NO AC_ANALYTICS_KEY");
  process.exit();
}
<commit_msg>Work on similarities engine<commit_after>const models = require('../../../models');
const _ = require('lodash');
const async = require('async');
const log = require('../../../utils/logger');
const importDomain = require('./utils').importDomain;
const importCommunity = require('./utils').importCommunity;
const importGroup = require('./utils').importGroup;
const importPost = require('./utils').importPost;
const importPoint = require('./utils').importPoint;

let updateAsyncLimit = 16;

let lineCrCounter = 0;

const processDots = () => {
  if (lineCrCounter>250) {
    process.stdout.write("\n");
    lineCrCounter = 1;
  } else {
    process.stdout.write(".");
    lineCrCounter += 1;
  }
};

const importAllDomains = (done) => {
  log.info('AcSimilarityDomainImport', {});

  models.Domain.unscoped().findAll({
        attributes: ['id','name','default_locale'],
        order: [
          ['id', 'asc' ]
        ]
      }).then((domains) => {
    lineCrCounter = 0;
    async.eachOfLimit(domains, updateAsyncLimit, (domain, index, callback) => {
      importDomain(domain, callback);
    }, () => {
      console.log("Finished updating domains");
      done();
    });
  }).catch(function (error) {
    done(error);
  });
};

const importAllCommunities = (done) => {
  log.info('AcSimilarityCommunityImport', {});

  models.Community.unscoped().findAll({
    include: [
      {
        model: models.Domain,
        attributes: ['id','default_locale'],
        required: true
      }
    ],
    attributes: ['id','name','default_locale'],
    order: [
      ['id', 'asc' ]
    ]
  }).then((communities) => {
    lineCrCounter = 0;
    async.eachOfLimit(communities, updateAsyncLimit, (community, index, callback) => {
      importCommunity(community, callback);
    }, () => {
      console.log("Finished updating communities");
      done();
    });
  }).catch(function (error) {
    done(error);
  });
};

const importAllGroups = (done) => {
  log.info('AcSimilarityGroupImport', {});

  models.Group.unscoped().findAll({
    include: [
      {
        model: models.Community,
        attributes: ['id','access','status','default_locale'],
        required: true,
        include: [
          {
            model: models.Domain,
            attributes: ['id','default_locale'],
            required: true
          }
        ]
      }
    ],
    attributes: ['id','name'],
    order: [
      ['id', 'asc' ]
    ]
  }).then((groups) => {
    lineCrCounter = 0;
    async.eachOfLimit(groups, updateAsyncLimit, (group, index, callback) => {
      importGroup(group, callback);
    }, () => {
      console.log("Finished updating communities");
      done();
    });
  }).catch(function (error) {
    done(error);
  });
};

const importAllPosts = (done) => {
  log.info('AcSimilarityImport', {});

  models.Post.unscoped().findAll(
    {
      include: [
        {
          model: models.Point,
          required: false,
          attributes: ['id','content'],
        },
        {
          model: models.Group,
          required: true,
          attributes: ['id','access','status','configuration'],
          include: [
            {
              attributes: ['id','formats'],
              model: models.Image, as: 'GroupLogoImages',
              required: false
            },
            {
              model: models.Community,
              attributes: ['id','access','status','default_locale'],
              required: true,
              include: [
                {
                  attributes: ['id','formats'],
                  model: models.Image, as: 'CommunityLogoImages',
                  required: false
                },
                {
                  model: models.Domain,
                  attributes: ['id','default_locale'],
                  required: true
                }
              ]
            }
          ]
        },
        {
          model: models.Image,
          required: false,
          as: 'PostHeaderImages',
          attributes: ['id','formats']
        },
        {
          model: models.Video,
          required: false,
          attributes: ['id','formats','updated_at','viewable','public_meta'],
          as: 'PostVideos',
          include: [
            {
              model: models.Image,
              as: 'VideoImages',
              attributes:["formats",'updated_at'],
              required: false
            },
          ]
        },
        {
          model: models.Audio,
          required: false,
          attributes: ['id','formats','updated_at','listenable'],
          as: 'PostAudios',
        }
      ],
      order: [
        ['id', 'desc' ],
        [ { model: models.Image, as: 'PostHeaderImages' } ,'updated_at', 'asc' ],
        [ { model: models.Group }, { model: models.Image, as: 'GroupLogoImages' } , 'created_at', 'desc' ],
        [ { model: models.Group }, { model: models.Community }, { model: models.Image, as: 'CommunityLogoImages' } , 'created_at', 'desc' ]
      ],
      attributes: ['id','name','description','group_id','category_id','status','deleted','language','created_at',
                   'user_id','official_status','public_data','cover_media_type',
                   'counter_endorsements_up','counter_endorsements_down','counter_points','counter_flags']
    }).then((posts) => {
    lineCrCounter = 0;
    async.eachOfLimit(posts, updateAsyncLimit, (post, index, callback) => {
      importPost(post, callback);
    }, () => {
      console.log("Finished updating posts");
      done();
    });
  }).catch(function (error) {
    done(error);
  });
};

const importAllPoints = (done) => {
  models.Point.unscoped().findAll({
    attributes: ['id', 'name', 'content', 'user_id', 'post_id', 'value', 'status', 'counter_quality_up', 'counter_quality_down', 'language', 'created_at'],
    order: [
      [models.PointRevision, 'created_at', 'asc'],
      [{model: models.Video, as: "PointVideos"}, 'updated_at', 'desc'],
      [{model: models.Audio, as: "PointAudios"}, 'updated_at', 'desc'],
    ],
    include: [
      {
        model: models.PointRevision,
        attributes: ['content', 'value', 'created_at'],
        required: false
      },
      {
        model: models.Video,
        required: false,
        attributes: ['id', 'formats'],
        as: 'PointVideos'
      },
      {
        model: models.Audio,
        required: false,
        attributes: ['id', 'formats'],
        as: 'PointAudios'
      },
      {
        model: models.Post,
        attributes: ['id', 'group_id','created_at','category_id','official_status','status'],
        required: true,
        include: [
          {
            model: models.Group,
            attributes: ['id','access','status','configuration'],
            required: true,
            include: [
              {
                model: models.Community,
                attributes: ['id','access','status','default_locale'],
                required: true,
                include: [
                  {
                    model: models.Domain,
                    attributes: ['id','default_locale'],
                    required: true
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }).then(function (points) {
    lineCrCounter = 0;
    async.eachOfLimit(points, updateAsyncLimit, (point, index, callback) => {
      importPoint(point, callback);
    }, () => {
      console.log("Finished updating posts");
      done();
    });
  }).catch(function (error) {
    done(error);
  });
};

const importAll = (done) => {
  async.series([
    /*
    (callback) => {
      importAllDomains((error) => {
        callback(error);
      });
    },
    (callback) => {
      importAllCommunities((error) => {
        callback(error);
      });
    },
    (callback) => {
      importAllGroups((error) => {
        callback(error);
      });
    },
    */
    (callback) => {
      importAllPosts((error) => {
        callback(error);
      });
    },
    (callback) => {
      importAllPoints((error) => {
        callback(error);
      })
    }
  ], (error) => {
    console.log("Finished importing all");
    if (error)
      console.error(error);
    done();
  });
};

if (process.env["AC_ANALYTICS_KEY"] && process.env["AC_ANALYTICS_BASE_URL"] ) {
  log.info('AcSimilarityImportStarting', {});
  if (process.argv[2] && process.argv[2]==="onlyUpdatePosts") {
    updateAsyncLimit = 8;
    importAllPosts(() => {
      console.log("Done updating posts");
      process.exit();
    });
  } else {
    importAll(() => {
      console.log("Done importing all");
      process.exit();
    });
  }
} else {
  console.error("NO AC_ANALYTICS_KEY");
  process.exit();
}
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { View, Animated } from 'react-native';
import CircularProgress from './CircularProgress';
const AnimatedProgress = Animated.createAnimatedComponent(CircularProgress);

export default class AnimatedCircularProgress extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      chartFillAnimation: new Animated.Value(props.prefill || 0)
    }
  }

  componentDidMount() {
    this.animateFill();
  }

  componentDidUpdate(prevProps) {
    if (prevProps.fill !== this.props.fill) {
      this.animateFill();
    }
  }

  animateFill() {
    const { tension, friction } = this.props;

    Animated.spring(
      this.state.chartFillAnimation,
      {
        toValue: this.props.fill,
        tension,
        friction
      }
    ).start();
  }

  performLinearAnimation(toValue, duration) {
    Animated.timing(this.state.chartFillAnimation, {
      toValue: toValue,
      duration: duration
    }).start();
  }

  render() {
    const { fill, prefill, ...other } = this.props;

    return (
      <AnimatedProgress
        {...other}
        fill={this.state.chartFillAnimation}
        />
    )
  }
}

AnimatedCircularProgress.propTypes = {
  style: View.propTypes.style,
  size: PropTypes.number.isRequired,
  fill: PropTypes.number,
  prefill: PropTypes.number,
  width: PropTypes.number.isRequired,
  tintColor: PropTypes.string,
  backgroundColor: PropTypes.string,
  tension: PropTypes.number,
  friction: PropTypes.number
}

AnimatedCircularProgress.defaultProps = {
  tension: 7,
  friction: 10
};
<commit_msg>tintColor, backgroundColor could be string or object in form of Animated Value<commit_after>import React, { PropTypes } from 'react';
import { View, Animated } from 'react-native';
import CircularProgress from './CircularProgress';
const AnimatedProgress = Animated.createAnimatedComponent(CircularProgress);

export default class AnimatedCircularProgress extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      chartFillAnimation: new Animated.Value(props.prefill || 0)
    }
  }

  componentDidMount() {
    this.animateFill();
  }

  componentDidUpdate(prevProps) {
    if (prevProps.fill !== this.props.fill) {
      this.animateFill();
    }
  }

  animateFill() {
    const { tension, friction } = this.props;

    Animated.spring(
      this.state.chartFillAnimation,
      {
        toValue: this.props.fill,
        tension,
        friction
      }
    ).start();
  }

  performLinearAnimation(toValue, duration) {
    Animated.timing(this.state.chartFillAnimation, {
      toValue: toValue,
      duration: duration
    }).start();
  }

  render() {
    const { fill, prefill, ...other } = this.props;

    return (
      <AnimatedProgress
        {...other}
        fill={this.state.chartFillAnimation}
        />
    )
  }
}

AnimatedCircularProgress.propTypes = {
  style: View.propTypes.style,
  size: PropTypes.number.isRequired,
  fill: PropTypes.number,
  prefill: PropTypes.number,
  width: PropTypes.number.isRequired,
  tintColor: PropTypes.oneOf([PropTypes.string, PropTypes.object]),
  backgroundColor: PropTypes.oneOf([PropTypes.string, PropTypes.object]),
  tension: PropTypes.number,
  friction: PropTypes.number
}

AnimatedCircularProgress.defaultProps = {
  tension: 7,
  friction: 10
};
<|endoftext|>


<commit_before>App.addChild('Contribution', {
  el: '#new-contribution',

  events: {
    'click .radio label' : 'clickReward',
    'click .submit-form' : 'submitForm',
    'input #contribution_value' : 'restrictChars'
  },

  restrictChars: function(event){
    var $target = $(event.target);
    $target.val($target.val().replace(/[^\d,]/, ''));
  },

  submitForm: function(){
    var user_value = this.$('.selected').find('.user-reward-value').val();
    var default_value = this.$('.selected').find('label[data-minimum-value]').data('minimum-value');
    this.$value.val(user_value || default_value);
    this.$('form').submit();
    return false;
  },

  activate: function(){
    this.$('.user-reward-value').mask('000.000.000,00', {reverse: true});
    this.$value = this.$('#contribution_value');
    this.$minimum = this.$('#minimum-value');
    this.clickReward({currentTarget: this.$('input[type=radio]:checked').parent()[0]});
    this.activateFloattingHeader();
  },

  activateFloattingHeader: function(){
    var top;
    var top_title = $('#new-contribution'),
    faq_top = $("#faq-box").offset().top;
    $(window).scroll(function() {
        top = $(top_title).offset().top,
        $(window).scrollTop() > top ? $(".reward-floating").addClass("reward-floating-display") : $(".reward-floating").removeClass("reward-floating-display");
        var t = $("#faq-box");
        $(window).scrollTop() > faq_top ? $(t).hasClass("faq-card-fixed") || $(t).addClass("faq-card-fixed") : $(t).hasClass("faq-card-fixed") && $(t).removeClass("faq-card-fixed")
    });
  },

  resetReward: function(event){
    if(parseInt('0' + this.$value.val()) < this.minimumValue()){
      this.selectReward(this.$('.radio label'));
    }
  },

  minimumValue: function(){
    return this.$('.selected').find('label[data-minimum-value]').data('minimum-value');
  },

  resetSelected: function(){
    this.$('.w-radio').removeClass('selected');
  },

  selectReward: function(reward){
    this.resetSelected();
    reward.find('input[type=radio]').prop('checked', true);
    this.$('.back-reward-money').hide();
    reward.find('.back-reward-money').show();
    reward.parent().addClass('selected');

  },

  clickReward: function(event){
    this.selectReward($(event.currentTarget));
    var minimum = this.minimumValue();
    this.$value.val(minimum);
    this.$minimum.html(minimum);
  }
});

App.addChild('FaqBox', {
  el: '#faq-box',

  events: {
    'click li.list-question' : 'clickQuestion'
  },

  clickQuestion: function(event){
    var $question = $(event.currentTarget);
    var $answer = $question.next();
    $question.toggleClass('open').toggleClass('alt-link');
    $answer.slideToggle('slow');
  },

  activate: function(){
    this.$('li.list-answer').hide();
  }
});
<commit_msg>Adjusts fixed faq box trigger<commit_after>App.addChild('Contribution', {
  el: '#new-contribution',

  events: {
    'click .radio label' : 'clickReward',
    'click .submit-form' : 'submitForm',
    'input #contribution_value' : 'restrictChars'
  },

  restrictChars: function(event){
    var $target = $(event.target);
    $target.val($target.val().replace(/[^\d,]/, ''));
  },

  submitForm: function(){
    var user_value = this.$('.selected').find('.user-reward-value').val();
    var default_value = this.$('.selected').find('label[data-minimum-value]').data('minimum-value');
    this.$value.val(user_value || default_value);
    this.$('form').submit();
    return false;
  },

  activate: function(){
    this.$('.user-reward-value').mask('000.000.000,00', {reverse: true});
    this.$value = this.$('#contribution_value');
    this.$minimum = this.$('#minimum-value');
    this.clickReward({currentTarget: this.$('input[type=radio]:checked').parent()[0]});
    this.activateFloattingHeader();
  },

  activateFloattingHeader: function(){
    var top;
    var top_title = $('#new-contribution'),
    faq_top = $("#faq-box").offset().top;
    $(window).scroll(function() {
        top = $(top_title).offset().top,
        $(window).scrollTop() > top ? $(".reward-floating").addClass("reward-floating-display") : $(".reward-floating").removeClass("reward-floating-display");
        var t = $("#faq-box");
        $(window).scrollTop() > faq_top-130 ? $(t).hasClass("faq-card-fixed") || $(t).addClass("faq-card-fixed") : $(t).hasClass("faq-card-fixed") && $(t).removeClass("faq-card-fixed")
    });
  },

  resetReward: function(event){
    if(parseInt('0' + this.$value.val()) < this.minimumValue()){
      this.selectReward(this.$('.radio label'));
    }
  },

  minimumValue: function(){
    return this.$('.selected').find('label[data-minimum-value]').data('minimum-value');
  },

  resetSelected: function(){
    this.$('.w-radio').removeClass('selected');
  },

  selectReward: function(reward){
    this.resetSelected();
    reward.find('input[type=radio]').prop('checked', true);
    this.$('.back-reward-money').hide();
    reward.find('.back-reward-money').show();
    reward.parent().addClass('selected');

  },

  clickReward: function(event){
    this.selectReward($(event.currentTarget));
    var minimum = this.minimumValue();
    this.$value.val(minimum);
    this.$minimum.html(minimum);
  }
});

App.addChild('FaqBox', {
  el: '#faq-box',

  events: {
    'click li.list-question' : 'clickQuestion'
  },

  clickQuestion: function(event){
    var $question = $(event.currentTarget);
    var $answer = $question.next();
    $question.toggleClass('open').toggleClass('alt-link');
    $answer.slideToggle('slow');
  },

  activate: function(){
    this.$('li.list-answer').hide();
  }
});
<|endoftext|>


<commit_before>$(function() {
  var container = $(".document .govspeak"),
      navigation = $(".contextual-info #document_sections"),
      mainstreamAlternative = $('.related-mainstream-content'),
      pages, headings, navigationLinks;

  var paginating = ($('.js-paginate-document').length > 0 && $(window).width() > 768);

  navigation.find(">li").each(function(el){
    var li = $(this),
        pageNav = li.find('>ol'),
        chapterSelector = '#' + li.find('>a').attr('href').split('#')[1],
        inPageNavigation = $("

On this page

");

    pageNav.remove();

    if (pageNav.length > 0 && paginating) {
      inPageNavigation.find('nav').append(pageNav);
      $(chapterSelector).after(inPageNavigation);
    };
  });

  if(mainstreamAlternative.length){
    mainstreamAlternative.insertAfter(container.children().get(1));
  }

  if (paginating) {
    container.splitIntoPages("h2");
    pages = container.find(".page");
    headings = container.find('h2');
    navigationLinks = navigation.find('a');

    var showPage = function(a) {
      var page = $(location.hash).parents(".page");
      var pageId = $(page).find('h2').attr('id')

      pages.not(page).addClass('hidden');
      navigationLinks.removeClass('active');

      if (page.length == 0) {
        pages.first().removeClass('hidden');
        navigationLinks.first().addClass('active')
      } else {
        page.removeClass('hidden');
        navigationLinks.filter('a[href$='+pageId+']').addClass('active');
        if (location.hash == ('#' + pageId)) {
          // html and body selector for IE 8.
          $('html, body').animate({scrollTop:0}, 0);
        }
      }
    }

    pages.each(function(i, el){
      var currentPage = $(el),
          prevNextNavigation = [],
          adjacentPage;

      // if there is a previous page
      if(i > 0){
        adjacentPage = $(headings.get(i-1));
        prevNextNavigation.push('
Previous page '+adjacentPage.text()+'
');
      }
      if(i < pages.length-1){
        adjacentPage = $(headings.get(i+1));
        prevNextNavigation.push('
Next page '+adjacentPage.text()+'
');
      }

      currentPage.append('
' + prevNextNavigation.join('') + '
');
    });

    $(window).hashchange(showPage);
    $(window).hashchange();
  }
})
<commit_msg>Links to specialist guidance footnotes should go to those footnotes<commit_after>$(function() {
  var container = $(".document .govspeak"),
      navigation = $(".contextual-info #document_sections"),
      mainstreamAlternative = $('.related-mainstream-content'),
      pages, headings, navigationLinks;

  var paginating = ($('.js-paginate-document').length > 0 && $(window).width() > 768);

  var escapeId = function(id) {
    return id.replace(/(:|\.)/g,'\\$1');
  }

  navigation.find(">li").each(function(el){
    var li = $(this),
        pageNav = li.find('>ol'),
        chapterSelector = '#' + li.find('>a').attr('href').split('#')[1],
        inPageNavigation = $("

On this page

");

    pageNav.remove();

    if (pageNav.length > 0 && paginating) {
      inPageNavigation.find('nav').append(pageNav);
      $(chapterSelector).after(inPageNavigation);
    };
  });

  if(mainstreamAlternative.length){
    mainstreamAlternative.insertAfter(container.children().get(1));
  }

  if (paginating) {
    container.splitIntoPages("h2");
    pages = container.find(".page");
    headings = container.find('h2');
    navigationLinks = navigation.find('a');

    var showPage = function(a) {
      var page = $(escapeId(location.hash)).parents(".page");
      var pageId = $(page).find('h2').attr('id')

      pages.not(page).addClass('hidden');
      navigationLinks.removeClass('active');

      if (page.length == 0) {
        pages.first().removeClass('hidden');
        navigationLinks.first().addClass('active')
      } else {
        page.removeClass('hidden');
        navigationLinks.filter('a[href$='+pageId+']').addClass('active');
        if (location.hash == ('#' + pageId)) {
          // html and body selector for IE 8.
          $('html, body').animate({scrollTop:0}, 0);
        } else {
          // This looks mad, but forces the browser to scroll to the anchor that may have been
          // invisible when the link was first clicked.  A footnote, for example.
          document.location = document.location
        }
      }
    }

    pages.each(function(i, el){
      var currentPage = $(el),
          prevNextNavigation = [],
          adjacentPage;

      // if there is a previous page
      if(i > 0){
        adjacentPage = $(headings.get(i-1));
        prevNextNavigation.push('
Previous page '+adjacentPage.text()+'
');
      }
      if(i < pages.length-1){
        adjacentPage = $(headings.get(i+1));
        prevNextNavigation.push('
Next page '+adjacentPage.text()+'
');
      }

      currentPage.append('
' + prevNextNavigation.join('') + '
');
    });

    $(window).hashchange(showPage);
    $(window).hashchange();
  }
})
<|endoftext|>


<commit_before>class ApplicationConfiguration {
    constructor() {
        this.configuratiun = require('./config.json');
    }

    get ApiEndpoint() {
        return this.configuratiun.ApiEndpoint;
    }

    get OldUIAddress() {
        return this.configuratiun.OldUIAddress;
    }

    get LoginPageAddress() {
        return this.configuratiun.LoginPageAddress;
    }
}

export default new ApplicationConfiguration();
<commit_msg>Update configuratiun<commit_after>class ApplicationConfiguration {
    constructor() {
        this.configuratiun = require('/config.json');
        console.log(this.configuratiun);
    }

    get ApiEndpoint() {
        return this.configuratiun.ApiEndpoint;
    }

    get OldUIAddress() {
        return this.configuratiun.OldUIAddress;
    }

    get LoginPageAddress() {
        return this.configuratiun.LoginPageAddress;
    }
}

export default new ApplicationConfiguration();
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';
import moment from 'moment';
import {studentProfile} from './fixtures/fixtures';
import StudentProfileHeader from './StudentProfileHeader';

const helpers = {
  renderActiveStudent(el, props) {
    const mergedProps = {
      student: studentProfile.student,
      ...props
    };
    ReactDOM.render(<StudentProfileHeader {...mergedProps} />, el);
  },

  renderTransferredStudent(el, props) {
    const this_student = studentProfile.student;
    this_student['enrollment_status'] = 'Transferred';

    const mergedProps = {
      student: this_student,
      ...props
    };
    ReactDOM.render(<StudentProfileHeader {...mergedProps} />, el);
  }

};

describe('active enrolled student', () => {
  it('renders note-taking area with homeroom', () => {
    const el = document.createElement('div');
    helpers.renderActiveStudent(el, {districtKey: 'somerville'});
    const yearsOld = moment().diff(studentProfile.student.date_of_birth, 'years'); // TODO (ARS): mock moment.utc() for spec
                                                                                // so we don't have to calculate this
    expect(el.innerHTML).toContain('Daisy Poppins');
    expect(el.innerHTML).toContain('Arthur D Healey');
    expect(el.innerHTML).toContain('5/23/2008');
    expect(el.innerHTML).toContain('(' + yearsOld + ' years old)');
    expect($(el).find('a.homeroom-link').text()).toContain('102');

    const modalIconEl = $(el).find('.click-event-modal').get(0);

    ReactTestUtils.Simulate.click(modalIconEl, () => {
      const modalText = $(document).find('.contact-info-modal').html();
      expect(modalText).toContain('1 Memorial Dr, Cambridge, MA 02142');
      expect(modalText).toContain('999-999-9999 C-Mom');
      expect(modalText).toContain('parent@example.com');
    });
  });
});

describe('non-active Transferred student', () => {
  it('renders note-taking area with Transferred status', () => {
    const el = document.createElement('div');
    helpers.renderTransferredStudent(el);

    expect(el.innerHTML).toContain('Daisy Poppins');
    expect(el.innerHTML).toContain('Arthur D Healey');
    expect(el.innerHTML).toContain('Transferred');
  });
});
<commit_msg>Pass in district key argument to spec<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';
import moment from 'moment';
import {studentProfile} from './fixtures/fixtures';
import StudentProfileHeader from './StudentProfileHeader';

const helpers = {
  renderActiveStudent(el, props) {
    const mergedProps = {
      student: studentProfile.student,
      districtKey: 'somerville',
      ...props
    };
    ReactDOM.render(<StudentProfileHeader {...mergedProps} />, el);
  },

  renderTransferredStudent(el, props) {
    const this_student = studentProfile.student;
    this_student['enrollment_status'] = 'Transferred';

    const mergedProps = {
      student: this_student,
      districtKey: 'somerville',
      ...props
    };
    ReactDOM.render(<StudentProfileHeader {...mergedProps} />, el);
  }

};

describe('active enrolled student', () => {
  it('renders note-taking area with homeroom', () => {
    const el = document.createElement('div');
    helpers.renderActiveStudent(el);
    const yearsOld = moment().diff(studentProfile.student.date_of_birth, 'years'); // TODO (ARS): mock moment.utc() for spec
                                                                                // so we don't have to calculate this
    expect(el.innerHTML).toContain('Daisy Poppins');
    expect(el.innerHTML).toContain('Arthur D Healey');
    expect(el.innerHTML).toContain('5/23/2008');
    expect(el.innerHTML).toContain('(' + yearsOld + ' years old)');
    expect($(el).find('a.homeroom-link').text()).toContain('102');

    const modalIconEl = $(el).find('.click-event-modal').get(0);

    ReactTestUtils.Simulate.click(modalIconEl, () => {
      const modalText = $(document).find('.contact-info-modal').html();
      expect(modalText).toContain('1 Memorial Dr, Cambridge, MA 02142');
      expect(modalText).toContain('999-999-9999 C-Mom');
      expect(modalText).toContain('parent@example.com');
    });
  });
});

describe('non-active Transferred student', () => {
  it('renders note-taking area with Transferred status', () => {
    const el = document.createElement('div');
    helpers.renderTransferredStudent(el);

    expect(el.innerHTML).toContain('Daisy Poppins');
    expect(el.innerHTML).toContain('Arthur D Healey');
    expect(el.innerHTML).toContain('Transferred');
  });
});
<|endoftext|>