fix: pk comment

This commit is contained in:
zzc
2026-06-15 22:29:03 +08:00
parent 3c7e520062
commit 88f4220432
3 changed files with 561 additions and 891 deletions

View File

@@ -1,7 +1,7 @@
<template>
<view class="pk-comment-section">
<view class="comment-section" :class="[`comment-section--${variant}`]">
<view class="comment-header">
<view class="comment-tabs">
<view v-if="showTabs" class="comment-tabs">
<text
v-for="tab in tabs"
:key="tab.value"
@@ -12,23 +12,27 @@
{{ tab.label }}
</text>
</view>
<view class="my-choice-pill" :class="selectedTone ? `my-choice-pill--${selectedTone}` : ''">
<text class="my-choice-pill-label">我站</text>
<text class="my-choice-pill-value">{{ selectedItemLabel }}</text>
<view v-else class="comment-title-wrap">
<text class="comment-title">{{ sectionTitle }}</text>
</view>
<view v-if="pillValue" class="header-pill" :class="pillTone ? `header-pill--${pillTone}` : ''">
<text v-if="pillLabel" class="header-pill-label">{{ pillLabel }}</text>
<text class="header-pill-value">{{ pillValue }}</text>
</view>
</view>
<view class="compose-card">
<view v-if="allowCompose" class="compose-card">
<view class="compose-tip">
<text class="compose-title">说说你的理由</text>
<text class="compose-desc">支持 {{ selectedItemLabel }} 的观点会更容易引发讨论</text>
<text class="compose-title">{{ composeTitle }}</text>
<text v-if="composeDesc" class="compose-desc">{{ composeDesc }}</text>
</view>
<view class="compose-box">
<input
class="compose-input"
v-model="commentText"
:disabled="sending"
placeholder="写下你的 PK 观点..."
:placeholder="composePlaceholder"
placeholder-class="compose-placeholder"
confirm-type="send"
@confirm="submitMainComment"
@@ -39,32 +43,43 @@
:disabled="sending || !commentText.trim()"
@tap="submitMainComment"
>
{{ sending ? "发送中" : "发布" }}
{{ sending ? composeSendingText : composeButtonText }}
</button>
</view>
</view>
<view class="comment-list">
<view v-if="loading && !comments.length" class="comment-state">
<text class="comment-state-title">评论加载中...</text>
<text class="comment-state-desc">看看大家都站哪边</text>
<text class="comment-state-title">{{ loadingTitle }}</text>
<text class="comment-state-desc">{{ loadingDesc }}</text>
</view>
<view v-else-if="loadError && !comments.length" class="comment-state">
<text class="comment-state-title">评论加载失败</text>
<text class="comment-state-title">{{ errorTitle }}</text>
<text class="comment-state-desc">{{ loadError }}</text>
<button class="comment-state-btn" @tap="refreshComments">重新加载</button>
</view>
<view v-else-if="!comments.length" class="comment-state">
<text class="comment-state-title">还没有人发言</text>
<text class="comment-state-desc">你可以成为这场 PK 的第一位评论官</text>
<view v-else-if="!comments.length" class="comment-state comment-state--empty">
<view v-if="showEmptyVisual" class="comment-empty-visual">
<view class="comment-empty-orbit orbit-1"></view>
<view class="comment-empty-orbit orbit-2"></view>
<view class="comment-empty-core">
<text class="comment-empty-emoji">{{ emptyEmoji }}</text>
</view>
</view>
<text class="comment-state-title">{{ emptyTitle }}</text>
<text class="comment-state-desc">{{ emptyDesc }}</text>
<text v-if="emptyTip" class="comment-state-tip">{{ emptyTip }}</text>
</view>
<CommentItem
v-for="comment in comments"
:key="comment.id"
:comment="comment"
:like-handler="likeComment"
page-name="pk_station"
@need-login="emit('need-login')"
:like-handler="likeHandler"
:page-name="pageName"
@need-login="emitNeedLogin"
@like-change="handleCommentLikeChange"
@reply="openReplyPopup"
@toggle-replies="handleToggleReplies"
@@ -73,15 +88,16 @@
</view>
<view v-if="comments.length" class="comment-footer">
<text v-if="loading" class="comment-footer-text">加载中...</text>
<text v-if="loading" class="comment-footer-text">{{ footerLoadingText }}</text>
<text
v-else-if="hasMore"
v-else-if="hasMore && loadMoreMode === 'click'"
class="comment-footer-link"
@tap="loadComments()"
>
查看更多评论
{{ footerMoreText }}
</text>
<text v-else class="comment-footer-text">没有更多评论了</text>
<text v-else-if="loadMoreMode === 'scroll'" class="comment-footer-text">{{ footerHintText }}</text>
<text v-else class="comment-footer-text">{{ footerDoneText }}</text>
</view>
<view
@@ -119,7 +135,7 @@
:disabled="sendingReply || !replyContent.trim()"
@tap="submitReplyComment"
>
{{ sendingReply ? "发送中" : "发送" }}
{{ sendingReply ? replySendingText : replyButtonText }}
</button>
</view>
</view>
@@ -131,52 +147,185 @@ import { computed, nextTick, ref, watch } from "vue";
import { onUnmounted } from "vue";
import CommentItem from "@/components/CommentItem/CommentItem.vue";
import { useUserStore } from "@/stores/user";
import {
fetchCommentList,
fetchCommentReplyList,
publishComment,
likeComment,
} from "@/api/pk";
import { FILE_BASE_URL } from "@/utils/constants";
import { formatDate } from "@/utils/date";
const props = defineProps({
pkId: {
type: String,
default: "",
},
selectedItemId: {
type: String,
default: "",
},
selectedItemLabel: {
type: String,
default: "",
},
currentPair: {
type: Object,
default: null,
},
visible: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(["need-login"]);
const userStore = useUserStore();
const tabs = [
const defaultTabs = [
{ label: "最热", value: "hot" },
{ label: "最新", value: "new" },
];
const props = defineProps({
requestKey: {
type: String,
default: "",
},
visible: {
type: Boolean,
default: true,
},
variant: {
type: String,
default: "topic",
},
sectionTitle: {
type: String,
default: "评论区",
},
showTabs: {
type: Boolean,
default: true,
},
tabs: {
type: Array,
default: () => defaultTabs,
},
allowCompose: {
type: Boolean,
default: false,
},
composeTitle: {
type: String,
default: "说说你的看法",
},
composeDesc: {
type: String,
default: "",
},
composePlaceholder: {
type: String,
default: "写下你的观点...",
},
composeButtonText: {
type: String,
default: "发布",
},
composeSendingText: {
type: String,
default: "发送中",
},
replyButtonText: {
type: String,
default: "发送",
},
replySendingText: {
type: String,
default: "发送中",
},
pageName: {
type: String,
default: "rating_detail",
},
pillLabel: {
type: String,
default: "",
},
pillValue: {
type: String,
default: "",
},
pillTone: {
type: String,
default: "",
},
loadingTitle: {
type: String,
default: "评论加载中...",
},
loadingDesc: {
type: String,
default: "正在拉取大家的观点",
},
errorTitle: {
type: String,
default: "评论加载失败",
},
errorFallbackText: {
type: String,
default: "网络开了点小差,稍后重试",
},
emptyTitle: {
type: String,
default: "还没有评论",
},
emptyDesc: {
type: String,
default: "来发第一条评论,带动一下讨论气氛",
},
emptyTip: {
type: String,
default: "",
},
emptyEmoji: {
type: String,
default: "💬",
},
showEmptyVisual: {
type: Boolean,
default: false,
},
footerLoadingText: {
type: String,
default: "加载中...",
},
footerMoreText: {
type: String,
default: "查看更多评论",
},
footerDoneText: {
type: String,
default: "没有更多评论了",
},
footerHintText: {
type: String,
default: "上拉加载更多",
},
loadMoreMode: {
type: String,
default: "click",
},
showSuccessToast: {
type: Boolean,
default: true,
},
mainSuccessText: {
type: String,
default: "评论已发布",
},
replySuccessText: {
type: String,
default: "回复已发送",
},
listHandler: {
type: Function,
required: true,
},
repliesHandler: {
type: Function,
required: true,
},
publishHandler: {
type: Function,
required: true,
},
normalizeComment: {
type: Function,
required: true,
},
likeHandler: {
type: Function,
default: null,
},
});
const emit = defineEmits(["need-login", "published"]);
const userStore = useUserStore();
const comments = ref([]);
const currentTab = ref("hot");
const currentTab = ref(defaultTabs[0].value);
const currentPage = ref(1);
const hasMore = ref(true);
const loading = ref(false);
const sending = ref(false);
const sendingReply = ref(false);
const loadError = ref("");
const commentText = ref("");
const replyTarget = ref(null);
@@ -184,86 +333,59 @@ const replyPopupVisible = ref(false);
const replyInputFocus = ref(false);
const replyContent = ref("");
const replyKeyboardHeight = ref(0);
const sendingReply = ref(false);
let keyboardHeightListener = null;
const selectedTone = computed(() => {
if (!props.currentPair || !props.selectedItemId) return "";
if (props.selectedItemId === props.currentPair.left?.id) return "left";
if (props.selectedItemId === props.currentPair.right?.id) return "right";
return "";
});
const isLoggedIn = computed(() => !!userStore.token || !!userStore.userInfo?.nickName);
const replyPlaceholder = computed(() => {
return replyTarget.value?.replyToName
? `回复 @${replyTarget.value.replyToName}...`
: "写下你的回复";
return replyTarget.value?.replyToName ? `回复 @${replyTarget.value.replyToName}...` : "写下你的回复";
});
const buildAvatarUrl = (avatar) => {
if (!avatar) return "https://api.dicebear.com/7.x/avataaars/svg?seed=fallback";
const normalizedAvatar = String(avatar).trim();
return normalizedAvatar.startsWith("http") ? normalizedAvatar : `${FILE_BASE_URL}${normalizedAvatar}`;
const parseListResponse = (res) => {
const source = res?.data || res || {};
const rawList =
source.list ||
source.records ||
res?.list ||
res?.records ||
(Array.isArray(source) ? source : []);
return Array.isArray(rawList) ? rawList : [];
};
const resolveChoiceMeta = (chooseItemId) => {
if (!chooseItemId || !props.currentPair) {
return { choiceLabel: "", choiceTone: "" };
const resolveHasMore = (res, list, page) => {
const data = res?.data || res || {};
const hasNext = data?.hasNext ?? res?.hasNext;
if (typeof hasNext === "boolean") return hasNext;
const total = Number(data?.totalCount ?? data?.total ?? res?.totalCount ?? res?.total ?? 0);
if (total > 0) {
const safeSize = Math.max(list.length, 1);
return page * safeSize < total;
}
if (chooseItemId === props.currentPair.left?.id) {
return {
choiceLabel: `支持 ${props.currentPair.left.name}`,
choiceTone: "left",
};
}
if (chooseItemId === props.currentPair.right?.id) {
return {
choiceLabel: `支持 ${props.currentPair.right.name}`,
choiceTone: "right",
};
}
return { choiceLabel: "已站队", choiceTone: "" };
const pages = Number(data?.pages || res?.pages || 0);
if (pages > 0) return page < pages;
return list.length > 0;
};
const normalizeComment = (item = {}, rootComment = null) => {
const user = item.user || {};
const replyToUser = item.replyToUser || {};
const choiceMeta = resolveChoiceMeta(item.chooseItemId);
const emitNeedLogin = () => {
emit("need-login");
};
return {
id: item.id,
rootCommentId: item.rootCommentId || rootComment?.id || null,
parentCommentId: item.parentCommentId || rootComment?.id || null,
replyToCommentId: item.replyToCommentId || null,
name: user.nickname || "匿名用户",
avatar: buildAvatarUrl(user.avatar),
time: formatDate(item.createdAt) || "刚刚",
content: item.content || "",
likes: Number(item.likeCount || 0),
isLiked: !!item.isLiked,
userAction: "",
replyCount: Number(item.replyCount || 0),
replyToName: replyToUser.nickname || "",
choiceLabel: choiceMeta.choiceLabel,
choiceTone: choiceMeta.choiceTone,
chooseItemId: item.chooseItemId || "",
repliesLoading: false,
repliesLoaded: false,
repliesHasMore: false,
repliesPage: 1,
replies: [],
};
const ensureLogin = () => {
if (isLoggedIn.value) return true;
emitNeedLogin();
return false;
};
const resetState = () => {
comments.value = [];
currentTab.value = "hot";
currentPage.value = 1;
hasMore.value = true;
loading.value = false;
sending.value = false;
sendingReply.value = false;
loadError.value = "";
commentText.value = "";
closeReplyPopup();
@@ -276,24 +398,8 @@ const patchCommentItem = (commentId, updater) => {
});
};
const resolveHasMore = (res, list, page) => {
const data = res?.data || res || {};
const hasNext = data?.hasNext ?? res?.hasNext;
if (typeof hasNext === "boolean") return hasNext;
const total = Number(data?.totalCount ?? data?.total ?? res?.totalCount ?? res?.total ?? 0);
if (total > 0) {
return page * Math.max(1, list.length) < total;
}
const pages = Number(data?.pages || res?.pages || 0);
if (pages > 0) return page < pages;
return list.length > 0;
};
const loadComments = async ({ reset = false } = {}) => {
if (!props.visible || !props.pkId || loading.value) return;
if (!props.visible || !props.requestKey || loading.value) return;
if (!reset && !hasMore.value) return;
const page = reset ? 1 : currentPage.value;
@@ -301,26 +407,18 @@ const loadComments = async ({ reset = false } = {}) => {
try {
loading.value = true;
loadError.value = "";
const res = await fetchCommentList({
pkId: props.pkId,
const res = await props.listHandler({
page,
orderBy: currentTab.value,
});
const source = res?.data || res || {};
const rawList =
source.list ||
source.records ||
res?.list ||
res?.records ||
(Array.isArray(source) ? source : []);
const list = Array.isArray(rawList) ? rawList : [];
const normalized = list.map((item) => normalizeComment(item));
const list = parseListResponse(res);
const normalized = list.map((item) => props.normalizeComment(item));
comments.value = reset ? normalized : [...comments.value, ...normalized];
hasMore.value = resolveHasMore(res, list, page);
currentPage.value = page + 1;
} catch (error) {
loadError.value = "网络开了点小差,稍后重试";
loadError.value = props.errorFallbackText;
} finally {
loading.value = false;
}
@@ -332,6 +430,11 @@ const refreshComments = async () => {
await loadComments({ reset: true });
};
const loadMoreComments = async () => {
if (loading.value || !hasMore.value) return;
await loadComments();
};
const switchTab = (tab) => {
if (currentTab.value === tab) return;
currentTab.value = tab;
@@ -339,22 +442,26 @@ const switchTab = (tab) => {
};
const submitMainComment = async () => {
if (!isLoggedIn.value) {
emit("need-login");
return;
}
if (!ensureLogin()) return;
const content = commentText.value.trim();
if (!content || sending.value || !props.pkId || !props.selectedItemId) return;
if (!content || sending.value) return;
try {
sending.value = true;
await publishComment({
pkId: props.pkId,
chooseItemId: props.selectedItemId,
await props.publishHandler({
content,
mode: "comment",
replyTarget: null,
});
uni.showToast({ title: "评论已发布", icon: "none" });
if (props.showSuccessToast) {
uni.showToast({ title: props.mainSuccessText, icon: "none" });
}
commentText.value = "";
emit("published", {
mode: "comment",
content,
replyTarget: null,
});
await refreshComments();
} catch (error) {
uni.showToast({ title: "发布失败", icon: "none" });
@@ -364,10 +471,7 @@ const submitMainComment = async () => {
};
const openReplyPopup = async (payload) => {
if (!isLoggedIn.value) {
emit("need-login");
return;
}
if (!ensureLogin()) return;
replyTarget.value = payload;
replyPopupVisible.value = true;
await nextTick();
@@ -385,24 +489,27 @@ const closeReplyPopup = () => {
};
const submitReplyComment = async () => {
if (!isLoggedIn.value) {
emit("need-login");
return;
}
if (!ensureLogin()) return;
const content = replyContent.value.trim();
if (!content || !replyTarget.value || sendingReply.value || !props.pkId || !props.selectedItemId) return;
if (!content || !replyTarget.value || sendingReply.value) return;
try {
sendingReply.value = true;
await publishComment({
pkId: props.pkId,
chooseItemId: props.selectedItemId,
await props.publishHandler({
content,
parentCommentId: replyTarget.value.parentCommentId,
replyToCommentId: replyTarget.value.replyToCommentId,
mode: "reply",
replyTarget: replyTarget.value,
});
uni.showToast({ title: "回复已发送", icon: "none" });
if (props.showSuccessToast) {
uni.showToast({ title: props.replySuccessText, icon: "none" });
}
const publishedReplyTarget = replyTarget.value;
closeReplyPopup();
emit("published", {
mode: "reply",
content,
replyTarget: publishedReplyTarget,
});
await refreshComments();
} catch (error) {
uni.showToast({ title: "回复失败", icon: "none" });
@@ -412,7 +519,7 @@ const submitReplyComment = async () => {
};
const loadReplies = async (comment, page = 1) => {
if (!comment?.id || !props.pkId) return;
if (!comment?.id) return;
patchCommentItem(comment.id, (item) => ({
...item,
@@ -420,15 +527,12 @@ const loadReplies = async (comment, page = 1) => {
}));
try {
const res = await fetchCommentReplyList({
pkId: props.pkId,
const res = await props.repliesHandler({
rootCommentId: comment.id,
page,
});
const source = res?.data || res || {};
const rawList = source.list || res?.list || [];
const list = Array.isArray(rawList) ? rawList : [];
const normalizedReplies = list.map((reply) => normalizeComment(reply, comment));
const list = parseListResponse(res);
const normalizedReplies = list.map((reply) => props.normalizeComment(reply, comment));
const hasMoreReplies = resolveHasMore(res, list, page);
patchCommentItem(comment.id, (item) => ({
@@ -486,9 +590,9 @@ const handleCommentLikeChange = ({ id, parentId, isReply, isLiked, likes }) => {
};
watch(
() => [props.pkId, props.visible, props.selectedItemId],
([pkId, visible, selectedItemId]) => {
if (!pkId || !visible || !selectedItemId) {
() => [props.requestKey, props.visible],
([requestKey, visible]) => {
if (!requestKey || !visible) {
resetState();
return;
}
@@ -500,16 +604,6 @@ watch(
{ immediate: true }
);
watch(
() => props.currentPair,
() => {
comments.value = comments.value.map((comment) => ({
...comment,
...resolveChoiceMeta(comment.chooseItemId),
}));
}
);
if (uni.onKeyboardHeightChange) {
keyboardHeightListener = (res) => {
replyKeyboardHeight.value = res?.height || 0;
@@ -525,12 +619,12 @@ onUnmounted(() => {
defineExpose({
refreshComments,
loadMoreComments,
});
</script>
<style lang="scss" scoped>
.pk-comment-section {
margin-top: 24rpx;
.comment-section {
padding: 32rpx;
border-radius: 32rpx;
background: rgba(255, 255, 255, 0.94);
@@ -538,6 +632,14 @@ defineExpose({
box-shadow: 0 18rpx 42rpx rgba(87, 92, 145, 0.08);
}
.comment-section--topic {
margin-top: 0;
}
.comment-section--pk {
margin-top: 24rpx;
}
.comment-header {
display: flex;
align-items: center;
@@ -551,6 +653,17 @@ defineExpose({
gap: 34rpx;
}
.comment-title-wrap {
display: flex;
align-items: center;
}
.comment-title {
font-size: 32rpx;
font-weight: 800;
color: #1f2432;
}
.comment-tab {
font-size: 30rpx;
color: #8a90a0;
@@ -576,7 +689,7 @@ defineExpose({
background: linear-gradient(90deg, #6557ff, #4d44f1);
}
.my-choice-pill {
.header-pill {
flex-shrink: 0;
display: inline-flex;
align-items: center;
@@ -586,22 +699,22 @@ defineExpose({
background: rgba(92, 67, 245, 0.1);
}
.my-choice-pill--right {
.header-pill--right {
background: rgba(255, 141, 95, 0.12);
}
.my-choice-pill-label {
.header-pill-label {
font-size: 22rpx;
color: #8a90a0;
}
.my-choice-pill-value {
.header-pill-value {
font-size: 22rpx;
font-weight: 700;
color: #4d44f1;
}
.my-choice-pill--right .my-choice-pill-value {
.header-pill--right .header-pill-value {
color: #ff7a45;
}
@@ -693,6 +806,53 @@ defineExpose({
background: #f8f9ff;
}
.comment-state--empty {
background: linear-gradient(180deg, rgba(248, 249, 255, 0.92) 0%, rgba(255, 255, 255, 0.96) 100%);
}
.comment-empty-visual {
position: relative;
width: 176rpx;
height: 176rpx;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 24rpx;
}
.comment-empty-core {
position: relative;
z-index: 2;
width: 112rpx;
height: 112rpx;
border-radius: 50%;
background: linear-gradient(135deg, #ffffff 0%, #eef2ff 100%);
box-shadow: 0 16rpx 34rpx rgba(99, 102, 241, 0.14);
display: flex;
align-items: center;
justify-content: center;
}
.comment-empty-emoji {
font-size: 50rpx;
}
.comment-empty-orbit {
position: absolute;
border-radius: 50%;
border: 2rpx dashed rgba(99, 102, 241, 0.16);
}
.orbit-1 {
inset: 12rpx;
}
.orbit-2 {
inset: 32rpx;
border-style: solid;
border-color: rgba(129, 140, 248, 0.12);
}
.comment-state-title {
display: block;
font-size: 30rpx;
@@ -708,6 +868,14 @@ defineExpose({
line-height: 1.7;
}
.comment-state-tip {
display: block;
margin-top: 12rpx;
font-size: 22rpx;
color: #a0a6b5;
line-height: 1.7;
}
.comment-state-btn {
margin-top: 22rpx;
height: 72rpx;