#47 Implements the reply and edit functionality for comments.

This commit is contained in:
Abijeet 2017-05-16 00:40:14 +05:30
parent 4f231d1bf0
commit 03e5d61798
10 changed files with 149 additions and 95 deletions

View File

@ -5,8 +5,8 @@ use Illuminate\Support\Facades\DB;
class Comment extends Ownable class Comment extends Ownable
{ {
protected $fillable = ['text', 'html']; protected $fillable = ['text', 'html', 'parent_id'];
/** /**
* Get the entity that this comment belongs to * Get the entity that this comment belongs to
* @return \Illuminate\Database\Eloquent\Relations\MorphTo * @return \Illuminate\Database\Eloquent\Relations\MorphTo
@ -15,7 +15,7 @@ class Comment extends Ownable
{ {
return $this->morphTo('entity'); return $this->morphTo('entity');
} }
/** /**
* Get the page that this comment is in. * Get the page that this comment is in.
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
@ -24,32 +24,32 @@ class Comment extends Ownable
{ {
return $this->belongsTo(Page::class); return $this->belongsTo(Page::class);
} }
/** /**
* Get the owner of this comment. * Get the owner of this comment.
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/ */
public function user() public function user()
{ {
return $this->belongsTo(User::class); return $this->belongsTo(User::class);
} }
public function getCommentsByPage($pageId, $commentId, $pageNum = 0, $limit = 0) { public function getCommentsByPage($pageId, $commentId, $pageNum = 0, $limit = 0) {
$query = static::newQuery(); $query = static::newQuery();
$query->join('users AS u', 'comments.created_by', '=', 'u.id'); $query->join('users AS u', 'comments.created_by', '=', 'u.id');
$query->leftJoin('users AS u1', 'comments.updated_by', '=', 'u1.id'); $query->leftJoin('users AS u1', 'comments.updated_by', '=', 'u1.id');
$query->leftJoin('images AS i', 'i.id', '=', 'u.image_id'); $query->leftJoin('images AS i', 'i.id', '=', 'u.image_id');
$query->selectRaw('comments.id, text, html, comments.created_by, comments.updated_by, comments.created_at, comments.updated_at, ' $query->selectRaw('comments.id, text, html, comments.created_by, comments.updated_by, comments.created_at, comments.updated_at, '
. 'u.name AS created_by_name, u1.name AS updated_by_name, ' . 'u.name AS created_by_name, u1.name AS updated_by_name, '
. '(SELECT count(c.id) FROM bookstack.comments c WHERE c.parent_id = comments.id AND page_id = ?) AS cnt_sub_comments, i.url AS avatar ', . '(SELECT count(c.id) FROM bookstack.comments c WHERE c.parent_id = comments.id AND page_id = ?) AS cnt_sub_comments, i.url AS avatar ',
[$pageId]); [$pageId]);
if (empty($commentId)) { if (empty($commentId)) {
$query->whereRaw('page_id = ? AND parent_id IS NULL', [$pageId]); $query->whereRaw('page_id = ? AND parent_id IS NULL', [$pageId]);
} else { } else {
$query->whereRaw('page_id = ? AND parent_id = ?', [$pageId, $commentId]); $query->whereRaw('page_id = ? AND parent_id = ?', [$pageId, $commentId]);
} }
$query->orderBy('created_at'); $query->orderBy('created_at');
return $query; return $query;
} }

View File

@ -2,18 +2,19 @@
use BookStack\Repos\CommentRepo; use BookStack\Repos\CommentRepo;
use BookStack\Repos\EntityRepo; use BookStack\Repos\EntityRepo;
use BookStack\Comment;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Views;
// delete -checkOwnablePermission \ // delete -checkOwnablePermission \
class CommentController extends Controller class CommentController extends Controller
{ {
protected $entityRepo; protected $entityRepo;
public function __construct(EntityRepo $entityRepo, CommentRepo $commentRepo) public function __construct(EntityRepo $entityRepo, CommentRepo $commentRepo, Comment $comment)
{ {
$this->entityRepo = $entityRepo; $this->entityRepo = $entityRepo;
$this->commentRepo = $commentRepo; $this->commentRepo = $commentRepo;
$this->comment = $comment;
parent::__construct(); parent::__construct();
} }
@ -43,10 +44,10 @@ class CommentController extends Controller
// create a new comment. // create a new comment.
$this->checkPermission('comment-create-all'); $this->checkPermission('comment-create-all');
$comment = $this->commentRepo->create($page, $request->only(['text', 'html', 'parent_id'])); $comment = $this->commentRepo->create($page, $request->only(['text', 'html', 'parent_id']));
$respMsg = trans('entities.comment_created'); $respMsg = trans('entities.comment_created');
} else { } else {
// update existing comment // update existing comment
// get comment by ID and check if this user has permission to update. // get comment by ID and check if this user has permission to update.
$comment = $this->comment->findOrFail($commentId); $comment = $this->comment->findOrFail($commentId);
$this->checkOwnablePermission('comment-update', $comment); $this->checkOwnablePermission('comment-update', $comment);
$this->commentRepo->update($comment, $request->all()); $this->commentRepo->update($comment, $request->all());
@ -59,7 +60,7 @@ class CommentController extends Controller
]); ]);
} }
public function destroy($id) { public function destroy($id) {
$comment = $this->comment->findOrFail($id); $comment = $this->comment->findOrFail($id);
$this->checkOwnablePermission('comment-delete', $comment); $this->checkOwnablePermission('comment-delete', $comment);
@ -67,13 +68,13 @@ class CommentController extends Controller
// //
} }
public function getComments($pageId, $commentId = null) { public function getCommentThread($pageId, $commentId = null) {
try { try {
$page = $this->entityRepo->getById('page', $pageId, true); $page = $this->entityRepo->getById('page', $pageId, true);
} catch (ModelNotFoundException $e) { } catch (ModelNotFoundException $e) {
return response('Not found', 404); return response('Not found', 404);
} }
if($page->draft) { if($page->draft) {
// cannot add comments to drafts. // cannot add comments to drafts.
return response()->json([ return response()->json([
@ -81,15 +82,15 @@ class CommentController extends Controller
'message' => trans('errors.no_comments_for_draft'), 'message' => trans('errors.no_comments_for_draft'),
], 400); ], 400);
} }
$this->checkOwnablePermission('page-view', $page); $this->checkOwnablePermission('page-view', $page);
$comments = $this->commentRepo->getCommentsForPage($pageId, $commentId); $comments = $this->commentRepo->getCommentsForPage($pageId, $commentId);
if (empty($commentId)) { if (empty($commentId)) {
// requesting for parent level comments, send the total count as well. // requesting for parent level comments, send the total count as well.
$totalComments = $this->commentRepo->getCommentCount($pageId); $totalComments = $this->commentRepo->getCommentCount($pageId);
return response()->json(array('success' => true, 'comments'=> $comments, 'total' => $totalComments)); return response()->json(['success' => true, 'comments'=> $comments, 'total' => $totalComments]);
} }
return response()->json(array('success' => true, 'comments'=> $comments)); return response()->json(['success' => true, 'comments'=> $comments]);
} }
} }

View File

@ -10,7 +10,7 @@ use BookStack\Page;
class CommentRepo { class CommentRepo {
/** /**
* *
* @var Comment $comment * @var Comment $comment
*/ */
protected $comment; protected $comment;
@ -25,7 +25,7 @@ class CommentRepo {
$comment->fill($data); $comment->fill($data);
// new comment // new comment
$comment->page_id = $page->id; $comment->page_id = $page->id;
$comment->created_by = $userId; $comment->created_by = $userId;
$comment->save(); $comment->save();
return $comment; return $comment;
} }
@ -37,13 +37,13 @@ class CommentRepo {
$comment->save(); $comment->save();
return $comment; return $comment;
} }
public function getCommentsForPage($pageId, $commentId, $count = 20) { public function getCommentsForPage($pageId, $commentId, $count = 20) {
// requesting parent comments // requesting parent comments
$query = $this->comment->getCommentsByPage($pageId, $commentId); $query = $this->comment->getCommentsByPage($pageId, $commentId);
return $query->paginate($count); return $query->paginate($count);
} }
public function getCommentCount($pageId) { public function getCommentCount($pageId) {
return $this->comment->where('page_id', '=', $pageId)->count(); return $this->comment->where('page_id', '=', $pageId)->count();
} }

View File

@ -683,29 +683,49 @@ module.exports = function (ngApp, events) {
}]); }]);
// CommentCrudController // CommentCrudController
ngApp.controller('CommentAddController', ['$scope', '$http', function ($scope, $http) { ngApp.controller('CommentReplyController', ['$scope', '$http', function ($scope, $http) {
const MarkdownIt = require("markdown-it"); const MarkdownIt = require("markdown-it");
const md = new MarkdownIt({html: true}); const md = new MarkdownIt({html: true});
let vm = this; let vm = this;
$scope.errors = {}; $scope.errors = {};
vm.saveComment = function () { vm.saveComment = function () {
let pageId = $scope.comment.pageId; let pageId = $scope.comment.pageId || $scope.pageId;
let comment = $scope.comment.newComment; let comment = $scope.comment.text;
let commentHTML = md.render($scope.comment.newComment); let commentHTML = md.render($scope.comment.text);
let serviceUrl = `/ajax/page/${pageId}/comment/`;
$http.post(window.baseUrl(`/ajax/page/${pageId}/comment/`), { let httpMethod = 'post';
let errorOp = 'add';
let reqObj = {
text: comment, text: comment,
html: commentHTML html: commentHTML
}).then(resp => { };
$scope.comment.newComment = '';
if ($scope.isEdit === true) {
// this will be set when editing the comment.
serviceUrl = `/ajax/page/${pageId}/comment/${$scope.comment.id}`;
httpMethod = 'put';
errorOp = 'update';
} else if ($scope.isReply === true) {
// if its reply, get the parent comment id
reqObj.parent_id = $scope.parentId;
}
$http[httpMethod](window.baseUrl(serviceUrl), reqObj).then(resp => {
if (!resp.data || resp.data.status !== 'success') { if (!resp.data || resp.data.status !== 'success') {
return events.emit('error', trans('error')); return events.emit('error', trans('error'));
} }
if ($scope.isEdit) {
$scope.comment.html = commentHTML;
$scope.$emit('evt.comment-success', $scope.comment.id);
} else {
$scope.comment.text = '';
$scope.$emit('evt.comment-success', null, true);
}
events.emit('success', trans(resp.data.message)); events.emit('success', trans(resp.data.message));
}, checkError('add'));
}, checkError(errorOp));
};
};
function checkError(errorGroupName) { function checkError(errorGroupName) {
$scope.errors[errorGroupName] = {}; $scope.errors[errorGroupName] = {};
return function(response) { return function(response) {
@ -725,19 +745,19 @@ module.exports = function (ngApp, events) {
ngApp.controller('CommentListController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) { ngApp.controller('CommentListController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
let vm = this; let vm = this;
$scope.errors = {}; $scope.errors = {};
$scope.defaultAvatar = defaultAvatar; $scope.defaultAvatar = defaultAvatar;
vm.totalCommentsStr = 'Loading...'; vm.totalCommentsStr = 'Loading...';
$scope.editorChange = function (content) { $scope.editorChange = function (content) {
console.log(content); console.log(content);
} }
$timeout(function() { $timeout(function() {
$http.get(window.baseUrl(`/ajax/page/${$scope.pageId}/comments/`)).then(resp => { $http.get(window.baseUrl(`/ajax/page/${$scope.pageId}/comments/`)).then(resp => {
if (!resp.data || resp.data.success !== true) { if (!resp.data || resp.data.success !== true) {
// TODO : Handle error // TODO : Handle error
return; return;
} }
vm.comments = resp.data.comments.data; vm.comments = resp.data.comments.data;
vm.totalComments = resp.data.total; vm.totalComments = resp.data.total;
// TODO : Fetch message from translate. // TODO : Fetch message from translate.
if (vm.totalComments === 0) { if (vm.totalComments === 0) {
@ -748,20 +768,19 @@ module.exports = function (ngApp, events) {
vm.totalCommentsStr = vm.totalComments + ' Comments' vm.totalCommentsStr = vm.totalComments + ' Comments'
} }
}, checkError('app')); }, checkError('app'));
}); });
vm.loadSubComments = function(event, comment) { vm.loadSubComments = function(event, comment) {
event.preventDefault(); event.preventDefault();
$http.get(window.baseUrl(`/ajax/page/${$scope.pageId}/comments/${comment.id}/sub-comments`)).then(resp => { $http.get(window.baseUrl(`/ajax/page/${$scope.pageId}/comments/${comment.id}/sub-comments`)).then(resp => {
console.log(resp);
if (!resp.data || resp.data.success !== true) { if (!resp.data || resp.data.success !== true) {
return; return;
} }
comment.is_loaded = true; comment.is_loaded = true;
comment.comments = resp.data.comments.data; comment.comments = resp.data.comments.data;
}, checkError('app')); }, checkError('app'));
}; };
function checkError(errorGroupName) { function checkError(errorGroupName) {
$scope.errors[errorGroupName] = {}; $scope.errors[errorGroupName] = {};
return function(response) { return function(response) {

View File

@ -818,29 +818,62 @@ module.exports = function (ngApp, events) {
} }
}; };
}]); }]);
ngApp.directive('commentReply', ['$timeout', function ($timeout) { ngApp.directive('commentReply', [function () {
return { return {
restrict: 'E', restrict: 'E',
templateUrl: 'comment-reply.html', templateUrl: 'comment-reply.html',
scope: { scope: {
pageId: '=',
parentId: '='
}, },
link: function (scope, element, attr) { link: function (scope, element) {
scope.isReply = true;
scope.$on('evt.comment-success', function (event) {
// no need for the event to do anything more.
event.stopPropagation();
event.preventDefault();
element.remove();
scope.$destroy();
});
} }
} }
}]); }]);
ngApp.directive('commentReplyLink', ['$document', '$compile', function ($document, $compile) { ngApp.directive('commentEdit', [function () {
return { return {
restrict: 'E',
templateUrl: 'comment-reply.html',
scope: {
comment: '=',
},
link: function (scope, element) {
scope.isEdit = true;
scope.$on('evt.comment-success', function (event, commentId) {
// no need for the event to do anything more.
event.stopPropagation();
event.preventDefault();
if (commentId === scope.comment.id && !scope.isNew) {
element.remove();
scope.$destroy();
}
});
}
}
}]);
ngApp.directive('commentReplyLink', ['$document', '$compile', '$http', function ($document, $compile, $http) {
return {
scope: {
comment: '='
},
link: function (scope, element, attr) { link: function (scope, element, attr) {
element.on('$destroy', function () { element.on('$destroy', function () {
element.off('click'); element.off('click');
scope.$destroy(); scope.$destroy();
}); });
element.on('click', function () { element.on('click', function () {
var $container = element.parents('.comment-box').first(); var $container = element.parents('.comment-box').first();
if (!$container.length) { if (!$container.length) {
@ -848,21 +881,31 @@ module.exports = function (ngApp, events) {
return; return;
} }
if (attr.noCommentReplyDupe) { if (attr.noCommentReplyDupe) {
removeDupe(); removeDupe();
} }
var compiledHTML = $compile('<comment-reply></comment-reply>')(scope);
$container.append(compiledHTML); compileHtml($container, scope, attr.isReply === 'true');
}); });
} }
}; };
function compileHtml($container, scope, isReply) {
let lnkFunc = null;
if (isReply) {
lnkFunc = $compile('<comment-reply page-id="comment.pageId" parent-id="comment.id"></comment-reply>');
} else {
lnkFunc = $compile('<comment-edit comment="comment"></comment-add>');
}
var compiledHTML = lnkFunc(scope);
$container.append(compiledHTML);
}
function removeDupe() { function removeDupe() {
let $existingElement = $document.find('comment-reply'); let $existingElement = $document.find('.comments-list comment-reply');
if (!$existingElement.length) { if (!$existingElement.length) {
return; return;
} }
$existingElement.remove(); $existingElement.remove();
} }
}]); }]);

View File

@ -1,13 +0,0 @@
<div class="comment-editor" ng-controller="CommentAddController as vm" ng-cloak>
<form novalidate>
<textarea name="markdown" rows="3" ng-model="comment.newComment" placeholder="{{ trans('entities.comment_placeholder') }}"
@if($errors->has('markdown')) class="neg" @endif>@if(isset($model) ||
old('markdown')){{htmlspecialchars( old('markdown') ? old('markdown') : ($model->markdown === '' ? $model->html : $model->markdown))}}@endif</textarea>
<input type="hidden" ng-model="pageId" name="comment.pageId" value="{{$pageId}}" ng-init="comment.pageId = {{$pageId }}">
<button type="submit" class="button pos" ng-click="vm.saveComment()">Save</button>
</form>
</div>
@if($errors->has('markdown'))
<div class="text-neg text-small">{{ $errors->first('markdown') }}</div>
@endif

View File

@ -1,10 +1,13 @@
<!-- TODO :: needs to be merged with add.blade.php --> <div class="comment-editor" ng-controller="CommentReplyController as vm" ng-cloak>
<form novalidate> <form novalidate>
<div simple-markdown-input smd-model="comment.newComment" smd-get-content="getCommentHTML" smd-clear="clearInput"> <textarea name="markdown" rows="3" ng-model="comment.text" placeholder="{{ trans('entities.comment_placeholder') }}"
<textarea name="markdown" rows="3" @if($errors->has('markdown')) class="neg" @endif>@if(isset($model) ||
@if($errors->has('markdown')) class="neg" @endif>@if(isset($model) || old('markdown')){{htmlspecialchars( old('markdown') ? old('markdown') : ($model->markdown === '' ? $model->html : $model->markdown))}}@endif</textarea>
old('markdown')){{htmlspecialchars( old('markdown') ? old('markdown') : ($model->markdown === '' ? $model->html : $model->markdown))}}@endif</textarea> <input type="hidden" ng-model="comment.pageId" name="comment.pageId" value="{{$pageId}}" ng-init="comment.pageId = {{$pageId }}">
</div> <button type="submit" class="button pos" ng-click="vm.saveComment(isReply)">Save</button>
<input type="hidden" ng-model="pageId" name="comment.pageId" value="{{$pageId}}" ng-init="comment.pageId = {{$pageId }}"> </form>
<button type="submit" class="button pos" ng-click="vm.saveComment()">Save</button> </div>
</form>
@if($errors->has('markdown'))
<div class="text-neg text-small">{{ $errors->first('markdown') }}</div>
@endif

View File

@ -2,7 +2,7 @@
@include('comments/list-item') @include('comments/list-item')
</script> </script>
<script type="text/ng-template" id="comment-reply.html"> <script type="text/ng-template" id="comment-reply.html">
@include('comments/comment-reply') @include('comments/comment-reply', ['pageId' => $pageId])
</script> </script>
<div ng-controller="CommentListController as vm" ng-init="pageId = <?= $page->id ?>" class="comments-list" ng-cloak> <div ng-controller="CommentListController as vm" ng-init="pageId = <?= $page->id ?>" class="comments-list" ng-cloak>
<h3>@{{vm.totalCommentsStr}}</h3> <h3>@{{vm.totalCommentsStr}}</h3>
@ -13,4 +13,4 @@
</div> </div>
</div> </div>
</div> </div>
@include('comments/add', ['pageId' => $pageId]) @include('comments/comment-reply', ['pageId' => $pageId])

View File

@ -6,12 +6,13 @@
<div class="comment-header"> <div class="comment-header">
@{{ ::comment.created_by_name }} @{{ ::comment.created_by_name }}
</div> </div>
<div ng-bind-html="::comment.html" class="comment-body"> <div ng-bind-html="comment.html" class="comment-body">
</div> </div>
<div class="comment-actions"> <div class="comment-actions">
<ul> <ul>
<li><a href="#" comment-reply-link no-comment-reply-dupe="true">Reply</a></li> <li><a href="#" comment-reply-link no-comment-reply-dupe="true" comment="comment" is-reply="true">Reply</a></li>
<li><a href="#" comment-reply-link no-comment-reply-dupe="true" comment="comment">Edit</a></li>
<li><a href="#">@{{::comment.created_at}}</a></li> <li><a href="#">@{{::comment.created_at}}</a></li>
</ul> </ul>
</div> </div>

View File

@ -123,8 +123,8 @@ Route::group(['middleware' => 'auth'], function () {
Route::post('/ajax/page/{pageId}/comment/', 'CommentController@save'); Route::post('/ajax/page/{pageId}/comment/', 'CommentController@save');
Route::put('/ajax/page/{pageId}/comment/{commentId}', 'CommentController@save'); Route::put('/ajax/page/{pageId}/comment/{commentId}', 'CommentController@save');
Route::delete('/ajax/comment/{id}', 'CommentController@destroy'); Route::delete('/ajax/comment/{id}', 'CommentController@destroy');
Route::get('/ajax/page/{pageId}/comments/{commentId}/sub-comments', 'CommentController@getComments'); Route::get('/ajax/page/{pageId}/comments/{commentId}/sub-comments', 'CommentController@getCommentThread');
Route::get('/ajax/page/{pageId}/comments/', 'CommentController@getComments'); Route::get('/ajax/page/{pageId}/comments/', 'CommentController@getCommentThread');
// Links // Links
Route::get('/link/{id}', 'PageController@redirectFromLink'); Route::get('/link/{id}', 'PageController@redirectFromLink');