]> BookStack Code Mirror - bookstack/commitdiff
Comments: updated component and split out code
authorDan Brown <redacted>
Wed, 7 Jun 2023 16:47:37 +0000 (17:47 +0100)
committerDan Brown <redacted>
Wed, 7 Jun 2023 16:47:37 +0000 (17:47 +0100)
Split out comment component code so single-comment actions (delete, edit) are handled within their own compontent.
Modernised existing component code.

lang/en/entities.php
resources/js/components/index.js
resources/js/components/page-comment.js [new file with mode: 0644]
resources/js/components/page-comments.js
resources/views/comments/comment-branch.blade.php
resources/views/comments/comment.blade.php
resources/views/comments/comments.blade.php
resources/views/comments/create.blade.php

index 501fc9f2a0e9231c5b7cd95cc9de59740819742d..8499bb30f25cf8344bf35b345e1451560223beb4 100644 (file)
@@ -362,8 +362,6 @@ return [
     'comment_placeholder' => 'Leave a comment here',
     'comment_count' => '{0} No Comments|{1} 1 Comment|[2,*] :count Comments',
     'comment_save' => 'Save Comment',
-    'comment_saving' => 'Saving comment...',
-    'comment_deleting' => 'Deleting comment...',
     'comment_new' => 'New Comment',
     'comment_created' => 'commented :createDiff',
     'comment_updated' => 'Updated :updateDiff by :username',
index 803714e62a35658d3b134831eb896740d2687bfb..a56f18a5aff728f7f7aba88aeb9b6f42c645ad9a 100644 (file)
@@ -34,6 +34,7 @@ export {MarkdownEditor} from './markdown-editor';
 export {NewUserPassword} from './new-user-password';
 export {Notification} from './notification';
 export {OptionalInput} from './optional-input';
+export {PageComment} from './page-comment';
 export {PageComments} from './page-comments';
 export {PageDisplay} from './page-display';
 export {PageEditor} from './page-editor';
diff --git a/resources/js/components/page-comment.js b/resources/js/components/page-comment.js
new file mode 100644 (file)
index 0000000..ff86297
--- /dev/null
@@ -0,0 +1,85 @@
+import {Component} from './component';
+import {getLoading, htmlToDom} from '../services/dom';
+
+export class PageComment extends Component {
+
+    setup() {
+        // Options
+        this.commentId = this.$opts.commentId;
+        this.commentLocalId = this.$opts.commentLocalId;
+        this.commentParentId = this.$opts.commentParentId;
+        this.deletedText = this.$opts.deletedText;
+        this.updatedText = this.$opts.updatedText;
+
+        // Element References
+        this.container = this.$el;
+        this.contentContainer = this.$refs.contentContainer;
+        this.form = this.$refs.form;
+        this.formCancel = this.$refs.formCancel;
+        this.editButton = this.$refs.editButton;
+        this.deleteButton = this.$refs.deleteButton;
+        this.replyButton = this.$refs.replyButton;
+        this.input = this.$refs.input;
+
+        this.setupListeners();
+    }
+
+    setupListeners() {
+        this.replyButton.addEventListener('click', () => this.$emit('reply', {id: this.commentLocalId}));
+        this.editButton.addEventListener('click', this.startEdit.bind(this));
+        this.deleteButton.addEventListener('click', this.delete.bind(this));
+        this.form.addEventListener('submit', this.update.bind(this));
+        this.formCancel.addEventListener('click', () => this.toggleEditMode(false));
+    }
+
+    toggleEditMode(show) {
+        this.contentContainer.toggleAttribute('hidden', show);
+        this.form.toggleAttribute('hidden', !show);
+    }
+
+    startEdit() {
+        this.toggleEditMode(true);
+        const lineCount = this.$refs.input.value.split('\n').length;
+        this.$refs.input.style.height = `${(lineCount * 20) + 40}px`;
+    }
+
+    async update(event) {
+        event.preventDefault();
+        const loading = this.showLoading();
+        this.form.toggleAttribute('hidden', true);
+
+        const reqData = {
+            text: this.input.value,
+            parent_id: this.parentId || null,
+        };
+
+        try {
+            const resp = await window.$http.put(`/comment/${this.commentId}`, reqData);
+            const newComment = htmlToDom(resp.data);
+            this.container.replaceWith(newComment);
+            window.$events.success(this.updatedText);
+        } catch (err) {
+            console.error(err);
+            window.$events.showValidationErrors(err);
+            this.form.toggleAttribute('hidden', false);
+            loading.remove();
+        }
+    }
+
+    async delete() {
+        this.showLoading();
+
+        await window.$http.delete(`/comment/${this.commentId}`);
+        this.container.closest('.comment-branch').remove();
+        window.$events.success(this.deletedText);
+        this.$emit('delete');
+    }
+
+    showLoading() {
+        const loading = getLoading();
+        loading.classList.add('px-l');
+        this.container.append(loading);
+        return loading;
+    }
+
+}
index 0ac9d05720de80cdf9ec1b71e31d4ed02c77d1e0..9dc5299630baac25eebddd6d35df19ce1d8df419 100644 (file)
@@ -1,6 +1,5 @@
-import {scrollAndHighlightElement} from '../services/util';
 import {Component} from './component';
-import {htmlToDom} from '../services/dom';
+import {getLoading, htmlToDom} from '../services/dom';
 
 export class PageComments extends Component {
 
@@ -10,166 +9,110 @@ export class PageComments extends Component {
 
         // Element references
         this.container = this.$refs.commentContainer;
-        this.formContainer = this.$refs.formContainer;
         this.commentCountBar = this.$refs.commentCountBar;
+        this.commentsTitle = this.$refs.commentsTitle;
         this.addButtonContainer = this.$refs.addButtonContainer;
         this.replyToRow = this.$refs.replyToRow;
+        this.formContainer = this.$refs.formContainer;
+        this.form = this.$refs.form;
+        this.formInput = this.$refs.formInput;
+        this.addCommentButton = this.$refs.addCommentButton;
+        this.hideFormButton = this.$refs.hideFormButton;
+        this.removeReplyToButton = this.$refs.removeReplyToButton;
 
         // Translations
-        this.updatedText = this.$opts.updatedText;
-        this.deletedText = this.$opts.deletedText;
         this.createdText = this.$opts.createdText;
         this.countText = this.$opts.countText;
 
         // Internal State
-        this.editingComment = null;
         this.parentId = null;
 
-        if (this.formContainer) {
-            this.form = this.formContainer.querySelector('form');
-            this.formInput = this.form.querySelector('textarea');
-            this.form.addEventListener('submit', this.saveComment.bind(this));
-        }
-
-        this.elem.addEventListener('click', this.handleAction.bind(this));
-        this.elem.addEventListener('submit', this.updateComment.bind(this));
-    }
-
-    handleAction(event) {
-        const actionElem = event.target.closest('[action]');
-
-        if (event.target.matches('a[href^="#"]')) {
-            const id = event.target.href.split('#')[1];
-            scrollAndHighlightElement(document.querySelector(`#${id}`));
-        }
-
-        if (actionElem === null) return;
-        event.preventDefault();
-
-        const action = actionElem.getAttribute('action');
-        const comment = actionElem.closest('[comment]');
-        if (action === 'edit') this.editComment(comment);
-        if (action === 'closeUpdateForm') this.closeUpdateForm();
-        if (action === 'delete') this.deleteComment(comment);
-        if (action === 'addComment') this.showForm();
-        if (action === 'hideForm') this.hideForm();
-        if (action === 'reply') this.setReply(comment);
-        if (action === 'remove-reply-to') this.removeReplyTo();
+        this.setupListeners();
     }
 
-    closeUpdateForm() {
-        if (!this.editingComment) return;
-        this.editingComment.querySelector('[comment-content]').style.display = 'block';
-        this.editingComment.querySelector('[comment-edit-container]').style.display = 'none';
-    }
-
-    editComment(commentElem) {
-        this.hideForm();
-        if (this.editingComment) this.closeUpdateForm();
-        commentElem.querySelector('[comment-content]').style.display = 'none';
-        commentElem.querySelector('[comment-edit-container]').style.display = 'block';
-        const textArea = commentElem.querySelector('[comment-edit-container] textarea');
-        const lineCount = textArea.value.split('\n').length;
-        textArea.style.height = `${(lineCount * 20) + 40}px`;
-        this.editingComment = commentElem;
-    }
+    setupListeners() {
+        this.removeReplyToButton.addEventListener('click', this.removeReplyTo.bind(this));
+        this.hideFormButton.addEventListener('click', this.hideForm.bind(this));
+        this.addCommentButton.addEventListener('click', this.showForm.bind(this));
 
-    updateComment(event) {
-        const form = event.target;
-        event.preventDefault();
-        const text = form.querySelector('textarea').value;
-        const reqData = {
-            text,
-            parent_id: this.parentId || null,
-        };
-        this.showLoading(form);
-        const commentId = this.editingComment.getAttribute('comment');
-        window.$http.put(`/comment/${commentId}`, reqData).then(resp => {
-            const newComment = document.createElement('div');
-            newComment.innerHTML = resp.data;
-            this.editingComment.innerHTML = newComment.children[0].innerHTML;
-            window.$events.success(this.updatedText);
-            window.$components.init(this.editingComment);
-            this.closeUpdateForm();
-            this.editingComment = null;
-        }).catch(window.$events.showValidationErrors).then(() => {
-            this.hideLoading(form);
-        });
-    }
-
-    deleteComment(commentElem) {
-        const id = commentElem.getAttribute('comment');
-        this.showLoading(commentElem.querySelector('[comment-content]'));
-        window.$http.delete(`/comment/${id}`).then(() => {
-            commentElem.parentNode.removeChild(commentElem);
-            window.$events.success(this.deletedText);
+        this.elem.addEventListener('page-comment-delete', () => {
             this.updateCount();
             this.hideForm();
         });
+
+        this.elem.addEventListener('page-comment-reply', event => {
+            this.setReply(event.detail.id);
+        });
+
+        if (this.form) {
+            this.form.addEventListener('submit', this.saveComment.bind(this));
+        }
     }
 
     saveComment(event) {
         event.preventDefault();
         event.stopPropagation();
+
+        const loading = getLoading();
+        loading.classList.add('px-l');
+        this.form.after(loading);
+        this.form.toggleAttribute('hidden', true);
+
         const text = this.formInput.value;
         const reqData = {
             text,
             parent_id: this.parentId || null,
         };
-        this.showLoading(this.form);
+
         window.$http.post(`/comment/${this.pageId}`, reqData).then(resp => {
             const newElem = htmlToDom(resp.data);
             this.container.appendChild(newElem);
-            window.$components.init(newElem);
             window.$events.success(this.createdText);
             this.resetForm();
             this.updateCount();
         }).catch(err => {
+            this.form.toggleAttribute('hidden', false);
             window.$events.showValidationErrors(err);
-            this.hideLoading(this.form);
         });
+
+        loading.remove();
     }
 
     updateCount() {
-        const count = this.container.children.length;
-        this.elem.querySelector('[comments-title]').textContent = window.trans_plural(this.countText, count, {count});
+        const count = this.getCommentCount();
+        this.commentsTitle.textContent = window.trans_plural(this.countText, count, {count});
     }
 
     resetForm() {
         this.formInput.value = '';
-        this.formContainer.appendChild(this.form);
         this.hideForm();
         this.removeReplyTo();
-        this.hideLoading(this.form);
     }
 
     showForm() {
-        this.formContainer.style.display = 'block';
-        this.formContainer.parentNode.style.display = 'block';
-        this.addButtonContainer.style.display = 'none';
+        this.formContainer.toggleAttribute('hidden', false);
+        this.addButtonContainer.toggleAttribute('hidden', true);
         this.formInput.focus();
-        this.formInput.scrollIntoView({behavior: 'smooth'});
     }
 
     hideForm() {
-        this.formContainer.style.display = 'none';
-        this.formContainer.parentNode.style.display = 'none';
+        this.formContainer.toggleAttribute('hidden', true);
         if (this.getCommentCount() > 0) {
             this.elem.appendChild(this.addButtonContainer);
         } else {
             this.commentCountBar.appendChild(this.addButtonContainer);
         }
-        this.addButtonContainer.style.display = 'block';
+        this.addButtonContainer.toggleAttribute('hidden', false);
     }
 
     getCommentCount() {
-        return this.elem.querySelectorAll('.comment-box[comment]').length;
+        return this.container.querySelectorAll('[compontent="page-comment"]').length;
     }
 
-    setReply(commentElem) {
+    setReply(commentLocalId) {
         this.showForm();
-        this.parentId = Number(commentElem.getAttribute('local-id'));
-        this.replyToRow.style.display = 'block';
+        this.parentId = commentLocalId;
+        this.replyToRow.toggleAttribute('hidden', false);
         const replyLink = this.replyToRow.querySelector('a');
         replyLink.textContent = `#${this.parentId}`;
         replyLink.href = `#comment${this.parentId}`;
@@ -177,23 +120,7 @@ export class PageComments extends Component {
 
     removeReplyTo() {
         this.parentId = null;
-        this.replyToRow.style.display = 'none';
-    }
-
-    showLoading(formElem) {
-        const groups = formElem.querySelectorAll('.form-group');
-        for (const group of groups) {
-            group.style.display = 'none';
-        }
-        formElem.querySelector('.form-group.loading').style.display = 'block';
-    }
-
-    hideLoading(formElem) {
-        const groups = formElem.querySelectorAll('.form-group');
-        for (const group of groups) {
-            group.style.display = 'block';
-        }
-        formElem.querySelector('.form-group.loading').style.display = 'none';
+        this.replyToRow.toggleAttribute('hidden', true);
     }
 
 }
index d64dd4ade1d51c5055ef52d623d039fac26da1f0..69c967cd2e77c0e6120dd5a18c6c7f9079475b8b 100644 (file)
@@ -1,4 +1,4 @@
-<div>
+<div class="comment-branch">
     <div class="mb-m">
         @include('comments.comment', ['comment' => $branch['comment']])
     </div>
index 093e5a899050965eba3c9effaee12c1063cf1290..ce0d5947388b9a1b726a4b7e4d11206a0cc49877 100644 (file)
@@ -1,4 +1,11 @@
-<div class="comment-box" comment="{{ $comment->id }}" local-id="{{$comment->local_id}}" parent-id="{{$comment->parent_id}}" id="comment{{$comment->local_id}}">
+<div component="page-comment"
+     option:page-comment:comment-id="{{ $comment->id }}"
+     option:page-comment:comment-local-id="{{ $comment->local_id }}"
+     option:page-comment:comment-parent-id="{{ $comment->parent_id }}"
+     option:page-comment:updated-text="{{ trans('entities.comment_updated_success') }}"
+     option:page-comment:deleted-text="{{ trans('entities.comment_deleted_success') }}"
+     id="comment{{$comment->local_id}}"
+     class="comment-box">
     <div class="header p-s">
         <div class="grid half left-focus no-gap v-center">
             <div class="meta text-muted text-small">
             </div>
             <div class="actions text-right">
                 @if(userCan('comment-update', $comment))
-                    <button type="button" class="text-button" action="edit" aria-label="{{ trans('common.edit') }}" title="{{ trans('common.edit') }}">@icon('edit')</button>
+                    <button refs="page-comment@edit-button" type="button" class="text-button"  aria-label="{{ trans('common.edit') }}" title="{{ trans('common.edit') }}">@icon('edit')</button>
                 @endif
                 @if(userCan('comment-create-all'))
-                    <button type="button" class="text-button" action="reply" aria-label="{{ trans('common.reply') }}" title="{{ trans('common.reply') }}">@icon('reply')</button>
+                    <button refs="page-comment@reply-button" type="button" class="text-button" aria-label="{{ trans('common.reply') }}" title="{{ trans('common.reply') }}">@icon('reply')</button>
                 @endif
                 @if(userCan('comment-delete', $comment))
                     <div component="dropdown" class="dropdown-container">
@@ -32,7 +39,7 @@
                         <ul refs="dropdown@menu" class="dropdown-menu" role="menu">
                             <li class="px-m text-small text-muted pb-s">{{trans('entities.comment_delete_confirm')}}</li>
                             <li>
-                                <button action="delete" type="button" class="text-button text-neg icon-item">
+                                <button refs="page-comment@delete-button" type="button" class="text-button text-neg icon-item">
                                     @icon('delete')
                                     <div>{{ trans('common.delete') }}</div>
                                 </button>
         </div>
     @endif
 
-    <div comment-content class="content px-s pb-s">
-        <div class="form-group loading" style="display: none;">
-            @include('common.loading-icon', ['text' => trans('entities.comment_deleting')])
-        </div>
+    <div refs="page-comment@content-container" class="content px-s pb-s">
         {!! $comment->html  !!}
     </div>
 
     @if(userCan('comment-update', $comment))
-        <div comment-edit-container style="display: none;" class="content px-s">
-            <form novalidate>
-                <div class="form-group description-input">
-                    <textarea name="markdown" rows="3" placeholder="{{ trans('entities.comment_placeholder') }}">{{ $comment->text }}</textarea>
-                </div>
-                <div class="form-group text-right">
-                    <button type="button" class="button outline" action="closeUpdateForm">{{ trans('common.cancel') }}</button>
-                    <button type="submit" class="button">{{ trans('entities.comment_save') }}</button>
-                </div>
-                <div class="form-group loading" style="display: none;">
-                    @include('common.loading-icon', ['text' => trans('entities.comment_saving')])
-                </div>
-            </form>
-        </div>
+        <form novalidate refs="page-comment@form" hidden class="content px-s block">
+            <div class="form-group description-input">
+                <textarea refs="page-comment@input" name="markdown" rows="3" placeholder="{{ trans('entities.comment_placeholder') }}">{{ $comment->text }}</textarea>
+            </div>
+            <div class="form-group text-right">
+                <button type="button" class="button outline" refs="page-comment@form-cancel">{{ trans('common.cancel') }}</button>
+                <button type="submit" class="button">{{ trans('entities.comment_save') }}</button>
+            </div>
+        </form>
     @endif
 
 </div>
\ No newline at end of file
index f50e3a218760365e4a7d480a514cc4f6410eff8c..b79f0fd45fda1d6bb767210fe1e490b9eb0a8abc 100644 (file)
@@ -1,17 +1,16 @@
 <section component="page-comments"
          option:page-comments:page-id="{{ $page->id }}"
-         option:page-comments:updated-text="{{ trans('entities.comment_updated_success') }}"
-         option:page-comments:deleted-text="{{ trans('entities.comment_deleted_success') }}"
          option:page-comments:created-text="{{ trans('entities.comment_created_success') }}"
          option:page-comments:count-text="{{ trans('entities.comment_count') }}"
          class="comments-list"
          aria-label="{{ trans('entities.comments') }}">
 
-    <div refs="page-comments@commentCountBar" class="grid half left-focus v-center no-row-gap">
-        <h5 comments-title>{{ trans_choice('entities.comment_count', $commentTree->count(), ['count' => $commentTree->count()]) }}</h5>
+    <div refs="page-comments@comment-count-bar" class="grid half left-focus v-center no-row-gap">
+        <h5 refs="page-comments@comments-title">{{ trans_choice('entities.comment_count', $commentTree->count(), ['count' => $commentTree->count()]) }}</h5>
         @if ($commentTree->empty() && userCan('comment-create-all'))
-            <div class="text-m-right" refs="page-comments@addButtonContainer">
-                <button type="button" action="addComment"
+            <div class="text-m-right" refs="page-comments@add-button-container">
+                <button type="button"
+                        refs="page-comments@add-comment-button"
                         class="button outline">{{ trans('entities.comment_add') }}</button>
             </div>
         @endif
@@ -28,7 +27,8 @@
 
         @if (!$commentTree->empty())
             <div refs="page-comments@addButtonContainer" class="text-right">
-                <button type="button" action="addComment"
+                <button type="button"
+                        refs="page-comments@add-comment-button"
                         class="button outline">{{ trans('entities.comment_add') }}</button>
             </div>
         @endif
index a5a84b004dc8e20a2fbf514487f5bfa13b548e3d..5f9f6d4499481f6b2dde9dde8ce2d2f8eea03cb6 100644 (file)
@@ -1,31 +1,29 @@
-<div class="comment-box" style="display:none;">
+<div refs="page-comments@form-container" hidden class="comment-box">
 
     <div class="header p-s">{{ trans('entities.comment_new') }}</div>
-    <div refs="page-comments@replyToRow" class="reply-row primary-background-light text-muted px-s py-xs mb-s" style="display: none;">
+    <div refs="page-comments@reply-to-row" hidden class="primary-background-light text-muted px-s py-xs mb-s">
         <div class="grid left-focus v-center">
             <div>
                 {!! trans('entities.comment_in_reply_to', ['commentId' => '<a href=""></a>']) !!}
             </div>
             <div class="text-right">
-                <button class="text-button" action="remove-reply-to">{{ trans('common.remove') }}</button>
+                <button refs="page-comments@remove-reply-to-button" class="text-button">{{ trans('common.remove') }}</button>
             </div>
         </div>
     </div>
 
-    <div refs="page-comments@formContainer" class="content px-s">
-        <form novalidate>
+    <div class="content px-s">
+        <form refs="page-comments@form" novalidate>
             <div class="form-group description-input">
-                        <textarea name="markdown" rows="3"
-                                  placeholder="{{ trans('entities.comment_placeholder') }}"></textarea>
+                <textarea refs="page-comments@form-input" name="markdown"
+                          rows="3"
+                          placeholder="{{ trans('entities.comment_placeholder') }}"></textarea>
             </div>
             <div class="form-group text-right">
                 <button type="button" class="button outline"
-                        action="hideForm">{{ trans('common.cancel') }}</button>
+                        refs="page-comments@hide-form-button">{{ trans('common.cancel') }}</button>
                 <button type="submit" class="button">{{ trans('entities.comment_save') }}</button>
             </div>
-            <div class="form-group loading" style="display: none;">
-                @include('common.loading-icon', ['text' => trans('entities.comment_saving')])
-            </div>
         </form>
     </div>
 
Morty Proxy This is a proxified and sanitized view of the page, visit original site.