<commit_before>/**
 * 表格组件
 * @author Cc
 * @date 2016/12/15
 */
gbClick = false;
var Table = {
    // 局部变量
    localVal: {
        tableSelf: "",
        staticDataObj: {},
        reqDataObj: {},
        columns: [],
        tableHead: [],
        isFirstRender: true, // 判断是否首次渲染
        isSearch: false // 判断是否点击查询
    },

    /**
     * public function 初始化组件
     *
     */
    init: function() {
        console.log('table init');
        var that = this;

        var proto = Object.create(HTMLElement.prototype);
        // 创建元素实例回调
        proto.createdCallback = function() {
            // console.log("createdCallback");
            that.localVal.tableSelf = this;
            that.localVal.staticDataObj = JSON.parse(this.getAttribute('data-staticData'));
            that.localVal.reqDataObj = JSON.parse(this.getAttribute('data-reqData'));
            if (!that.localVal.reqDataObj.pageSize) that.localVal.reqDataObj.pageSize = 200;
            if (!that.localVal.reqDataObj.currentPage) that.localVal.reqDataObj.currentPage = 1;

            // young.luo
            eval("that.prepareDataFunc = " + this.getAttribute('data-prepareDataFunc')); // 额外对请求的数据做处理
            eval("that.afterGetDataFunc = " + this.getAttribute('data-afterGetDataFunc')); // 收到数据后回调

            that.requestData();
        };

        // 向文档插入实例回调
        proto.attachedCallback = function() {
            // console.log("attachedCallback");
        };

        // debugger
        document.registerElement('tag-table', { prototype: proto });
    },

    /**
     * public function 请求数据
     * @param {boolean} isTriggered // 判断是否手动触发
     *
     */
    requestData: function(isTriggered) {
        var that = this;
        var _this = this.localVal.tableSelf,
            _staticDataObj = this.localVal.staticDataObj,
            _reqDataObj = this.localVal.reqDataObj;
        // 读取cookies中form表单的参数
        var reqData = window.PubFunc.getCookie(_staticDataObj.reqCookie);
        if (reqData.hasOwnProperty("undefined")) return false;

        // 点击查询加载表格
        if (isTriggered) {
            this.localVal.isSearch = true;
        }

        // 返回数据前
        window.PubFunc.showLoading();

        // 组装request data，主要是翻页相关的和额外的参数
        for (var _reqDataObjItem in _reqDataObj) {
            reqData[_reqDataObjItem] = _reqDataObj[_reqDataObjItem];
        }

        // young.luo
        if (that.prepareDataFunc) that.prepareDataFunc(_this, reqData);

        $.ajax({
            type: _staticDataObj.ajaxType,
            url: _staticDataObj.url,
            data: JSON.stringify(reqData),
            dataType: "json",
            contentType: "application/json",
            success: function(res) {
                if (res.code === 200) {
                    console.log('%csuccess', 'background: green; color: white;');
                    // 为了延迟看loading
                    setTimeout(function() {
                        window.PubFunc.hideLoading();
                        that._renderTable(reqData, res.data);
                    }, 1500);

                    // young.luo
                    if (that.afterGetDataFunc) {
                        that.afterGetDataFunc(that, res);
                    }
                } else {
                    window.PubFunc.hideLoading();
                    alert(res.msg);
                }
            },
            error: function() {
                console.log('%cerror', 'background: red; color: white;');
            }
        });

    },

    /**
     * private function 渲染表格
     * @param {object} __reqDataObj // 请求参数
     * @param {object} resData // 返回数据
     *
     */
    _renderTable: function(__reqDataObj, resData) {
        if (resData && resData.head.length > 0) {
            this.localVal.columns = []; // 重置列表表头字段顺序
            // 设置列表表头字段顺序
            var sort = resData.sort;
            for (var i = 0; i < sort.length; i++) {
                this.localVal.columns.push({
                    "data": sort[i]
                })
            }

            // 存储表头
            this.localVal.tableHead = resData.head;

            this._mainTable(__reqDataObj, resData);
        }
    },

    /**
     * private function 渲染表格主体，操作表格
     * @param {object} ___reqDataObj // 请求参数
     * @param {object} _resData  // 返回数据
     *
     */
    _mainTable: function(___reqDataObj, _resData) {
        var that = this,
            ___this = this.localVal.tableSelf,
            ___staticDataObj = this.localVal.staticDataObj,
            columns = this.localVal.columns;

        // 添加表头
        var excelbtn = "";
        if (___staticDataObj.exportExcel) {
            excelbtn = '<button class="btn btn-success" id="exportExcel">导出Excel</button>';
        }
        var tableToolbar = '

' + excelbtn + '<button class="btn btn-success showAllColumns">显示所有列</button>

';
        var headTemp = "",
            headData = this.localVal.tableHead;
        for (var i = 0; i < headData.length; i++) {
            headTemp += '' + headData[i] + '	';
        }
        $(___this).html('
' + tableToolbar + '

' + headTemp + '

');

        // 渲染主体
        var dataTableContent = $('#' + ___staticDataObj.id).DataTable({
            "pageLength": this.localVal.reqDataObj.pageSize,
            "searching": false,
            "language": that._dataTableConfig(this.localVal.reqDataObj.pageSize),
            // "order": [[1, "desc"]],
            "ordering": false, // 因为开启了serverSide，所以排序也会发起ajax请求，但又因为只对当前页进行排序，因此要禁用这个排序
            "columns": columns, // 设置列表表头字段顺序
            "processing": true,
            "serverSide": true, //启用服务器端分页
            "ajax": function(data, callback, settings) {
                console.log("%cmaintable", "background: red", data);
                var param = ___reqDataObj;
                param.currentPage = (data.start / data.length) + 1;
                param.pageSize = data.length;

                // young.luo 回调
                if (this.prepareDataFunc) this.prepareDataFunc(__this, param);

                // 初次加载或点击查询，更新表格
                if (that.localVal.isFirstRender || that.localVal.isSearch) {
                    that.localVal.isFirstRender = false;
                    that._getTable(data, _resData, callback);
                    return false;
                }

                console.log('%cpage:', "background: pink", param.currentPage);
                console.log('%clength:', "background: pink", data.length);
                // dataTable本身组件的操作触发，更新表格
                $.ajax({
                    type: ___staticDataObj.ajaxType,
                    url: ___staticDataObj.url,
                    cache: false, //禁用缓存
                    data: JSON.stringify(param), //传入组装的参数
                    dataType: "json",
                    contentType: "application/json",
                    success: function(res) {
                        if (res.code === 200) {
                            console.log("%cmaintableReqSucc", "background: green", res);
                            that._getTable(data, res.data, callback);
                        } else {
                            window.PubFunc.hideLoading();
                            alert(res.msg);
                        }
                    }
                })
            },

        });

        // fixedHeader
        new $.fn.dataTable.FixedHeader(dataTableContent, {
            headerOffset: $('.navbar').height()
        });
        // $.each($('table.fixedHeader-floating th'), function(index, item) {
        //   console.log($(item).width());
        //   var tdItem = $('table.dataTable tbody tr:first-child td')[index];
        //   $(item).width($(tdItem).width());
        // });
        $('table.dataTable').scroll(function() {
            var tableScrollLeft = $(this).scrollLeft();
            $('table.fixedHeader-floating').scrollLeft(tableScrollLeft);
        });

        // 显示隐藏列
        $('.hideColumn').bind('click', function(e) {
            e.stopPropagation();
            dataTableContent.column($(this).attr('data-column')).visible(false);
            that._setTableDynamicStyle();

        });
        $('.showAllColumns').bind('click', function() {
            dataTableContent.columns().visible(true);
            that._setTableDynamicStyle();
        });

        // 每页显示项数
        $('#js_menuLen').bind('keydown', function(e) {
            var menuLenVal = $(this).val();
            if (e.which == "13") dataTableContent.page.len(menuLenVal).draw();
        })

        // 导出Excel
        $('#exportExcel').bind('click', function() {
            if (gbClick) {
                alert("上一个下载任务还在进行中!");
                return;
            }
            // 防止选中后没有点击查询，直接点击导出，所以这里重新组装请求参数
            window.PubFunc.setCookie(___staticDataObj.reqCookie, $('#js_searchFrom').serialize(), 7);
            var reReqData = window.PubFunc.getCookie(___staticDataObj.reqCookie);
            for (var i in that.localVal.reqDataObj) {
                reReqData[i] = that.localVal.reqDataObj[i];
            }
            reReqData['isExportExcel'] = true;

            // young.luo
            if (that.prepareDataFunc) that.prepareDataFunc(___this, reReqData);
            gbClick = true;
            $.ajax({
                type: ___staticDataObj.ajaxType,
                url: ___staticDataObj.url,
                cache: false,
                data: JSON.stringify(reReqData),
                dataType: "json",
                contentType: "application/json",
                success: function(res) {
                    gbClick = false;
                    if (res.code === 200) {
                        alert("文件生成成功: " + res.data.filename);
                        //window.location.href='download_file.do?file='+ res.data.filename + "&type=2";
                        console.log("%cexportExcelDataGet", "background: orange", res);
                    } else {
                        window.PubFunc.hideLoading();
                        alert(res.msg);
                    }
                }
            });
        });
    },

    /**
     * private function 主体数据插入
     * @param {object} dataTableAjaxData // dataTable自带的ajax data
     * @param {object} __resData // 返回数据
     * @param {function} _callback // dataTable回调方法
     *
     */
    _getTable: function(dataTableAjaxData, __resData, _callback) {
        this.localVal.isSearch = false; // 重置为非点击查询

        var ____staticDataObj = this.localVal.staticDataObj;
        var returnData = {};
        returnData.draw = dataTableAjaxData.draw; //这里直接自行返回了draw计数器,应该由后台返回
        returnData.recordsTotal = __resData.page.recordCount; //返回数据全部记录
        returnData.recordsFiltered = __resData.page.recordCount; //后台不实现过滤功能，每次查询均视作全部结果

        var resList = __resData.page.resList;
        if (__resData.total) resList.push(__resData.total); // 加上“总计”行，用于显示，但不计入pageLength，见上
        returnData.data = resList; //返回的数据列表
        // console.log(returnData);
        //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
        //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
        _callback(returnData);

        // 动态插入数据排序
        $('#' + ____staticDataObj.id).trigger("update").tablesorter();
        // 初始化排序
        setTimeout(function() {
            var sorting = [
                [____staticDataObj.orderColumn, ____staticDataObj.orderDir]
            ];
            $('#' + ____staticDataObj.id).trigger("sorton", [sorting]);
        }, 1);

        this._setTableDynamicStyle();
    },

    /**
     * private function 设置表格动态样式
     *
     */
    _setTableDynamicStyle: function() {
        // 设置table的横向滚动态
        // display: block时才能出现滚动条
        // display: table时才能在内容少的时候自适应宽度撑满table
        if ($('table.dataTable tbody').width() > $('.dataTables_wrapper').width()) {
            $('table.dataTable').css({
                'display': 'block',
                'overflow-x': 'auto'
            })
        } else {
            $('table.dataTable').css({
                'display': 'table'
            })
        }

    },

    /**
     * private object datatable配置
     *
     */
    _dataTableConfig: function(menuLen) {
        return {
            "sProcessing": "处理中...",
            // "sLengthMenu": "每页 _MENU_ 项",
            "sLengthMenu": '每页 <input type="text" class="form-control" id="js_menuLen" value="' + menuLen + '" /> 项',
            "sZeroRecords": "没有匹配结果",
            "sInfo": "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项",
            "sInfoEmpty": "当前显示第 0 至 0 项，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "sLast": "末页",
                "sJump": "跳转"
            },
            "oAria": {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            },
        }
    }
}

Table.init();<commit_msg>刷新不更新表格，只有点击才更新<commit_after>/**
 * 表格组件
 * @author Cc
 * @date 2016/12/15
 */
gbClick = false;
var Table = {
    // 局部变量
    localVal: {
        tableSelf: "",
        staticDataObj: {},
        reqDataObj: {},
        columns: [],
        tableHead: [],
        isSearch: false // 判断是否点击查询
    },

    /**
     * public function 初始化组件
     *
     */
    init: function() {
        console.log('table init');
        var that = this;

        var proto = Object.create(HTMLElement.prototype);
        // 创建元素实例回调
        proto.createdCallback = function() {
            // console.log("createdCallback");
            that.localVal.tableSelf = this;
            that.localVal.staticDataObj = JSON.parse(this.getAttribute('data-staticData'));
            that.localVal.reqDataObj = JSON.parse(this.getAttribute('data-reqData'));
            if (!that.localVal.reqDataObj.pageSize) that.localVal.reqDataObj.pageSize = 200;
            if (!that.localVal.reqDataObj.currentPage) that.localVal.reqDataObj.currentPage = 1;

            // young.luo
            eval("that.prepareDataFunc = " + this.getAttribute('data-prepareDataFunc')); // 额外对请求的数据做处理
            eval("that.afterGetDataFunc = " + this.getAttribute('data-afterGetDataFunc')); // 收到数据后回调
        };

        // 向文档插入实例回调
        proto.attachedCallback = function() {
            // console.log("attachedCallback");
        };

        // debugger
        document.registerElement('tag-table', { prototype: proto });
    },

    /**
     * public function 请求数据
     * @param {boolean} isTriggered // 判断是否手动触发
     *
     */
    requestData: function(isTriggered) {
        var that = this;
        var _this = this.localVal.tableSelf,
            _staticDataObj = this.localVal.staticDataObj,
            _reqDataObj = this.localVal.reqDataObj;
        // 读取cookies中form表单的参数
        var reqData = window.PubFunc.getCookie(_staticDataObj.reqCookie);
        if (reqData.hasOwnProperty("undefined")) return false;

        // 点击查询加载表格
        if (isTriggered) {
            this.localVal.isSearch = true;
        }

        // 返回数据前
        window.PubFunc.showLoading();

        // 组装request data，主要是翻页相关的和额外的参数
        for (var _reqDataObjItem in _reqDataObj) {
            reqData[_reqDataObjItem] = _reqDataObj[_reqDataObjItem];
        }

        // young.luo
        if (that.prepareDataFunc) that.prepareDataFunc(_this, reqData);

        $.ajax({
            type: _staticDataObj.ajaxType,
            url: _staticDataObj.url,
            data: JSON.stringify(reqData),
            dataType: "json",
            contentType: "application/json",
            success: function(res) {
                if (res.code === 200) {
                    console.log('%csuccess', 'background: green; color: white;');
                    // 为了延迟看loading
                    setTimeout(function() {
                        window.PubFunc.hideLoading();
                        that._renderTable(reqData, res.data);
                    }, 1500);

                    // young.luo
                    if (that.afterGetDataFunc) {
                        that.afterGetDataFunc(that, res);
                    }
                } else {
                    window.PubFunc.hideLoading();
                    alert(res.msg);
                }
            },
            error: function() {
                console.log('%cerror', 'background: red; color: white;');
            }
        });

    },

    /**
     * private function 渲染表格
     * @param {object} __reqDataObj // 请求参数
     * @param {object} resData // 返回数据
     *
     */
    _renderTable: function(__reqDataObj, resData) {
        if (resData && resData.head.length > 0) {
            this.localVal.columns = []; // 重置列表表头字段顺序
            // 设置列表表头字段顺序
            var sort = resData.sort;
            for (var i = 0; i < sort.length; i++) {
                this.localVal.columns.push({
                    "data": sort[i]
                })
            }

            // 存储表头
            this.localVal.tableHead = resData.head;

            this._mainTable(__reqDataObj, resData);
        }
    },

    /**
     * private function 渲染表格主体，操作表格
     * @param {object} ___reqDataObj // 请求参数
     * @param {object} _resData  // 返回数据
     *
     */
    _mainTable: function(___reqDataObj, _resData) {
        var that = this,
            ___this = this.localVal.tableSelf,
            ___staticDataObj = this.localVal.staticDataObj,
            columns = this.localVal.columns;

        // 添加表头
        var excelbtn = "";
        if (___staticDataObj.exportExcel) {
            excelbtn = '<button class="btn btn-success" id="exportExcel">导出Excel</button>';
        }
        var tableToolbar = '

' + excelbtn + '<button class="btn btn-success showAllColumns">显示所有列</button>

';
        var headTemp = "",
            headData = this.localVal.tableHead;
        for (var i = 0; i < headData.length; i++) {
            headTemp += '' + headData[i] + '	';
        }
        $(___this).html('
' + tableToolbar + '

' + headTemp + '

');

        // 渲染主体
        var dataTableContent = $('#' + ___staticDataObj.id).DataTable({
            "pageLength": this.localVal.reqDataObj.pageSize,
            "searching": false,
            "language": that._dataTableConfig(this.localVal.reqDataObj.pageSize),
            // "order": [[1, "desc"]],
            "ordering": false, // 因为开启了serverSide，所以排序也会发起ajax请求，但又因为只对当前页进行排序，因此要禁用这个排序
            "columns": columns, // 设置列表表头字段顺序
            "processing": true,
            "serverSide": true, //启用服务器端分页
            "ajax": function(data, callback, settings) {
                console.log("%cmaintable", "background: red", data);
                var param = ___reqDataObj;
                param.currentPage = (data.start / data.length) + 1;
                param.pageSize = data.length;

                // young.luo 回调
                if (this.prepareDataFunc) this.prepareDataFunc(__this, param);

                // 点击查询，更新表格
                if (that.localVal.isSearch) {
                    that._getTable(data, _resData, callback);
                    return false;
                }

                console.log('%cpage:', "background: pink", param.currentPage);
                console.log('%clength:', "background: pink", data.length);
                // dataTable本身组件的操作触发，更新表格
                $.ajax({
                    type: ___staticDataObj.ajaxType,
                    url: ___staticDataObj.url,
                    cache: false, //禁用缓存
                    data: JSON.stringify(param), //传入组装的参数
                    dataType: "json",
                    contentType: "application/json",
                    success: function(res) {
                        if (res.code === 200) {
                            console.log("%cmaintableReqSucc", "background: green", res);
                            that._getTable(data, res.data, callback);
                        } else {
                            window.PubFunc.hideLoading();
                            alert(res.msg);
                        }
                    }
                })
            },

        });

        // fixedHeader
        new $.fn.dataTable.FixedHeader(dataTableContent, {
            headerOffset: $('.navbar').height()
        });
        // $.each($('table.fixedHeader-floating th'), function(index, item) {
        //   console.log($(item).width());
        //   var tdItem = $('table.dataTable tbody tr:first-child td')[index];
        //   $(item).width($(tdItem).width());
        // });
        $('table.dataTable').scroll(function() {
            var tableScrollLeft = $(this).scrollLeft();
            $('table.fixedHeader-floating').scrollLeft(tableScrollLeft);
        });

        // 显示隐藏列
        $('.hideColumn').bind('click', function(e) {
            e.stopPropagation();
            dataTableContent.column($(this).attr('data-column')).visible(false);
            that._setTableDynamicStyle();

        });
        $('.showAllColumns').bind('click', function() {
            dataTableContent.columns().visible(true);
            that._setTableDynamicStyle();
        });

        // 每页显示项数
        $('#js_menuLen').bind('keydown', function(e) {
            var menuLenVal = $(this).val();
            if (e.which == "13") dataTableContent.page.len(menuLenVal).draw();
        })

        // 导出Excel
        $('#exportExcel').bind('click', function() {
            if (gbClick) {
                alert("上一个下载任务还在进行中!");
                return;
            }
            // 防止选中后没有点击查询，直接点击导出，所以这里重新组装请求参数
            window.PubFunc.setCookie(___staticDataObj.reqCookie, $('#js_searchFrom').serialize(), 7);
            var reReqData = window.PubFunc.getCookie(___staticDataObj.reqCookie);
            for (var i in that.localVal.reqDataObj) {
                reReqData[i] = that.localVal.reqDataObj[i];
            }
            reReqData['isExportExcel'] = true;

            // young.luo
            if (that.prepareDataFunc) that.prepareDataFunc(___this, reReqData);
            gbClick = true;
            $.ajax({
                type: ___staticDataObj.ajaxType,
                url: ___staticDataObj.url,
                cache: false,
                data: JSON.stringify(reReqData),
                dataType: "json",
                contentType: "application/json",
                success: function(res) {
                    gbClick = false;
                    if (res.code === 200) {
                        alert("文件生成成功: " + res.data.filename);
                        //window.location.href='download_file.do?file='+ res.data.filename + "&type=2";
                        console.log("%cexportExcelDataGet", "background: orange", res);
                    } else {
                        window.PubFunc.hideLoading();
                        alert(res.msg);
                    }
                }
            });
        });
    },

    /**
     * private function 主体数据插入
     * @param {object} dataTableAjaxData // dataTable自带的ajax data
     * @param {object} __resData // 返回数据
     * @param {function} _callback // dataTable回调方法
     *
     */
    _getTable: function(dataTableAjaxData, __resData, _callback) {
        this.localVal.isSearch = false; // 重置为非点击查询

        var ____staticDataObj = this.localVal.staticDataObj;
        var returnData = {};
        returnData.draw = dataTableAjaxData.draw; //这里直接自行返回了draw计数器,应该由后台返回
        returnData.recordsTotal = __resData.page.recordCount; //返回数据全部记录
        returnData.recordsFiltered = __resData.page.recordCount; //后台不实现过滤功能，每次查询均视作全部结果

        var resList = __resData.page.resList;
        if (__resData.total) resList.push(__resData.total); // 加上“总计”行，用于显示，但不计入pageLength，见上
        returnData.data = resList; //返回的数据列表
        // console.log(returnData);
        //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
        //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
        _callback(returnData);

        // 动态插入数据排序
        $('#' + ____staticDataObj.id).trigger("update").tablesorter();
        // 初始化排序
        setTimeout(function() {
            var sorting = [
                [____staticDataObj.orderColumn, ____staticDataObj.orderDir]
            ];
            $('#' + ____staticDataObj.id).trigger("sorton", [sorting]);
        }, 1);

        this._setTableDynamicStyle();
    },

    /**
     * private function 设置表格动态样式
     *
     */
    _setTableDynamicStyle: function() {
        // 设置table的横向滚动态
        // display: block时才能出现滚动条
        // display: table时才能在内容少的时候自适应宽度撑满table
        if ($('table.dataTable tbody').width() > $('.dataTables_wrapper').width()) {
            $('table.dataTable').css({
                'display': 'block',
                'overflow-x': 'auto'
            })
        } else {
            $('table.dataTable').css({
                'display': 'table'
            })
        }

    },

    /**
     * private object datatable配置
     *
     */
    _dataTableConfig: function(menuLen) {
        return {
            "sProcessing": "处理中...",
            // "sLengthMenu": "每页 _MENU_ 项",
            "sLengthMenu": '每页 <input type="text" class="form-control" id="js_menuLen" value="' + menuLen + '" /> 项',
            "sZeroRecords": "没有匹配结果",
            "sInfo": "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项",
            "sInfoEmpty": "当前显示第 0 至 0 项，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "sLast": "末页",
                "sJump": "跳转"
            },
            "oAria": {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            },
        }
    }
}

Table.init();<|endoftext|>


<commit_before>import emptyContent from '../../data/emptyContent';
import store from '../../store';
import utils from '../utils';

const dataExtractor = /<!--stackedit_data:([A-Za-z0-9+/=\s]+)-->$/;

export default {
  serializeContent(content) {
    let result = content.text;
    const data = {};
    if (content.properties.length > 1) {
      data.properties = content.properties;
    }
    if (Object.keys(content.discussions).length) {
      data.discussions = content.discussions;
    }
    if (Object.keys(content.comments).length) {
      data.comments = content.comments;
    }
    if (content.history && content.history.length) {
      data.history = content.history;
    }
    if (Object.keys(data).length) {
      const serializedData = utils.encodeBase64(JSON.stringify(data)).replace(/(.{50})/g, '$1\n');
      result += `<!--stackedit_data:\n${serializedData}\n-->`;
    }
    return result;
  },
  parseContent(serializedContent, syncLocation) {
    const result = utils.deepCopy(store.state.content.itemMap[`${syncLocation.fileId}/content`])
      || emptyContent();
    result.text = utils.sanitizeText(serializedContent);
    result.history = [];
    const extractedData = dataExtractor.exec(serializedContent);
    if (extractedData) {
      try {
        const serializedData = extractedData[1].replace(/\s/g, '');
        const parsedData = JSON.parse(utils.decodeBase64(serializedData));
        result.text = utils.sanitizeText(serializedContent.slice(0, extractedData.index));
        if (parsedData.properties) {
          result.properties = utils.sanitizeText(parsedData.properties);
        }
        if (parsedData.discussions) {
          result.discussions = parsedData.discussions;
        }
        if (parsedData.comments) {
          result.comments = parsedData.comments;
        }
        result.history = parsedData.history || [];
      } catch (e) {
        // Ignore
      }
    }
    result.hash = utils.hash(utils.serializeObject({
      ...result,
      hash: undefined,
    }));
    return result;
  },
  /**
   * Find and open a file location that fits the criteria
   */
  openFileWithLocation(allLocations, criteria) {
    return allLocations.some((location) => {
        // If every field fits the criteria
      if (Object.keys(criteria).every(key => criteria[key] === location[key])) {
        // Found one location that fits, open it if it exists
        const file = store.state.file.itemMap[location.fileId];
        if (file) {
          store.commit('file/setCurrentId', file.id);
          // If file is in the trash, restore it
          if (file.parentId === 'trash') {
            store.commit('file/patchItem', {
              ...file,
              parentId: null,
            });
          }
          return true;
        }
      }
      return false;
    });
  },
};
<commit_msg>Fixed #1165<commit_after>import emptyContent from '../../data/emptyContent';
import store from '../../store';
import utils from '../utils';

const dataExtractor = /<!--stackedit_data:([A-Za-z0-9+/=\s]+)-->$/;

export default {
  serializeContent(content) {
    let result = content.text;
    const data = {};
    if (content.properties.length > 1) {
      data.properties = content.properties;
    }
    if (Object.keys(content.discussions).length) {
      data.discussions = content.discussions;
    }
    if (Object.keys(content.comments).length) {
      data.comments = content.comments;
    }
    if (content.history && content.history.length) {
      data.history = content.history;
    }
    if (Object.keys(data).length) {
      const serializedData = utils.encodeBase64(JSON.stringify(data)).replace(/(.{50})/g, '$1\n');
      result += `<!--stackedit_data:\n${serializedData}\n-->`;
    }
    return result;
  },
  parseContent(serializedContent, syncLocation = {}) {
    const result = utils.deepCopy(store.state.content.itemMap[`${syncLocation.fileId}/content`])
      || emptyContent();
    result.text = utils.sanitizeText(serializedContent);
    result.history = [];
    const extractedData = dataExtractor.exec(serializedContent);
    if (extractedData) {
      try {
        const serializedData = extractedData[1].replace(/\s/g, '');
        const parsedData = JSON.parse(utils.decodeBase64(serializedData));
        result.text = utils.sanitizeText(serializedContent.slice(0, extractedData.index));
        if (parsedData.properties) {
          result.properties = utils.sanitizeText(parsedData.properties);
        }
        if (parsedData.discussions) {
          result.discussions = parsedData.discussions;
        }
        if (parsedData.comments) {
          result.comments = parsedData.comments;
        }
        result.history = parsedData.history || [];
      } catch (e) {
        // Ignore
      }
    }
    result.hash = utils.hash(utils.serializeObject({
      ...result,
      hash: undefined,
    }));
    return result;
  },
  /**
   * Find and open a file location that fits the criteria
   */
  openFileWithLocation(allLocations, criteria) {
    return allLocations.some((location) => {
        // If every field fits the criteria
      if (Object.keys(criteria).every(key => criteria[key] === location[key])) {
        // Found one location that fits, open it if it exists
        const file = store.state.file.itemMap[location.fileId];
        if (file) {
          store.commit('file/setCurrentId', file.id);
          // If file is in the trash, restore it
          if (file.parentId === 'trash') {
            store.commit('file/patchItem', {
              ...file,
              parentId: null,
            });
          }
          return true;
        }
      }
      return false;
    });
  },
};
<|endoftext|>


<commit_before>(function(angular) {
  'use strict';
  angular.module('ngIsoConstants.filters')
  /**
   * @brief converts Alpha2 or NumericCode to Name
   * @details Returns original input if unable to concert
   *
   * @param  input - numeric Country code or alpha2
   * @return Country name
   */
  .filter('isoCountry', ['ISO3166', function(ISO3166) {
    return function(input) {
      var result = null;
      if (isNumeric(input)) {
        result = ISO3166.getCountryObjFromNumericCode(input);

      } else if (typeof(input) === 'string') {
        if (input.length === 2) {
          result = ISO3166.getCountryObjFromAlpha2(input.toUpperCase());

        } else if (input.length === 3) {
          result = ISO3166.getCountryObjFromAlpha3(input.toUpperCase());

        }
      }

      return (result) ? result.name: input;

      function isNumeric(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
      }
    };
  }]);
})(angular);
<commit_msg>Fix spelling<commit_after>(function(angular) {
  'use strict';
  angular.module('ngIsoConstants.filters')
  /**
   * @brief converts Alpha2 or NumericCode to Name
   * @details Returns original input if unable to convert
   *
   * @param  input - numeric Country code or alpha2
   * @return Country name
   */
  .filter('isoCountry', ['ISO3166', function(ISO3166) {
    return function(input) {
      var result = null;
      if (isNumeric(input)) {
        result = ISO3166.getCountryObjFromNumericCode(input);

      } else if (typeof(input) === 'string') {
        if (input.length === 2) {
          result = ISO3166.getCountryObjFromAlpha2(input.toUpperCase());

        } else if (input.length === 3) {
          result = ISO3166.getCountryObjFromAlpha3(input.toUpperCase());

        }
      }

      return (result) ? result.name: input;

      function isNumeric(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
      }
    };
  }]);
})(angular);
<|endoftext|>


<commit_before>message = 'We create PortfolioEntryElements when the event handler is responding to a list of objects from the server that includes a new PortfolioEntry.';
// FIXME: Come up with a suitable response, matching the description above.
response = {
    // FIXME: We might not need these models here.
    'dias': [{'pk': 0}],

    'citations': [
    {'pk': 0, 'fields': {'portfolio_entry_id': 0}}, // These belong to different
    {'pk': 1, 'fields': {'portfolio_entry_id': 1}}, // PortfolioEntries.
    ],

    'portfolio_entries': [{'pk': 0, 'fields': {
        'project_id': 0,
        'project_description': 'described',
        'experience_description': 'i hacked things'
    }
    }
    ],
    'projects': [{'pk': 0, 'fields': {'name': 'bindlestiff'}}],
    'summaries': {'0': 'Ohloh: Coded in shell script for 12 months since 2007.'},
    'project_icon_urls': {'0': '/static/images/the-logo-bluegreen-125px.png'}
};

testUpdatePortfolio = function() {
    updatePortfolio(response);
    $(response.portfolio_entries).each( function() {

            var portfolio_entry = this;

            // "this" is a JSON representation of a PortfolioEntry.
            // Did we create this PortfolioEntryElement?
            var pee = $("#portfolio_entry_" + portfolio_entry.pk);

            fireunit.ok( pee.size() == 1,
                "Expected a portfolio_entry corresponding to " + portfolio_entry);
            fireunit.ok( $('.project_name', pee).text() == "bindlestiff",
                "Expected the new portfolio_entry to say its project name is bindlestiff");
            fireunit.ok( pee.find("img.project_icon").attr('src') ==
                "/static/images/the-logo-bluegreen-125px.png",
                "Expected the project icon URL to properly be set.");
            fireunit.ok( $(".project_description", pee).text() == "described",
                "Expected the new portfolio_entry to say " +
                "its project description is 'described'");
            fireunit.ok( $(".experience_description", pee).text() == "i hacked things",
                "Expected the new portfolio_entry to say a description of the experience");

            /*
             * Check that each citation in the response is also in the DOM.
             */

            // List the citations in the DOM.
            var dom_citations = $('.citations li', pee);

            fireunit.ok(
                    dom_citations.size() == 1,
                    "Expected the number of citation elements in the " +
                    "PortfolioEntryElement == 1 == the number of " +
                    "citations in the input that belong to this PEE.");

            // For each citation in the response, check that its data
            // is stuffed into the DOM.
            // I'll refer to a "citation in the response" as a
            // "response citation" from now on.
            var testThatResponseCitationHasADOMCitation = function() {
                var responseCitation = this;

                var msg = "Find DOM citation matching this response citation.";
                var $domCitation = $('#citation_'+responseCitation.pk);
                fireunit.ok($domCitation.size() > 0, msg);

                var msg = "Assert match of citation summary.";
                fireunit.ok($domCitation.find('.summary').text() ==
                        response.summaries[responseCitation.pk],
                        msg);
            };

            // Test that each of this portfolio entry's citations
            // has a corresponding DOM citation.
            $([response.citations[0]]).each(testThatResponseCitationHasADOMCitation);

            // And now check the reverse: For each citation in the DOM,
            // check that its data is in the response.

            fireunit.ok($('.citations li').size() == 1, "Expected just one citation in the DOM.");
            fireunit.ok($('.citations li')[0].id == 'citation_0',
                    "Expected the one citation in the DOM to have id citation_0");

    });
};

testUpdatePortfolio();

testNoDuplication = function() {
    $('#portfolio *').remove();

    updatePortfolio(response);
    fireunit.ok($('.citations li').size() == 1, "Assert there's one citation.");
    fireunit.ok($('.portfolio_entry:visible').size() == 1, "Assert there's one portfolio entry.");

    updatePortfolio(response);
    fireunit.ok($('.citations li').size() == 1, "Assert there's still one citation.");
    fireunit.ok($('.portfolio_entry:visible').size() == 1, "Assert there's still one portfolio entry.");
};
testNoDuplication();
<commit_msg>Fixed some failing tests in js.<commit_after>message = 'We create PortfolioEntryElements when the event handler is responding to a list of objects from the server that includes a new PortfolioEntry.';
// FIXME: Come up with a suitable response, matching the description above.
response = {
    // FIXME: We might not need these models here.
    'dias': [{'pk': 0}],

    'citations': [
    {'pk': 0, 'fields': {'portfolio_entry_id': 0}}, // These belong to different
    {'pk': 1, 'fields': {'portfolio_entry_id': 1}}, // PortfolioEntries.
    ],

    'portfolio_entries': [{'pk': 0, 'fields': {
        'project_id': 0,
        'project_description': 'described',
        'experience_description': 'i hacked things'
    }
    }
    ],
    'projects': [{'pk': 0, 'fields': {'name': 'bindlestiff'}}],
    'summaries': {'0': 'Ohloh: Coded in shell script for 12 months since 2007.'},
    'project_icon_urls': {'0': '/static/images/the-logo-bluegreen-125px.png'}
};

testUpdatePortfolio = function() {
    updatePortfolio(response);
    $(response.portfolio_entries).each( function() {

            var portfolio_entry = this;

            // "this" is a JSON representation of a PortfolioEntry.
            // Did we create this PortfolioEntryElement?
            var pee = $("#portfolio_entry_" + portfolio_entry.pk);

            fireunit.ok( pee.size() == 1,
                "Expected a portfolio_entry corresponding to " + portfolio_entry);
            fireunit.ok( $('.project_name', pee).text() == "bindlestiff",
                "Expected the new portfolio_entry to say its project name is bindlestiff");
            fireunit.ok( pee.find("img.project_icon").attr('src') ==
                "/static/images/the-logo-bluegreen-125px.png",
                "Expected the project icon URL to properly be set.");
            fireunit.ok( $(".project_description", pee).text() == "described",
                "Expected the new portfolio_entry to say " +
                "its project description is 'described'");
            fireunit.ok( $(".experience_description", pee).text() == "i hacked things",
                "Expected the new portfolio_entry to say a description of the experience");

            /*
             * Check that each citation in the response is also in the DOM.
             */

            // List the citations in the DOM.
            var dom_citations = $('.citations > li', pee);

            fireunit.ok(
                    dom_citations.size() == 1,
                    "Expected the number of citation elements in the " +
                    "PortfolioEntryElement == 1 == the number of " +
                    "citations in the input that belong to this PEE. Instead " +
                    "the number of citation elements == " + dom_citations.size());

            // For each citation in the response, check that its data
            // is stuffed into the DOM.
            // I'll refer to a "citation in the response" as a
            // "response citation" from now on.
            var testThatResponseCitationHasADOMCitation = function() {
                var responseCitation = this;

                var msg = "Find DOM citation matching this response citation.";
                var $domCitation = $('#citation_'+responseCitation.pk);
                fireunit.ok($domCitation.size() > 0, msg);

                var msg = "Assert match of citation summary.";
                fireunit.ok($domCitation.find('.summary').text() ==
                        response.summaries[responseCitation.pk],
                        msg);
            };

            // Test that each of this portfolio entry's citations
            // has a corresponding DOM citation.
            $([response.citations[0]]).each(testThatResponseCitationHasADOMCitation);

            // And now check the reverse: For each citation in the DOM,
            // check that its data is in the response.

            fireunit.ok($('.citations > li').size() == 1, "Expected just one citation in the DOM.");
            fireunit.ok($('.citations > li')[0].id == 'citation_0',
                    "Expected the one citation in the DOM to have id citation_0");

    });
};

testUpdatePortfolio();

testNoDuplication = function() {
    $('#portfolio *').remove();

    updatePortfolio(response);
    fireunit.ok($('.citations > li').size() == 1, "Assert there's one citation.");
    fireunit.ok($('.portfolio_entry:visible').size() == 1, "Assert there's one portfolio entry.");

    updatePortfolio(response);
    fireunit.ok($('.citations > li').size() == 1, "Assert there's still one citation.");
    fireunit.ok($('.portfolio_entry:visible').size() == 1, "Assert there's still one portfolio entry.");
};
testNoDuplication();
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createContactLink = exports.combineHeaders = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var combineHeaders = exports.combineHeaders = function combineHeaders() {
  var searchParams = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  return Object.keys(searchParams).map(function (key) {
    return key + '=' + encodeURIComponent(searchParams[key]);
  }).join('&');
};

var createContactLink = exports.createContactLink = function createContactLink(tel, sms, facetime, email, headers) {
  var link = void 0;
  if (email) {
    link = 'mailto:' + email;
    if (headers) {
      link += '?' + combineHeaders(headers);
    }
  } else if (tel) {
    link = 'tel:' + tel;
  } else if (sms) {
    link = 'sms:' + sms;
  } else if (facetime) {
    link = 'facetime:' + facetime;
  }
  return link;
};

var Obfuscate = function (_Component) {
  _inherits(Obfuscate, _Component);

  function Obfuscate() {
    _classCallCheck(this, Obfuscate);

    return _possibleConstructorReturn(this, (Obfuscate.__proto__ || Object.getPrototypeOf(Obfuscate)).apply(this, arguments));
  }

  _createClass(Obfuscate, [{
    key: 'render',
    value: function render() {
      return this.props.obfuscate ? this.renderObfuscatedLink() : this.renderLink();
    }
  }, {
    key: 'renderLink',
    value: function renderLink() {
      var _props = this.props,
          tel = _props.tel,
          sms = _props.sms,
          facetime = _props.facetime,
          email = _props.email,
          obfuscate = _props.obfuscate,
          headers = _props.headers,
          children = _props.children,
          others = _objectWithoutProperties(_props, ['tel', 'sms', 'facetime', 'email', 'obfuscate', 'headers', 'children']);

      return _react2.default.createElement(
        'a',
        _extends({
          href: createContactLink(tel, sms, facetime, email, headers)
        }, others),
        children || tel || sms || facetime || email
      );
    }
  }, {
    key: 'reverse',
    value: function reverse(s) {
      return s.split('').reverse().join('');
    }
  }, {
    key: 'renderObfuscatedLink',
    value: function renderObfuscatedLink() {
      var _props2 = this.props,
          tel = _props2.tel,
          sms = _props2.sms,
          facetime = _props2.facetime,
          email = _props2.email,
          obfuscate = _props2.obfuscate,
          headers = _props2.headers,
          children = _props2.children,
          style = _props2.style,
          linkText = _props2.linkText,
          others = _objectWithoutProperties(_props2, ['tel', 'sms', 'facetime', 'email', 'obfuscate', 'headers', 'children', 'style', 'linkText']);

      var obsStyle = _extends({}, style || {}, {
        unicodeBidi: 'bidi-override'
      });

      if (!children) {
        obsStyle.direction = 'rtl';
      }

      return _react2.default.createElement(
        'a',
        _extends({
          onClick: this.handleClick.bind(this),
          href: linkText || 'obfuscated'
        }, others, {
          style: obsStyle
        }),
        children || this.reverse(tel || sms || facetime || email).replace('(', ')').replace(')', '(')
      );
    }
  }, {
    key: 'handleClick',
    value: function handleClick(event) {
      event.preventDefault();
      var _props3 = this.props,
          tel = _props3.tel,
          sms = _props3.sms,
          facetime = _props3.facetime,
          email = _props3.email,
          headers = _props3.headers;

      window.location.href = createContactLink(tel, sms, facetime, email, headers);
    }
  }]);

  return Obfuscate;
}(_react.Component);

Obfuscate.propTypes = {
  children: _propTypes.node,
  tel: _propTypes.string,
  sms: _propTypes.string,
  facetime: _propTypes.string,
  email: _propTypes.string,
  headers: _propTypes.object,
  obfuscate: _propTypes.bool,
  style: _propTypes.object
};

Obfuscate.defaultProps = {
  obfuscate: true
};

exports.default = Obfuscate;<commit_msg>Add improved copy results<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var combineHeaders = function combineHeaders() {
  var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  return Object.keys(params).map(function (key) {
    return key + '=' + encodeURIComponent(params[key]);
  }).join('&');
};

var createContactLink = function createContactLink(tel, sms, facetime, email, headers) {
  var link = void 0;
  if (email) {
    link = 'mailto:' + email;
    if (headers) {
      link += '?' + combineHeaders(headers);
    }
  } else if (tel) {
    link = 'tel:' + tel;
  } else if (sms) {
    link = 'sms:' + sms;
  } else if (facetime) {
    link = 'facetime:' + facetime;
  }
  return link;
};

var Obfuscate = function (_Component) {
  _inherits(Obfuscate, _Component);

  function Obfuscate(props) {
    _classCallCheck(this, Obfuscate);

    var _this = _possibleConstructorReturn(this, (Obfuscate.__proto__ || Object.getPrototypeOf(Obfuscate)).call(this, props));

    _this.state = {
      isHovered: false
    };
    return _this;
  }

  _createClass(Obfuscate, [{
    key: 'render',
    value: function render() {
      return this.props.obfuscate ? this.renderObfuscatedLink() : this.renderLink();
    }
  }, {
    key: 'renderLink',
    value: function renderLink() {
      var _props = this.props,
          tel = _props.tel,
          sms = _props.sms,
          facetime = _props.facetime,
          email = _props.email,
          obfuscate = _props.obfuscate,
          headers = _props.headers,
          children = _props.children,
          others = _objectWithoutProperties(_props, ['tel', 'sms', 'facetime', 'email', 'obfuscate', 'headers', 'children']);

      return _react2.default.createElement(
        'a',
        _extends({
          href: createContactLink(tel, sms, facetime, email, headers)
        }, others),
        children || tel || sms || facetime || email
      );
    }
  }, {
    key: 'reverse',
    value: function reverse(s) {
      return s.split('').reverse().join('');
    }
  }, {
    key: 'renderObfuscatedLink',
    value: function renderObfuscatedLink() {
      var _this2 = this;

      var _props2 = this.props,
          tel = _props2.tel,
          sms = _props2.sms,
          facetime = _props2.facetime,
          email = _props2.email,
          obfuscate = _props2.obfuscate,
          headers = _props2.headers,
          children = _props2.children,
          style = _props2.style,
          linkText = _props2.linkText,
          others = _objectWithoutProperties(_props2, ['tel', 'sms', 'facetime', 'email', 'obfuscate', 'headers', 'children', 'style', 'linkText']);

      var obsStyle = this.state.isHovered === true ? _extends({}, style || {}, {
        unicodeBidi: 'bidi-override',
        direction: 'ltr'
      }) : _extends({}, style || {}, {
        unicodeBidi: 'bidi-override',
        direction: 'rtl'
      });

      var link = function link(state) {
        return _this2.state.isHovered === true ? tel || sms || facetime || email : children || _this2.reverse(tel || sms || facetime || email).replace('(', ')').replace(')', '(');
      };

      return _react2.default.createElement(
        'a',
        _extends({
          onClick: this.handleClick.bind(this),
          onMouseOver: this.handleCopy.bind(this),
          href: linkText || 'obfuscated'
        }, others, {
          style: obsStyle
        }),
        link()
      );
    }
  }, {
    key: 'handleClick',
    value: function handleClick(event) {
      event.preventDefault();
      var _props3 = this.props,
          tel = _props3.tel,
          sms = _props3.sms,
          facetime = _props3.facetime,
          email = _props3.email,
          headers = _props3.headers;

      window.location.href = createContactLink(tel, sms, facetime, email, headers);
    }
  }, {
    key: 'handleCopy',
    value: function handleCopy() {
      this.setState(function (state) {
        return _extends({}, state, {
          isHovered: true
        });
      });
    }
  }]);

  return Obfuscate;
}(_react.Component);

Obfuscate.propTypes = {
  children: _propTypes.node,
  tel: _propTypes.string,
  sms: _propTypes.string,
  facetime: _propTypes.string,
  email: _propTypes.string,
  headers: _propTypes.object,
  obfuscate: _propTypes.bool,
  style: _propTypes.object,
  linkText: _propTypes.string
};

Obfuscate.defaultProps = {
  obfuscate: true
};

exports.default = Obfuscate;<|endoftext|>


<commit_before>'use strict';

angular.module('notes.controllers', []).
	controller('MainCtrl', function ($scope, $location, $http) {

		$scope.noteList = [];
		$scope.isThereUnsavedData = false;
		$scope.isSaving = false;
		$scope.isUsingNoteArea = false;

		var path = $scope.path = $location.path();
		$scope.base = (path === '/') ? '' : path + '/';

		var getNoteDataLocation = function() {
			return '/data' + $location.path();
		};

		var getNoteListLocation = function() {
			return '/notes-at' + $location.path();
		};

		var saveNoteData = function () {
			if ($scope.isThereUnsavedData) {
				$scope.isThereUnsavedData = false;
				$scope.isSaving = true;

				var data = {};
				data.note = $scope.noteData;

				$http.put(getNoteDataLocation(), data)
				.success(function (data, status, headers, config) {
					console.log(data);
					$scope.isSaving = false;
				}).
				error(function (data, status, headers, config) {
					console.log(data);
					$scope.isSaving = false;
				});
			}
		};

		$scope.mouseEnterNoteArea = function() {
			$scope.isUsingNoteArea = true;
		};

		$scope.mouseLeaveNoteArea = function() {
			$scope.isUsingNoteArea = false;
		};

		var init = function () {
			$http.get(getNoteDataLocation())
			.success(function (data, status, headers, config) {
				if (status === 200) {
					$scope.noteData = data;
				}
				else {
					$scope.noteData = "";
				}

			}).
			error(function (data, status, headers, config) {
				console.log(data);
			});

			$http.get(getNoteListLocation())
			.success(function (data, status, headers, config) {
				if (status === 200) {
					$scope.noteList = data;
				}
				else {
					$scope.noteList = [];
				}
			}).
			error(function (data, status, headers, config) {
				console.log(data);
			});

			$scope.$watch('noteData', function (val, oldval) {
				if (oldval) {
					$scope.isThereUnsavedData = true;
				}
			}, true);

			var twoSeconds = 2 * 1000;
			setInterval(saveNoteData, twoSeconds);
		};

		init();
	});
<commit_msg>Fix: Ensure save requests are valid<commit_after>'use strict';

angular.module('notes.controllers', []).
	controller('MainCtrl', function ($scope, $location, $http) {

		$scope.noteList = [];
		$scope.isThereUnsavedData = false;
		$scope.isSaving = false;
		$scope.isUsingNoteArea = false;

		var path = $scope.path = $location.path();
		$scope.base = (path === '/') ? '' : path + '/';

		var getNoteDataLocation = function() {
			return '/data' + $location.path();
		};

		var getNoteListLocation = function() {
			return '/notes-at' + $location.path();
		};

		var saveNoteData = function () {

			if ($scope.isThereUnsavedData) {
				if (path !== $location.path()) {
					// Stop invalid requests that can happen
					// when we're navigating quickly.
					$scope.isThereUnsavedData = false;
					return;
				}

				$scope.isThereUnsavedData = false;
				$scope.isSaving = true;

				var data = {};
				data.note = $scope.noteData;

				$http.put(getNoteDataLocation(), data)
				.success(function (data, status, headers, config) {
					console.log(data);
					$scope.isSaving = false;
				}).
				error(function (data, status, headers, config) {
					console.log(data);
					$scope.isSaving = false;
				});
			}
		};

		$scope.mouseEnterNoteArea = function() {
			$scope.isUsingNoteArea = true;
		};

		$scope.mouseLeaveNoteArea = function() {
			$scope.isUsingNoteArea = false;
		};

		var init = function () {
			$http.get(getNoteDataLocation())
			.success(function (data, status, headers, config) {
				if (status === 200) {
					$scope.noteData = data;
				}
				else {
					$scope.noteData = "";
				}

			}).
			error(function (data, status, headers, config) {
				console.log(data);
			});

			$http.get(getNoteListLocation())
			.success(function (data, status, headers, config) {
				if (status === 200) {
					$scope.noteList = data;
				}
				else {
					$scope.noteList = [];
				}
			}).
			error(function (data, status, headers, config) {
				console.log(data);
			});

			$scope.$watch('noteData', function (val, oldval) {
				if (oldval) {
					$scope.isThereUnsavedData = true;
				}
			}, true);

			var twoSeconds = 2 * 1000;
			setInterval(saveNoteData, twoSeconds);
		};

		init();
	});
<|endoftext|>


<commit_before>mclab = window.mclab || {};
mclab.editor = mclab.editor || {};

mclab.editor.Tab = function (li, label, session, editor) {
  this.li = li;
  this.label = label;
  this.li.data('tab', this);
  this.session = session;
  this.editor = editor;
};

mclab.editor.Tab.prototype.getSiblings = function() {
  return this.li.siblings().map(function (i, li) {
    return $(li).data('tab');
  });
};

mclab.editor.Tab.prototype.getClosestTab = function() {
  var tab = this.li.prev('li');
  if (tab.length === 0) {
    tab = this.li.next('li');
  }
  if (tab.length !== 0) {
    return tab.data('tab') || null;
  }
  return null;
}

mclab.editor.Tab.prototype.isSelected = function() {
  return this.li.hasClass('active');
};

mclab.editor.Tab.prototype.unselect = function() {
  this.li.removeClass('active');
};

mclab.editor.Tab.prototype.select = function() {
  this.li.addClass('active');
  this.getSiblings().each(function (i, tab) { tab.unselect(); });
  this.editor.editor.setSession(this.session);
  this.editor.show();
};

mclab.editor.Tab.prototype.close = function() {
  if (this.isSelected()) {
    var tab = this.getClosestTab();
    if (tab !== null) {
      tab.select();
    }
  }

  this.editor.removeTabLabeled(this.label);
  this.li.remove();

  if (this.editor.getNumTabs() === 0) {
    this.editor.hide();
  }
};

mclab.editor.TabbedEditor = function(id, aceId) {
  this.el = $('#' + id);
  this.editor_el = $('#' + aceId);
  this.editor = ace.edit(aceId);
  this.editor.setTheme('ace/theme/solarized_dark');
  this.editor.setFontSize(14);
  this.editor.setShowPrintMargin(false);
  this.editor.setSession(this.newSession(''));
  this.editor.resize();
  this.editor.focus();

  $(window).resize(this.resizeAce.bind(this));
  this.resizeAce();

  this.tabs = {};

  this.el.find('ul.editor-tabs')
    .on('click', 'li:not(.editor-add-file)', function () {
      $(this).data('tab').select();
    })
    .on('click', 'span.glyphicon-remove', function() {
      $(this).parents('li').first().data('tab').close();
      return false;
    });

  this.newTabButton = this.el.find('.editor-add-file').first();
  this.newTabButton.on('click', (function () {
    var filename = prompt('Name: ');
    if (/[^\s]/.test(filename)) {
      this.createTab(filename).select();
    }
  }).bind(this));

  this.hide();
};

mclab.editor.TabbedEditor.prototype.hide = function() {
  this.editor_el.css('visibility', 'hidden');
};

mclab.editor.TabbedEditor.prototype.show = function() {
  this.editor_el.css('visibility', 'visible');
};

mclab.editor.TabbedEditor.prototype.getNumTabs = function(name) {
  return Object.keys(this.tabs).length;
};

mclab.editor.TabbedEditor.prototype.getTabLabeled = function(name) {
  return this.tabs[name];
};

mclab.editor.TabbedEditor.prototype.hasTabLabeled = function(name) {
  return name in this.tabs;
};

mclab.editor.TabbedEditor.prototype.removeTabLabeled = function(name) {
  delete this.tabs[name];
};

mclab.editor.TabbedEditor.prototype.createTab = function(filename, contents) {
  if (contents === undefined) {
    contents = '';
  }
  var li = $('<li>').append($('<a>').attr('href', '#').append(
    filename, ' ', mclab.utils.makeIcon('remove')));
  li.insertBefore(this.newTabButton);
  this.tabs[filename] = new mclab.editor.Tab(li, filename, this.newSession(contents), this);
  return this.tabs[filename];
};

mclab.editor.TabbedEditor.prototype.newSession = function(text) {
  var session = ace.createEditSession(text, 'ace/mode/matlab');
  session.setUseSoftTabs(true);
  return session;
};

mclab.editor.TabbedEditor.prototype.resizeAce = function() {
    var height = $(window).height();
    this.editor_el.height(3 * height / 4);
    this.editor.resize();
    // TODO(isbadawi): This shouldn't be here
    $('#console').height(height / 4);
    ace.edit('console').resize();
};

mclab.editor.TabbedEditor.prototype.overlayErrors = function(errors) {
  if (errors === undefined) {
    errors = [];
  }
  this.editor.getSession().setAnnotations(
    errors.map(function (err) {
      return {
        row: err.line - 1,
        column: err.col - 1,
        text: err.message,
        type: 'error'
      };
    })
  );
};

mclab.editor.TabbedEditor.prototype.tryParse = function() {
  mclab.ajax.parseCode(this.editor.getValue(), (function (data) {
    this.overlayErrors(data.errors);
  }).bind(this));
};

mclab.editor.TabbedEditor.prototype.startSyntaxChecker = function() {
  var typingTimer = null;
  var doneTypingInterval = 1000;

  var doneTyping = (function() {
    this.tryParse();
    typingTimer = null;
  }).bind(this);

  this.editor.on('change', function() {
    if (typingTimer != null) {
      clearTimeout(typingTimer);
      typingTimer = null;
    }
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
  });
};

mclab.editor.TabbedEditor.prototype.openFile = function(path) {
  if (this.hasTabLabeled(path)) {
    this.getTabLabeled(path).select();
    return;
  }
  var self = this;
  mclab.ajax.readFile(path, function (data) {
    self.createTab(path, data).select();
  });
};
<commit_msg>Don't create a tab if user hits cancel.<commit_after>mclab = window.mclab || {};
mclab.editor = mclab.editor || {};

mclab.editor.Tab = function (li, label, session, editor) {
  this.li = li;
  this.label = label;
  this.li.data('tab', this);
  this.session = session;
  this.editor = editor;
};

mclab.editor.Tab.prototype.getSiblings = function() {
  return this.li.siblings().map(function (i, li) {
    return $(li).data('tab');
  });
};

mclab.editor.Tab.prototype.getClosestTab = function() {
  var tab = this.li.prev('li');
  if (tab.length === 0) {
    tab = this.li.next('li');
  }
  if (tab.length !== 0) {
    return tab.data('tab') || null;
  }
  return null;
}

mclab.editor.Tab.prototype.isSelected = function() {
  return this.li.hasClass('active');
};

mclab.editor.Tab.prototype.unselect = function() {
  this.li.removeClass('active');
};

mclab.editor.Tab.prototype.select = function() {
  this.li.addClass('active');
  this.getSiblings().each(function (i, tab) { tab.unselect(); });
  this.editor.editor.setSession(this.session);
  this.editor.show();
};

mclab.editor.Tab.prototype.close = function() {
  if (this.isSelected()) {
    var tab = this.getClosestTab();
    if (tab !== null) {
      tab.select();
    }
  }

  this.editor.removeTabLabeled(this.label);
  this.li.remove();

  if (this.editor.getNumTabs() === 0) {
    this.editor.hide();
  }
};

mclab.editor.TabbedEditor = function(id, aceId) {
  this.el = $('#' + id);
  this.editor_el = $('#' + aceId);
  this.editor = ace.edit(aceId);
  this.editor.setTheme('ace/theme/solarized_dark');
  this.editor.setFontSize(14);
  this.editor.setShowPrintMargin(false);
  this.editor.setSession(this.newSession(''));
  this.editor.resize();
  this.editor.focus();

  $(window).resize(this.resizeAce.bind(this));
  this.resizeAce();

  this.tabs = {};

  this.el.find('ul.editor-tabs')
    .on('click', 'li:not(.editor-add-file)', function () {
      $(this).data('tab').select();
    })
    .on('click', 'span.glyphicon-remove', function() {
      $(this).parents('li').first().data('tab').close();
      return false;
    });

  this.newTabButton = this.el.find('.editor-add-file').first();
  this.newTabButton.on('click', (function () {
    var filename = prompt('Name: ');
    if (filename !== null && /[^\s]/.test(filename)) {
      this.createTab(filename).select();
    }
  }).bind(this));

  this.hide();
};

mclab.editor.TabbedEditor.prototype.hide = function() {
  this.editor_el.css('visibility', 'hidden');
};

mclab.editor.TabbedEditor.prototype.show = function() {
  this.editor_el.css('visibility', 'visible');
};

mclab.editor.TabbedEditor.prototype.getNumTabs = function(name) {
  return Object.keys(this.tabs).length;
};

mclab.editor.TabbedEditor.prototype.getTabLabeled = function(name) {
  return this.tabs[name];
};

mclab.editor.TabbedEditor.prototype.hasTabLabeled = function(name) {
  return name in this.tabs;
};

mclab.editor.TabbedEditor.prototype.removeTabLabeled = function(name) {
  delete this.tabs[name];
};

mclab.editor.TabbedEditor.prototype.createTab = function(filename, contents) {
  if (contents === undefined) {
    contents = '';
  }
  var li = $('<li>').append($('<a>').attr('href', '#').append(
    filename, ' ', mclab.utils.makeIcon('remove')));
  li.insertBefore(this.newTabButton);
  this.tabs[filename] = new mclab.editor.Tab(li, filename, this.newSession(contents), this);
  return this.tabs[filename];
};

mclab.editor.TabbedEditor.prototype.newSession = function(text) {
  var session = ace.createEditSession(text, 'ace/mode/matlab');
  session.setUseSoftTabs(true);
  return session;
};

mclab.editor.TabbedEditor.prototype.resizeAce = function() {
    var height = $(window).height();
    this.editor_el.height(3 * height / 4);
    this.editor.resize();
    // TODO(isbadawi): This shouldn't be here
    $('#console').height(height / 4);
    ace.edit('console').resize();
};

mclab.editor.TabbedEditor.prototype.overlayErrors = function(errors) {
  if (errors === undefined) {
    errors = [];
  }
  this.editor.getSession().setAnnotations(
    errors.map(function (err) {
      return {
        row: err.line - 1,
        column: err.col - 1,
        text: err.message,
        type: 'error'
      };
    })
  );
};

mclab.editor.TabbedEditor.prototype.tryParse = function() {
  mclab.ajax.parseCode(this.editor.getValue(), (function (data) {
    this.overlayErrors(data.errors);
  }).bind(this));
};

mclab.editor.TabbedEditor.prototype.startSyntaxChecker = function() {
  var typingTimer = null;
  var doneTypingInterval = 1000;

  var doneTyping = (function() {
    this.tryParse();
    typingTimer = null;
  }).bind(this);

  this.editor.on('change', function() {
    if (typingTimer != null) {
      clearTimeout(typingTimer);
      typingTimer = null;
    }
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
  });
};

mclab.editor.TabbedEditor.prototype.openFile = function(path) {
  if (this.hasTabLabeled(path)) {
    this.getTabLabeled(path).select();
    return;
  }
  var self = this;
  mclab.ajax.readFile(path, function (data) {
    self.createTab(path, data).select();
  });
};
<|endoftext|>


<commit_before>var RegStatusCard = {
    name: 'RegStatusCard',
    dom_target: undefined,

    render_init: function() {
        if (window.card_display_dates.is_after_start_of_registration_display_period &&
            window.card_display_dates.is_before_end_of_registration_display_period) {
            WSData.fetch_notice_data(RegStatusCard.render_upon_data,RegStatusCard.render_error);
            WSData.fetch_oquarter_data(RegStatusCard.render_upon_data, RegStatusCard.render_error);
        }
        else {
            $("#RegStatusCard").hide();
        }
    },
    render_upon_data: function() {
        //If more than one data source, multiple callbacks point to this function
        //Delay rendering until all requests are complete
        //Do something smart about not showing error if AJAX is pending
        if (!RegStatusCard._has_all_data()) {
            return;
        }
        RegStatusCard._render();
    },

    _has_all_data: function () {
        if (WSData.notice_data() && WSData.oquarter_data()) {
            return true;
        }
        return false;
    },
    render_error: function () {
        RegStatusCard.dom_target.html(CardWithError.render("Registration"));
    },

    _render_for_term: function(quarter, card) {
        var source = $("#reg_status_card").html();
        var template = Handlebars.compile(source);
        var reg_notices = Notices.get_notices_for_tag("reg_card_messages");
        var reg_holds = Notices.get_notices_for_tag("reg_card_holds");
        var reg_date = Notices.get_notices_for_tag("est_reg_date");
        var i, j;

        // Filter estimated registration dates for summer...
        var display_reg_dates = [];
        for (i = 0; i < reg_date.length; i++) {
            var notice = reg_date[i];
            for (j = 0; j < notice.attributes.length; j++) {
                var attribute = notice.attributes[j];
                if (quarter == "Summer") {
                    if ((attribute.name == "Quarter") && (attribute.value == "Summer")) {
                        display_reg_dates.push(notice);
                    }
                }
                else {
                    if ((attribute.name == "Quarter") && (attribute.value != "Summer")) {
                        display_reg_dates.push(notice);
                    }
                }
            }
        }

        var year, has_registration, next_term_data;
        if (quarter == "Summer") {
            next_term_data = WSData.oquarter_data().next_term_data;
            var terms = WSData.oquarter_data().terms;
            year = next_term_data.year;

            for (i = 0; i < terms.length; i++) {
                var term = terms[i];
                if ((term.quarter == quarter) && term.section_count) {
                    has_registration = true;
                }
            }
        }
        else {
            next_term_data = WSData.oquarter_data().next_term_data;
            quarter = next_term_data.quarter;
            year = next_term_data.year;
            has_registration = next_term_data.has_registration;
        }

        if (has_registration) {
            return;
        }

        var finaid_tags = ["reg_summeraid_avail_title"];
        var finaid_notices = [];
        var notice;
        for (i = 0; i < finaid_tags.length; i += 1) {
            notice = Notices.get_notices_for_tag(finaid_tags[i])[0];
            if (notice !== undefined) {
                finaid_notices.push(notice);
            }
        }
        //Get hold count from notice attrs
        var hold_count = reg_holds.length;
        return template({"finaid_notices": (finaid_notices.length > 0 ? finaid_notices : null),
                         "reg_notices": reg_notices,
                         "reg_holds": reg_holds,
                         "card": card,
                         "is_tacoma": window.user.tacoma,
                         "is_bothell": window.user.bothell,
                         "is_seattle": window.user.seattle,
                         "hold_count": hold_count,
                         "est_reg_date": display_reg_dates,
                         "reg_next_quarter" : quarter,
                         "reg_next_year": year
                         });
    },

    _add_events: function(card) {
        // show registration resources
        var id, holds_class;
        if (card) {
            id = "#show_reg_resources_"+card;
            holds_class = ".reg_disclosure_"+card;
        }
        else {
            id = "#show_reg_resources";
            holds_class = ".reg_disclosure";
        }

        // Prevent a closure on card
        (function(label) {
            $('body').on('click', id, function (ev) {
                var div, expose;
                if (label) {
                    div = $("#reg_resources_"+label);
                    expose = $("#show_reg_resources_"+label);
                }
                else {
                    div = $("#reg_resources");
                    expose = $("#show_reg_resources");
                }

                ev.preventDefault();
                var card = $(ev.target).closest("[data-type='card']");

                div.toggleClass("slide-show");

                if (div.hasClass("slide-show")) {
                    expose.text("Show less");
                    div.attr('aria-hidden', 'false');
                    expose.attr('title', 'Collapse to hide additional registration resources');
                    window.myuw_log.log_card(card, "expand");
                } else {
                    div.attr('aria-hidden', 'true');
                    expose.attr('title', 'Expand to show additional registration resources');
                    window.myuw_log.log_card(card, "collapse");

                    setTimeout(function() {
                        expose.text("Show more");
                    }, 700);
                }
            });

            // show hold details
            $('body').on('click', holds_class, function (ev) {
                ev.preventDefault();
                var div, expose, hide;
                if (label) {
                    div = $("#reg_holds_"+label);
                    expose = $("#show_reg_holds_"+label);
                    hide = $("#hide_reg_holds_"+label);
                }
                else {
                    div = $("#reg_holds");
                    expose = $("#show_reg_holds");
                    hide = $("#hide_reg_holds");
                }

                div.toggleClass("slide-show");
                if (div.hasClass("slide-show")) {
                    expose.hide();
                    hide.show();
                    window.myuw_log.log_card("RegHolds", "expand");
                }
                else {
                    window.myuw_log.log_card("RegHolds", "collapse");
                    setTimeout(function () {
                        expose.show();
                        hide.hide();
                    }, 700);
                }
            });

        })(card);
    },

    _render: function () {
        var next_term_data = WSData.oquarter_data().next_term_data;
        var reg_next_quarter = next_term_data.quarter;
        content = RegStatusCard._render_for_term(reg_next_quarter);

        if (!content) {
            RegStatusCard.dom_target.hide();
            return;
        }

        RegStatusCard._add_events();

        RegStatusCard.dom_target.html(content);
    }
};
<commit_msg>jslint fix<commit_after>var RegStatusCard = {
    name: 'RegStatusCard',
    dom_target: undefined,

    render_init: function() {
        if (window.card_display_dates.is_after_start_of_registration_display_period &&
            window.card_display_dates.is_before_end_of_registration_display_period) {
            WSData.fetch_notice_data(RegStatusCard.render_upon_data,RegStatusCard.render_error);
            WSData.fetch_oquarter_data(RegStatusCard.render_upon_data, RegStatusCard.render_error);
        }
        else {
            $("#RegStatusCard").hide();
        }
    },
    render_upon_data: function() {
        //If more than one data source, multiple callbacks point to this function
        //Delay rendering until all requests are complete
        //Do something smart about not showing error if AJAX is pending
        if (!RegStatusCard._has_all_data()) {
            return;
        }
        RegStatusCard._render();
    },

    _has_all_data: function () {
        if (WSData.notice_data() && WSData.oquarter_data()) {
            return true;
        }
        return false;
    },
    render_error: function () {
        RegStatusCard.dom_target.html(CardWithError.render("Registration"));
    },

    _render_for_term: function(quarter, card) {
        var source = $("#reg_status_card").html();
        var template = Handlebars.compile(source);
        var reg_notices = Notices.get_notices_for_tag("reg_card_messages");
        var reg_holds = Notices.get_notices_for_tag("reg_card_holds");
        var reg_date = Notices.get_notices_for_tag("est_reg_date");
        var i, j;

        // Filter estimated registration dates for summer...
        var display_reg_dates = [];
        for (i = 0; i < reg_date.length; i++) {
            var notice = reg_date[i];
            for (j = 0; j < notice.attributes.length; j++) {
                var attribute = notice.attributes[j];
                if (quarter == "Summer") {
                    if ((attribute.name == "Quarter") && (attribute.value == "Summer")) {
                        display_reg_dates.push(notice);
                    }
                }
                else {
                    if ((attribute.name == "Quarter") && (attribute.value != "Summer")) {
                        display_reg_dates.push(notice);
                    }
                }
            }
        }

        var year, has_registration, next_term_data;
        if (quarter == "Summer") {
            next_term_data = WSData.oquarter_data().next_term_data;
            var terms = WSData.oquarter_data().terms;
            year = next_term_data.year;

            for (i = 0; i < terms.length; i++) {
                var term = terms[i];
                if ((term.quarter == quarter) && term.section_count) {
                    has_registration = true;
                }
            }
        }
        else {
            next_term_data = WSData.oquarter_data().next_term_data;
            quarter = next_term_data.quarter;
            year = next_term_data.year;
            has_registration = next_term_data.has_registration;
        }

        if (has_registration) {
            return;
        }

        var finaid_tags = ["reg_summeraid_avail_title"];
        var finaid_notices = [];
        for (i = 0; i < finaid_tags.length; i += 1) {
            var fnotice = Notices.get_notices_for_tag(finaid_tags[i])[0];
            if (fnotice !== undefined) {
                finaid_notices.push(fnotice);
            }
        }
        //Get hold count from notice attrs
        var hold_count = reg_holds.length;
        return template({"finaid_notices": (finaid_notices.length > 0 ? finaid_notices : null),
                         "reg_notices": reg_notices,
                         "reg_holds": reg_holds,
                         "card": card,
                         "is_tacoma": window.user.tacoma,
                         "is_bothell": window.user.bothell,
                         "is_seattle": window.user.seattle,
                         "hold_count": hold_count,
                         "est_reg_date": display_reg_dates,
                         "reg_next_quarter" : quarter,
                         "reg_next_year": year
                         });
    },

    _add_events: function(card) {
        // show registration resources
        var id, holds_class;
        if (card) {
            id = "#show_reg_resources_"+card;
            holds_class = ".reg_disclosure_"+card;
        }
        else {
            id = "#show_reg_resources";
            holds_class = ".reg_disclosure";
        }

        // Prevent a closure on card
        (function(label) {
            $('body').on('click', id, function (ev) {
                var div, expose;
                if (label) {
                    div = $("#reg_resources_"+label);
                    expose = $("#show_reg_resources_"+label);
                }
                else {
                    div = $("#reg_resources");
                    expose = $("#show_reg_resources");
                }

                ev.preventDefault();
                var card = $(ev.target).closest("[data-type='card']");

                div.toggleClass("slide-show");

                if (div.hasClass("slide-show")) {
                    expose.text("Show less");
                    div.attr('aria-hidden', 'false');
                    expose.attr('title', 'Collapse to hide additional registration resources');
                    window.myuw_log.log_card(card, "expand");
                } else {
                    div.attr('aria-hidden', 'true');
                    expose.attr('title', 'Expand to show additional registration resources');
                    window.myuw_log.log_card(card, "collapse");

                    setTimeout(function() {
                        expose.text("Show more");
                    }, 700);
                }
            });

            // show hold details
            $('body').on('click', holds_class, function (ev) {
                ev.preventDefault();
                var div, expose, hide;
                if (label) {
                    div = $("#reg_holds_"+label);
                    expose = $("#show_reg_holds_"+label);
                    hide = $("#hide_reg_holds_"+label);
                }
                else {
                    div = $("#reg_holds");
                    expose = $("#show_reg_holds");
                    hide = $("#hide_reg_holds");
                }

                div.toggleClass("slide-show");
                if (div.hasClass("slide-show")) {
                    expose.hide();
                    hide.show();
                    window.myuw_log.log_card("RegHolds", "expand");
                }
                else {
                    window.myuw_log.log_card("RegHolds", "collapse");
                    setTimeout(function () {
                        expose.show();
                        hide.hide();
                    }, 700);
                }
            });

        })(card);
    },

    _render: function () {
        var next_term_data = WSData.oquarter_data().next_term_data;
        var reg_next_quarter = next_term_data.quarter;
        content = RegStatusCard._render_for_term(reg_next_quarter);

        if (!content) {
            RegStatusCard.dom_target.hide();
            return;
        }

        RegStatusCard._add_events();

        RegStatusCard.dom_target.html(content);
    }
};
<|endoftext|>


<commit_before>/** EXTENDED MODEL **/
(function() {
	if (!('User' in Garp.dataTypes)) {
		return;
	}

	/**
	 * Add some fields that trick Chrome into auto-filling them.
	 * This prevents form fuckup on the _actual_ fields below.
	 */
	function addHoneypotFieldsForChromeAutofill(target) {
		target.addField({
			hidden: true,
			disabled: false,
			allowBlank: true,
			name: '__fake_login__',
			fieldLabel: 'fake login'
		});

		target.addField({
			hidden: true,
			disabled: false,
			allowBlank: true,
			inputType: 'password',
			name: '__fake_password__',
			fieldLabel: 'fake password'
		});
	}

	Garp.dataTypes.User.on('init', function(){
		['AuthLocal', 'AuthPasswordless', 'AuthFacebook', 'AuthTwitter', 'AuthLinkedin']
			.map(function(rl) {
				this.removeRelationPanel(rl);
			}.bind(this));

		Ext.apply(this.getColumn('fullname'), {
			virtualSortField: 'first_name'
		});

		addHoneypotFieldsForChromeAutofill(this);

		this.addColumn({
			dataIndex: 'password',
			header: 'Password',
			renderer: Ext.emptyFn,
			hidden: true,
			virtual: true
		});

		this.addField({
			hidden: true,
			ref: '../../../passwordField',
			name: 'password'
		});

		this.addField({
			allowBlank: true,
			xtype: 'passwordfieldset',
			ref: '../../../changePassword',
			callback: function(field, val){
				var passwordField = field.refOwner.refOwner.passwordField;
				var email = field.refOwner.refOwner.getForm().findField('email');
				if (val || email._keepRequired) {
					email.allowBlank = false;
					email.label.addClass('required-field');
					passwordField.setValue(val);
				} else {
					email.allowBlank = true;
					email.label.removeClass('required-field');
					passwordField.setValue('');
				}
				field.refOwner.refOwner.getForm().items.each(function(){
					if (this.validate) {
						this.validate();
					}
				});
			}
		});

		this.addListener('loaddata', function(rec, formPanel){

			formPanel.changePassword.collapseAndHide();

			if (rec.get('image_id')) {
				formPanel.ImagePreview_image_id.setText(Garp.renderers.imageRelationRenderer(rec.get('image_id'), null, rec) || __('Add image'));
			}

			// Now remove some roles from the dropdown, based on ACL:
			var roleField = formPanel.getForm().findField('role');
			if (roleField) {
				var ownRole = Garp.localUser.role || 'User';
				Ext.each(Garp.ACL[ownRole].children, function(disabledRole){
					var idx = roleField.store.find('field1', disabledRole);
					roleField.store.removeAt(idx);
					// roleField.store.remove(disabledRole);
				});
			}
			var email = formPanel.getForm().findField('email');
			if(email && email.allowBlank === false){
				email._keepRequired = true;
			} else if(email){
				email._keepRequired = false;
			}

			// Cleanup honeypot fields
			setTimeout(function() {
				formPanel.getForm().remove(form.findField('__fake_login__'));
				formPanel.getForm().remove(form.findField('__fake_password__'));
			}, 1000);
		});

	});
})();
<commit_msg>Fixed undefined var<commit_after>/** EXTENDED MODEL **/
(function() {
	if (!('User' in Garp.dataTypes)) {
		return;
	}

	/**
	 * Add some fields that trick Chrome into auto-filling them.
	 * This prevents form fuckup on the _actual_ fields below.
	 */
	function addHoneypotFieldsForChromeAutofill(target) {
		target.addField({
			hidden: true,
			disabled: false,
			allowBlank: true,
			name: '__fake_login__',
			fieldLabel: 'fake login'
		});

		target.addField({
			hidden: true,
			disabled: false,
			allowBlank: true,
			inputType: 'password',
			name: '__fake_password__',
			fieldLabel: 'fake password'
		});
	}

	Garp.dataTypes.User.on('init', function(){
		['AuthLocal', 'AuthPasswordless', 'AuthFacebook', 'AuthTwitter', 'AuthLinkedin']
			.map(function(rl) {
				this.removeRelationPanel(rl);
			}.bind(this));

		Ext.apply(this.getColumn('fullname'), {
			virtualSortField: 'first_name'
		});

		addHoneypotFieldsForChromeAutofill(this);

		this.addColumn({
			dataIndex: 'password',
			header: 'Password',
			renderer: Ext.emptyFn,
			hidden: true,
			virtual: true
		});

		this.addField({
			hidden: true,
			ref: '../../../passwordField',
			name: 'password'
		});

		this.addField({
			allowBlank: true,
			xtype: 'passwordfieldset',
			ref: '../../../changePassword',
			callback: function(field, val){
				var passwordField = field.refOwner.refOwner.passwordField;
				var email = field.refOwner.refOwner.getForm().findField('email');
				if (val || email._keepRequired) {
					email.allowBlank = false;
					email.label.addClass('required-field');
					passwordField.setValue(val);
				} else {
					email.allowBlank = true;
					email.label.removeClass('required-field');
					passwordField.setValue('');
				}
				field.refOwner.refOwner.getForm().items.each(function(){
					if (this.validate) {
						this.validate();
					}
				});
			}
		});

		this.addListener('loaddata', function(rec, formPanel) {

			formPanel.changePassword.collapseAndHide();

			if (rec.get('image_id')) {
				formPanel.ImagePreview_image_id.setText(Garp.renderers.imageRelationRenderer(rec.get('image_id'), null, rec) || __('Add image'));
			}

			// Now remove some roles from the dropdown, based on ACL:
			var roleField = formPanel.getForm().findField('role');
			if (roleField) {
				var ownRole = Garp.localUser.role || 'User';
				Ext.each(Garp.ACL[ownRole].children, function(disabledRole) {
					var idx = roleField.store.find('field1', disabledRole);
					roleField.store.removeAt(idx);
					// roleField.store.remove(disabledRole);
				});
			}
			var email = formPanel.getForm().findField('email');
			if (email && email.allowBlank === false) {
				email._keepRequired = true;
			} else if (email) {
				email._keepRequired = false;
			}

			// Cleanup honeypot fields
			setTimeout(function() {
				formPanel.getForm().remove(formPanel.getForm().findField('__fake_login__'));
				formPanel.getForm().remove(formPanel.getForm().findField('__fake_password__'));
			}, 1000);
		});

	});
})();
<|endoftext|>


<commit_before>/*!
 * Titon Probe v0.3.0
 * Copyright 2010-2013, The Titon Project - http://titon.io
 * BSD-2 - https://github.com/titon/probe/blob/master/license.md
 */
!(function(i){var n,m=typeof module!=="undefined"&&module.exports;if(m){i._=require("lodash")}if(typeof i._==="undefined"){return}n=i._;n.extend(n,{empty:function(a){if(n.isArray(a)){a=[]}else{if(n.isString(a)){a=""}else{a={}}}return a},camelCase:function(a){return a.replace(/\W\D/g,function(b){return b.charAt(1).toUpperCase()})},capitalize:function(a){return a.replace(/\b[a-z]/g,function(b){return b.toUpperCase()})},slugify:function(a){return a.replace(/[A-Z]/g,function(b){return" "+b.charAt(0)}).replace(/\s{2,}/g," ").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+|-+$/,"").toLowerCase()},limit:function(c,b,a){return Math.min(a,Math.max(b,c))},round:function(b,a){a=Math.pow(10,a||0).toFixed(a<0?-a:0);return Math.round(b*a)/a},toFloat:function(a){return parseFloat(a)},toInt:function(a,b){return parseInt(a,b||10)}});var g=[[[Array],["compact","difference","drop","findIndex","findLastIndex","first","flatten","head","indexOf","initial","intersection","last","lastIndexOf","pull","range","remove","rest","sortedIndex","tail","take","union","uniq","unique","unzip","without","xor","zip","zipObject"]],[[Array,Object,String],["all","any","at","collect","contains","countBy","detect","empty","each","eachRight","every","filter","find","findLast","findWhere","foldl","foldr","forEach","forEachRight","groupBy","include","indexBy","inject","invoke","map","max","min","pluck","reduce","reduceRight","reject","sample","select","shuffle","size","some","sortBy","toArray","where","constant"]],[[Function],["bind","compose","curry","debounce","defer","delay","memoize","once","partial","partialRight","throttle","createCallback"]],[[Object],["assign","clone","cloneDeep","defaults","extend","findKey","findLastKey","forIn","forInRight","forOwn","forOwnRight","functions","has","invert","keys","mapValues","merge","methods","mixin","omit","pairs","pick","property","result","transform","values"]],[[String],["escape","unescape","template","uniqueId","camelCase","slugify","capitalize"]],[[Number],["times","limit","round","toFloat","toInt","parseInt"]],[[Array,Object,String,Number],["isEmpty","isEqual","isUndefined","isNull","toString","valueOf"]]];var k,j,h,d,f,e,l=Array.prototype.slice;for(k=0;(d=g[k]);k++){for(j=0;(f=d[0][j]);j++){for(h=0;(e=d[1][h]);h++){if(!n[e]){continue}if(f[e]||f.prototype[e]){continue}if(f===Object){f[e]=n[e];continue}(function(a){f.prototype[a]=function(){var b=l.call(arguments)||[];b.unshift(this);return n[a].apply(this,b)}}(e))}}}if(m){exports._=n}})(this);<commit_msg>minified with grunt<commit_after>/*!
 * Titon Probe v0.3.0
 * Copyright 2010-2013, The Titon Project - http://titon.io
 * BSD-2 - https://github.com/titon/probe/blob/master/license.md
 */
!function(a){"use strict";var b,c="undefined"!=typeof module&&module.exports;if(c&&(a._=require("lodash")),"undefined"!=typeof a._){b=a._,b.extend(b,{empty:function(a){return a=b.isArray(a)?[]:b.isString(a)?"":{}},camelCase:function(a){return a.replace(/\W\D/g,function(a){return a.charAt(1).toUpperCase()})},capitalize:function(a){return a.replace(/\b[a-z]/g,function(a){return a.toUpperCase()})},slugify:function(a){return a.replace(/[A-Z]/g,function(a){return" "+a.charAt(0)}).replace(/\s{2,}/g," ").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+|-+$/,"").toLowerCase()},limit:function(a,b,c){return Math.min(c,Math.max(b,a))},round:function(a,b){return b=Math.pow(10,b||0).toFixed(0>b?-b:0),Math.round(a*b)/b},toFloat:function(a){return parseFloat(a)},toInt:function(a,b){return parseInt(a,b||10)}});var d,e,f,g,h,i,j=[[[Array],["compact","difference","drop","findIndex","findLastIndex","first","flatten","head","indexOf","initial","intersection","last","lastIndexOf","pull","range","remove","rest","sortedIndex","tail","take","union","uniq","unique","unzip","without","xor","zip","zipObject"]],[[Array,Object,String],["all","any","at","collect","contains","countBy","detect","empty","each","eachRight","every","filter","find","findLast","findWhere","foldl","foldr","forEach","forEachRight","groupBy","include","indexBy","inject","invoke","map","max","min","pluck","reduce","reduceRight","reject","sample","select","shuffle","size","some","sortBy","toArray","where","constant"]],[[Function],["bind","compose","curry","debounce","defer","delay","memoize","once","partial","partialRight","throttle","createCallback"]],[[Object],["assign","clone","cloneDeep","defaults","extend","findKey","findLastKey","forIn","forInRight","forOwn","forOwnRight","functions","has","invert","keys","mapValues","merge","methods","mixin","omit","pairs","pick","property","result","transform","values"]],[[String],["escape","unescape","template","uniqueId","camelCase","slugify","capitalize"]],[[Number],["times","limit","round","toFloat","toInt","parseInt"]],[[Array,Object,String,Number],["isEmpty","isEqual","isUndefined","isNull","toString","valueOf"]]],k=Array.prototype.slice;for(d=0;g=j[d];d++)for(e=0;h=g[0][e];e++)for(f=0;i=g[1][f];f++)b[i]&&(h[i]||h.prototype[i]||(h!==Object?!function(a){h.prototype[a]=function(){var c=k.call(arguments)||[];return c.unshift(this),b[a].apply(this,c)}}(i):h[i]=b[i]));c&&(exports._=b)}}(this);<|endoftext|>