Skip to content

Commit

Permalink
refactor: comment list
Browse files Browse the repository at this point in the history
  • Loading branch information
yilanboy committed Nov 13, 2024
1 parent dfa0e25 commit 455cd3c
Show file tree
Hide file tree
Showing 15 changed files with 137 additions and 132 deletions.
39 changes: 21 additions & 18 deletions app/Livewire/Shared/Comments/CommentCard.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,58 +19,61 @@ class CommentCard extends Component
use MarkdownConverter;

#[Locked]
public int $maxLayer;
public int $postId;

#[Locked]
public int $currentLayer;
public int $postUserId;

#[Locked]
public int $postId;
public int $maxLayer;

#[Locked]
public int $postAuthorId;
public int $currentLayer;

#[Locked]
public int $commentId;
public int $childrenPerPage = 3;

#[Locked]
public ?int $userId;
public int $commentId;

#[Locked]
public string $userGravatarUrl;
public ?int $commentUserId;

#[Locked]
public string $userName;
public ?string $commentUserGravatarUrl;

#[Locked]
public bool $hasChildren;
public string $commentUserName;

#[Locked]
public int $childrenPerPage = 3;
public string $commentBody;

public string $body;
#[Locked]
public string $commentCreatedAt;

public string $createdAt;
#[Locked]
public bool $commentIsEdited;

public bool $isEdited;
#[Locked]
public bool $commentHasChildren;

/**
* @throws CommonMarkException
*/
#[Computed]
public function convertedBody(): string
{
return $this->convertToHtml($this->body);
return $this->convertToHtml($this->commentBody);
}

#[On('comment-updated.{commentId}')]
#[On('update-comment-{commentId}')]
public function refreshComment(): void
{
$comment = Comment::findOrFail($this->commentId);

$this->body = $comment->body;
$this->createdAt = $comment->created_at;
$this->isEdited = true;
$this->commentBody = $comment->body;
$this->commentCreatedAt = $comment->created_at;
$this->commentIsEdited = true;
}

public function render(): View
Expand Down
15 changes: 10 additions & 5 deletions app/Livewire/Shared/Comments/CommentGroup.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
Expand All @@ -18,19 +19,19 @@ class CommentGroup extends Component
use AuthorizesRequests;

#[Locked]
public int $maxLayer = 2;
public int $postId;

#[Locked]
public int $currentLayer = 1;
public int $postUserId;

#[Locked]
public ?int $parentId = null;
public int $maxLayer = 2;

#[Locked]
public int $postId;
public int $currentLayer = 1;

#[Locked]
public int $postAuthorId;
public ?int $parentId = null;

/**
* Use this comment group name as a dynamic event name.
Expand All @@ -52,6 +53,7 @@ class CommentGroup extends Component
* 2 => ["id" => 2, "body" => "world" ...],
* ],
*/
#[Locked]
public array $comments = [];

#[On('insert-new-comment-to-{commentGroupName}')]
Expand All @@ -68,6 +70,9 @@ public function insertComment(array $comment): void
*/
public function destroy(int $commentId): void
{
$test = implode(',', array_keys($this->comments));
Log::info("Show comments: {$test}");

$comment = Comment::find(id: $commentId, columns: ['id', 'user_id', 'post_id']);

// Check comment is not deleted
Expand Down
50 changes: 21 additions & 29 deletions app/Livewire/Shared/Comments/CommentList.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,22 @@
class CommentList extends Component
{
#[Locked]
public int $maxLayer = 2;
public int $postId;

#[Locked]
public int $currentLayer = 1;
public int $postUserId;

#[Locked]
public int $perPage = 10;
public int $maxLayer = 2;

#[Locked]
public int $postId;
public int $currentLayer = 1;

#[Locked]
public int $postAuthorId;
public ?int $parentId = null;

#[Locked]
public ?int $parentId = null;
public int $perPage = 10;

/**
* This value will be either the root-comment-list or [comment id]-comment-list,
Expand All @@ -56,8 +56,6 @@ class CommentList extends Component
*/
public array $commentsList = [];

public int $skipCounts = 0;

public bool $showMoreButtonIsActive = true;

/**
Expand All @@ -79,21 +77,7 @@ public function appendNewIdToNewCommentIds(int $id): void
$this->newCommentIds[] = $id;
}

public function showMoreComments(): void
{
$comments = $this->getComments();

$this->updateSkipCounts();
$this->updateCommentsList($comments);
$this->updateShowMoreButtonStatus($comments);
}

public function render(): View
{
return view('livewire.shared.comments.comment-list');
}

private function getComments(): array
private function getComments(int $skip): array
{
$comments = Comment::query()
->select(['id', 'user_id', 'body', 'created_at', 'updated_at'])
Expand All @@ -116,7 +100,7 @@ private function getComments(): array
// When parent id is not null,
// it means this comment list is children of another comment.
->where('parent_id', $this->parentId)
->skip($this->skipCounts)
->skip($skip)
// Plus one is needed here because we need to determine whether there is a next page.
->take($this->perPage + 1)
->with('user:id,name,email')
Expand All @@ -138,11 +122,6 @@ private function getComments(): array
return $comments;
}

private function updateSkipCounts(): void
{
$this->skipCounts += $this->perPage;
}

private function updateCommentsList(array $comments): void
{
if (count($comments) > 0) {
Expand All @@ -156,4 +135,17 @@ private function updateShowMoreButtonStatus(array $comments): void
$this->showMoreButtonIsActive = false;
}
}

public function showMoreComments(int $skip = 0): void
{
$comments = $this->getComments($skip);

$this->updateCommentsList($comments);
$this->updateShowMoreButtonStatus($comments);
}

public function render(): View
{
return view('livewire.shared.comments.comment-list');
}
}
4 changes: 3 additions & 1 deletion app/Livewire/Shared/Comments/Comments.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@ class Comments extends Component
public int $postId;

#[Locked]
public int $postAuthorId;
public int $postUserId;

#[Locked]
public int $maxLayer = 2;

#[Locked]
public int $commentCounts;

#[Locked]
public CommentOrder $order = CommentOrder::POPULAR;

// update comment count in post show page
Expand Down
2 changes: 1 addition & 1 deletion app/Livewire/Shared/Comments/CreateCommentModal.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ private function prepareCommentCardArray(Comment $comment, ?User $user): array
$comment['user'] = [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'gravatar_url' => get_gravatar($user->email),
];

return $comment;
Expand Down
4 changes: 1 addition & 3 deletions app/Livewire/Shared/Comments/EditCommentModal.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ class EditCommentModal extends Component

public bool $previewIsEnabled = false;

public int $commentId;

public string $body = '';

protected function rules(): array
Expand Down Expand Up @@ -65,7 +63,7 @@ public function update(Comment $comment): void

$this->dispatch('close-edit-comment-modal');

$this->dispatch('comment-updated.'.$comment->id);
$this->dispatch('update-comment-'.$comment->id);
}

public function render(): View
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ class="gradient-underline-grow inline-block text-2xl dark:text-gray-50"

<livewire:shared.comments.comments
:post-id="$post->id"
:post-author-id="$post->user_id"
:post-user-id="$post->user_id"
:comment-counts="$post->comment_counts"
/>
</div>
Expand Down
46 changes: 23 additions & 23 deletions resources/views/livewire/shared/comments/comment-card.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
Alpine.data('commentCard', () => ({
openEditCommentModal() {
this.$dispatch('open-edit-comment-modal', {
commentId: this.$root.dataset.commentId,
body: this.$root.dataset.body,
id: this.$root.dataset.commentId,
body: this.$root.dataset.commentBody,
})
},
openCreateCommentModal() {
this.$dispatch('open-create-comment-modal', {
parentId: this.$root.dataset.commentId,
replyTo: this.$root.dataset.userName
replyTo: this.$root.dataset.commentUserName
})
}
}));
Expand All @@ -19,36 +19,36 @@

<div
data-comment-id="{{ $commentId }}"
data-body="{{ $body }}"
data-user-name="{{ $userId !== 0 ? $userName : '訪客' }}"
data-comment-body="{{ $commentBody }}"
data-comment-user-name="{{ $commentUserName }}"
x-data="commentCard"
>
<x-dashed-card class="mt-6">
<div class="flex flex-col">
<div class="flex items-center space-x-4 text-base">
@if (!is_null($userId))
@if (!is_null($commentUserId))
<a
href="{{ route('users.show', ['id' => $userId]) }}"
href="{{ route('users.show', ['id' => $commentUserId]) }}"
wire:navigate
>
<img
class="size-10 rounded-full hover:ring-2 hover:ring-blue-400"
src="{{ $userGravatarUrl }}"
alt="{{ $userName }}"
src="{{ $commentUserGravatarUrl }}"
alt="{{ $commentUserName }}"
>
</a>
@else
<x-icon.question-circle-fill class="size-10 text-gray-300 dark:text-gray-500" />
@endif

<span class="dark:text-gray-50">{{ $userName }}</span>
<span class="dark:text-gray-50">{{ $commentUserName }}</span>

<time
class="hidden text-gray-400 md:block"
datetime="{{ date('d-m-Y', strtotime($createdAt)) }}"
>{{ date('Y 年 m 月 d 日', strtotime($createdAt)) }}</time>
datetime="{{ date('d-m-Y', strtotime($commentCreatedAt)) }}"
>{{ date('Y 年 m 月 d 日', strtotime($commentCreatedAt)) }}</time>

@if ($isEdited)
@if ($commentIsEdited)
<span class="text-gray-400">(已編輯)</span>
@endif
</div>
Expand All @@ -59,7 +59,7 @@ class="hidden text-gray-400 md:block"

<div class="flex items-center justify-end gap-6 text-base text-gray-400">
@auth
@if (auth()->id() === $userId)
@if (auth()->id() === $commentUserId)
<button
class="flex items-center hover:text-gray-500 dark:hover:text-gray-300"
type="button"
Expand All @@ -70,7 +70,7 @@ class="flex items-center hover:text-gray-500 dark:hover:text-gray-300"
</button>
@endif

@if (in_array(auth()->id(), [$userId, $postAuthorId]))
@if (in_array(auth()->id(), [$commentUserId, $postUserId]))
<button
class="flex items-center hover:text-gray-500 dark:hover:text-gray-300"
type="button"
Expand Down Expand Up @@ -104,24 +104,24 @@ class="relative pl-4 before:absolute before:left-0 before:top-0 before:h-full be
id="children-{{ $commentId }}"
>
<livewire:shared.comments.comment-group
:$maxLayer
:current-layer="$currentLayer + 1"
:post-id="$postId"
:post-author-id="$postAuthorId"
:post-user-id="$postUserId"
:max-layer="$maxLayer"
:current-layer="$currentLayer + 1"
:parent-id="$commentId"
:comment-group-name="$commentId . '-new-comment-group'"
/>

{{-- If this comment has no sub-messages,
do not render the next level of sub-comment list to avoid redundant SQL queries. --}}
@if ($hasChildren)
@if ($commentHasChildren)
<livewire:shared.comments.comment-list
:$maxLayer
:post-id="$postId"
:post-user-id="$postUserId"
:max-layer="$maxLayer"
:current-layer="$currentLayer + 1"
:per-page="$childrenPerPage"
:$postId
:$postAuthorId
:parent-id="$commentId"
:per-page="$childrenPerPage"
:comment-list-name="$commentId . '-comment-list'"
:order="App\Enums\CommentOrder::OLDEST"
/>
Expand Down
Loading

0 comments on commit 455cd3c

Please sign in to comment.