zhyd.comment.js 19.5 KB
Newer Older
Y
yadong.zhang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/**
 * MIT License
 *
 * Copyright (c) 2018 yadong.zhang
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *
Y
yadong.zhang 已提交
25
 * 评论插件(md版)
Y
yadong.zhang 已提交
26 27 28
 *
 * @date 2018-01-05 10:57
 * @author zhyd(yadong.zhang0415#gmail.com)
Y
yadong.zhang 已提交
29
 * @link https://www.zhyd.me
30 31 32 33 34 35 36 37 38 39 40 41
 */
var _form = {
    valid: function(form){
        var valid = true;
        $(form).find("small").each(function(){
            if($(this).attr("data-bv-result") == "INVALID"){
                valid = false;
            }
        });
        return valid;
    }
};
Y
yadong.zhang 已提交
42

43 44 45 46 47 48 49 50 51 52 53 54 55
$.extend({
    comment: {
        detailKey: 'comment-detail',
        sid: 0,
        _commentDetailModal: '',
        _detailForm: '',
        _detailFormBtn: '',
        _closeBtn: '',
        _commentPid: '',
        _commentPlace: '',
        _commentPost: '',
        _cancelReply: '',
        _commentReply: '',
Y
yadong.zhang 已提交
56
        _simplemde: null,
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
        initDom: function () {
            $.comment._commentDetailModal = $('#comment-detail-modal');
            $.comment._detailForm = $('#detail-form');
            $.comment._detailFormBtn = $('#detail-form-btn');
            $.comment._closeBtn = $('#comment-detail-modal .close');
            $.comment._commentPid = $('#comment-pid');
            $.comment._commentPlace = $('#comment-place');
            $.comment._commentPost = $('#comment-post');
            $.comment._cancelReply = $('#cancel-reply');
            $.comment._commentReply = $('.comment-reply');
        },
        init: function (options) {
            var $box = $('#comment-box');
            if (!$box || !$box[0]) {
                return;
            }
            var op = $.extend({
            }, options);
            var commentBox = '<div id="comment-place">'
                    + '<div class="comment-post" id="comment-post" style="position: relative">'
77
                    + '<h5 class="custom-title"><i class="fa fa-commenting-o fa-fw icon"></i><strong>评论</strong><small></small></h5>'
78
                    + '<form class="form-horizontal" role="form" id="comment-form">'
Y
yadong.zhang 已提交
79
                    + '<div class="cancel-reply" id="cancel-reply" style="display: none;"><a href="javascript:void(0);" onclick="$.comment.cancelReply(this)" rel="external nofollow"><i class="fa fa-share"></i>取消回复</a></div>'
80
                    + '<input type="hidden" name="pid" id="comment-pid" value="0" size="22" tabindex="1">'
Y
yadong.zhang 已提交
81 82
                    + '<textarea id="comment_content" class="form-control col-md-7 col-xs-12 valid" style="display: none"></textarea>'
                    + '<textarea name="content" style="display: none"></textarea>'
83
                    + '<div style="position: absolute;right: 10px;bottom: 70px;font-size: 14px;color: #dbdada;z-index: 1;">' + op.wmName + '<br>' + op.wmUrl + '<br>' + op.wmDesc + '</div>'
84 85 86 87 88 89
                    + '<a id="comment-form-btn" type="button" data-loading-text="正在提交评论..." class="btn btn-default btn-block">提交评论</a>'
                    + '</form></div></div>';
            $box.html(commentBox);
            // 初始化并缓存常用的dom元素
            $.comment.initDom();
            // 创建编辑框
Y
yadong.zhang 已提交
90
            this._simplemde = $.comment.createEdit(op);
91 92 93 94
            $.comment.loadCommentList($box);
            $.comment.initValidatorPlugin();
        },
        createEdit: function (options) {
Y
yadong.zhang 已提交
95 96 97 98 99
            var simplemde = new SimpleMDE({
                element: document.getElementById("comment_content"),
                toolbar: ["bold", "italic", "|", "code", "quote", "|", "preview", "|", "guide"],
                autoDownloadFontAwesome: false,
                // autofocus: true,
智布道's avatar
智布道 已提交
100
                placeholder: options.placeholder || "说点什么吧",
Y
yadong.zhang 已提交
101 102 103 104 105 106 107 108
                renderingConfig: {
                    codeSyntaxHighlighting: true
                },
                tabSize: 4
            });
            simplemde.codemirror.on("change", function(){
                $("textarea[name=content]").val(simplemde.markdown(simplemde.value()));
            });
Y
yadong.zhang 已提交
109

Y
yadong.zhang 已提交
110
            return simplemde;
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        },
        loadCommentList: function (box, pageNumber) {
            var sid = box.attr("data-id");
            if(!sid){
                throw "未指定sid!";
            }
            this.sid = sid;
            $.ajax({
                type: "post",
                url: "/api/comments",
                data: {sid: sid, pageNumber: pageNumber || 1},
                success: function (json) {
                    $.alert.ajaxSuccess(json);
                    // 加载 评论列表 start
                    var commentList = json.data.commentList;
                    var commentListBox  = '';
                    if(!commentList){
                        commentListBox = '<div class="commentList">'
129
                                + '<h5 class="custom-title"><i class="fa fa-comments-o fa-fw icon"></i><strong>0 评论</strong><small></small></h5>'
130 131 132 133 134 135 136 137 138 139 140 141
                                + '<ul class="comment">';
                        commentListBox += '<li><div class="list-comment-empty-w fade-in">'
                                +'<div class="empty-prompt-w">'
                                +'<span class="prompt-null-w">还没有评论,快来抢沙发吧!</span>'
                                +'</div>'
                                +'</div></li>';
                        // 加载 评论列表 end
                        commentListBox += '</ul></div>';
                        $(commentListBox).appendTo(box);
                    }else{
                        // 首次加载-刷新页面后第一次加载,此时没有点击加载更多进行分页
                        if(!pageNumber) {
Y
yadong.zhang 已提交
142
                            commentListBox = '<div class="commentList">'
143
                                    + '<h5 class="custom-title"><i class="fa fa-comments-o fa-fw icon"></i><strong>' + json.data.total + ' 评论</strong><small></small></h5>'
Y
yadong.zhang 已提交
144
                                    + '<ul class="comment">';
145 146 147 148 149
                        }
                        for(var i = 0, len = commentList.length; i < len ; i ++){
                            var comment = commentList[i];
                            var userUrl = comment.url || "javascript:void(0)";
                            var parent = comment.parent;
Y
yadong.zhang 已提交
150 151 152 153
                            var adminIcon = '';
                            if(comment.admin){
                                adminIcon = '<img src="/img/author.png" alt="" class="author-icon" title="管理员">';
                            }
154 155 156 157
                            var parentQuote = parent ? '<a href="#comment-' + parent.id + '" class="comment-quote">@' + parent.nickname + '</a><div style="background-color: #f5f5f5;padding: 5px;margin: 5px;border-radius: 4px;"><i class="fa fa-quote-left"></i><p></p><div style="padding-left: 10px;">' + filterXSS(parent.content) + '</div></div>' : '';
                            commentListBox += '<li>' +
                                    '    <div class="comment-body fade-in" id="comment-'+comment.id+'">' +
                                    '        <div class="cheader">' +
Y
yadong.zhang 已提交
158
                                    '           <div class="user-img">' + adminIcon + '<img class="userImage" src="' + filterXSS(comment.avatar) + '" onerror="this.src=\'' + appConfig.staticPath + '/img/user.png\'"></div>' +
159 160 161
                                    '           <div class="user-info">' +
                                    '              <div class="nickname">' +
                                    '                 <a target="_blank" href="' + userUrl + '" rel="external nofollow"><strong>' + comment.nickname + '</strong></a>' +
Y
yadong.zhang 已提交
162 163
                                    '                <i class="icons os-' + comment.osShortName + '" title="' + comment.os + '"></i>' +
                                    '                <i class="icons browser-' + comment.browserShortName + '" title="' + comment.browser + '"></i>' +
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
                                    '              </div>            ' +
                                    '             <div class="timer">' +
                                    '                  <i class="fa fa-clock-o fa-fw"></i>' + comment.createTimeString +
                                    '                  <i class="fa fa-map-marker fa-fw"></i>' + comment.address +
                                    '              </div>' +
                                    '          </div>' +
                                    '        </div>' +
                                    '        <div class="content">' + parentQuote + '<div>' + filterXSS(comment.content) + '</div></div>' +
                                    '        <div class="sign">' +
                                    '            <a href="javascript:void(0);" class="comment-up" onclick="$.comment.praise(' + comment.id + ', this)"><i class="fa fa-thumbs-o-up"></i>赞(<span class="count">' + comment.support + '</span>)<i class="sepa"></i></a>' +
                                    '            <a href="javascript:void(0);" class="comment-down" onclick="$.comment.step(' + comment.id + ', this)"><i class="fa fa-thumbs-o-down"></i>踩(<span class="count">' + comment.oppose + '</span>)<i class="sepa"></i></a>' +
                                    '            <a href="javascript:void(0);" class="comment-reply" onclick="$.comment.reply(' + comment.id + ', this)"><i class="fa fa-reply"></i>回复</a>' +
                                    '            <a href="javascript:void(0);" class="comment-flag hide" onclick="$.comment.report(' + comment.id + ', this)"><i class="fa fa-flag"></i>举报</a>' +
                                    '        </div>' +
                                    '    </div>' +
                                    '</li>';
                        }
                        // 如果存在下一页,则显示加载按钮
                        if(json.data.hasNextPage){
Y
yadong.zhang 已提交
183 184
                            commentListBox += '<li><div class="list-comment-empty-w fade-in">'
                                    +'<div class="empty-prompt-w">'
185
                                    +'<span class="prompt-null-w pointer load-more">加载更多 <i class="fa fa-angle-double-down"></i></span>'
Y
yadong.zhang 已提交
186 187
                                    +'</div>'
                                    +'</div></li>';
188 189 190 191 192
                        }
                        // 加载 评论列表 end

                        if(!pageNumber) {
                            // 首次加载-刷新页面后第一次加载,此时没有点击加载更多进行分页
Y
yadong.zhang 已提交
193 194 195
                            commentListBox += '</ul></div>';
                            $(commentListBox).appendTo(box);
                        }else{
196 197 198
                            // 点击加载更多时,列表追加到ul中
                            $(commentListBox).appendTo($(".comment"));
                        }
Y
yadong.zhang 已提交
199

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
                        // 加载更多按钮
                        $(".load-more").click(function () {
                            $(this).parents('li').hide();
                            $.comment.loadCommentList(box, json.data.nextPage)
                        });
                    }
                },
                error: $.alert.ajaxError
            });
        },
        initValidatorPlugin: function () {
            $.comment._detailForm.bootstrapValidator({
                message: "输入值无效",
                feedbackIcons: {
                    valid: "fa fa-check",
                    invalid: "fa fa-remove",
                    validating: "fa fa-refresh"
                },
                fields: {
                    nickname: {
                        validators: {
                            notEmpty: {
                                message: "昵称必填"
Y
yadong.zhang 已提交
223 224 225
                            }
                        }
                    },
226 227 228 229
                    url: {
                        validators: {
                            uri: {
                                message: "URL地址不正确"
Y
yadong.zhang 已提交
230
                            }
231 232 233 234 235 236
                        }
                    },
                    email: {
                        validators: {
                            emailAddress: {
                                message: "邮箱地址不正确"
Y
yadong.zhang 已提交
237 238 239 240
                            }
                        }
                    }
                }
241 242 243 244 245 246 247 248 249 250 251
            });
        },
        submit: function (target) {
            var $this = $(target);
            $this.button('loading');
            var detail = localStorage.getItem(this.detailKey);
            var data = $("#comment-form").serialize();
            if(!detail){
            }else{
                var detailInfoJson = $.tool.parseFormSerialize(detail);
                $.comment._detailForm.find("input").each(function () {
Y
yadong.zhang 已提交
252
                    var $this = $(this);
253 254 255
                    var inputName = $this.attr("name");
                    if(detailInfoJson[inputName]){
                        $this.val(detailInfoJson[inputName]);
Y
yadong.zhang 已提交
256 257
                    }
                });
258 259 260
                var $img = $.comment._detailForm.find('img');
                $img.attr('src', detailInfoJson.avatar);
                $img.removeClass('hide');
Y
yadong.zhang 已提交
261

262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
            }
            this._commentDetailModal.modal('show');
            this._closeBtn.unbind('click');
            this._closeBtn.click(function () {
                setTimeout(function () {
                    $this.html("<i class='fa fa-close'></i>取消操作...");
                    setTimeout(function () {
                        $this.button('reset');
                    }, 1000);
                }, 500);
            });
            // 模态框抖动
            this._commentDetailModal.find('.modal-content').addClass("shake");
            $.comment._detailForm.find("input[name=qq]").unbind('change');
            $.comment._detailForm.find("input[name=qq]").change(function () {
                var $this = $(this);
                var qq = $this.val();
                var $nextImg = $this.next('img');
                if(qq){
Y
yadong.zhang 已提交
281 282
                    $.ajax({
                        type: "post",
283
                        url: "/api/qq/" + qq,
Y
yadong.zhang 已提交
284
                        success: function (json) {
Y
yadong.zhang 已提交
285
                            $.alert.ajaxSuccess(json);
286 287 288 289 290 291 292 293 294 295
                            var data = json.data;
                            $.comment._detailForm.find("input").each(function () {
                                var $this = $(this);
                                var inputName = $this.attr("name");
                                if(data[inputName]){
                                    $this.val(data[inputName]);
                                }
                            });
                            $nextImg.attr('src', data.avatar);
                            $nextImg.removeClass('hide');
Y
yadong.zhang 已提交
296
                        },
297
                        error: $.alert.ajaxError
Y
yadong.zhang 已提交
298
                    });
299 300
                }else{
                    $nextImg.addClass('hide');
Y
yadong.zhang 已提交
301
                }
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

            });

            // 提交评论
            this._detailFormBtn.unbind('click');
            this._detailFormBtn.click(function () {
                $.comment._detailForm.bootstrapValidator("validate");
                if (_form.valid($.comment._detailForm)) {
                    data = data + "&" + $.comment._detailForm.serialize();
                    localStorage.setItem($.comment.detailKey, $.comment._detailForm.serialize());
                    submitForm(data);
                }
            });

            function submitForm(data) {
Y
yadong.zhang 已提交
317
                console.log(data);
Y
yadong.zhang 已提交
318 319
                $.ajax({
                    type: "post",
320 321
                    url: "/api/comment",
                    data: data + '&sid=' + $.comment.sid,
Y
yadong.zhang 已提交
322
                    success: function (json) {
Y
yadong.zhang 已提交
323
                        $.alert.ajaxSuccess(json);
324 325 326 327 328 329 330 331 332
                        $.comment._commentDetailModal.modal('hide');

                        setTimeout(function () {
                            $this.html("<i class='fa fa-check'></i>" + json.message);
                            setTimeout(function () {
                                $this.button('reset');
                                window.location.reload();
                            }, 3000);
                        }, 1000);
Y
yadong.zhang 已提交
333
                    },
334
                    error: function (data) {
Y
yadong.zhang 已提交
335
                        // console.log(data);
Y
yadong.zhang 已提交
336
                        $.alert.ajaxError();
337
                        $this.button('reset');
Y
yadong.zhang 已提交
338
                    }
Y
yadong.zhang 已提交
339 340
                });
            }
341 342
        },
        reply: function (pid, target) {
Y
yadong.zhang 已提交
343
            // console.log(pid);
344 345
            this._commentPid.val(pid);
            this._cancelReply.show();
Y
yadong.zhang 已提交
346
            // this._commentReply.show();
347
            $(target).hide();
Y
yadong.zhang 已提交
348
            $(target).parents('.comment-body').append($("#comment-form"));
349 350 351 352 353
        },
        cancelReply: function (target) {
            this._commentPid.val("");
            this._cancelReply.hide();
            $(target).parents(".comment-body").find('.comment-reply').show();
Y
yadong.zhang 已提交
354
            this._commentPost.append($("#comment-form"));
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
        },
        /* 赞 */
        praise: function (pid, target) {
            $.bubble.unbind();
            $.ajax({
                type: "post",
                url: "/api/doSupport/" + pid,
                success: function (json) {
                    $.alert.ajaxSuccess(json);
                    if(json.status == 200){
                        $(target).effectBubble({y:-80, className:'thumb-bubble', fontSize: 1, content: '<i class="fa fa-smile-o"></i>+1'});
                        var oldCount = $(target).find('span.count').text();
                        $(target).find('span.count').text(parseInt(oldCount) + 1);
                    }
                    $.bubble.init();
                },
                error: function () {
                    $.alert.ajaxError();
                    $.bubble.init();
                }
            });
        },
        /* 踩 */
        step: function (pid, target) {
            $.bubble.unbind();
            $.ajax({
                type: "post",
                url: "/api/doOppose/" + pid,
                success: function (json) {
                    $.alert.ajaxSuccess(json);
                    if(json.status == 200){
                        $(target).effectBubble({y:-80, className:'thumb-bubble', fontSize: 1, content: '<i class="fa fa-meh-o"></i>+1'});
                        var oldCount = $(target).find('span.count').text();
                        $(target).find('span.count').text(parseInt(oldCount) + 1);
                    }
                    $.bubble.init();
                },
                error: function () {
                    $.alert.ajaxError();
                    $.bubble.init();
                }
            });
        },
        /* 举报 */
        report: function (pid, target) {
Y
yadong.zhang 已提交
400
        }
401 402
    }
});
Y
yadong.zhang 已提交
403