# Conflicts:
#	pages/chat/components/messageList.vue
#	uni_modules/z-paging/changelog.md
#	uni_modules/z-paging/components/z-paging-cell/z-paging-cell.vue
#	uni_modules/z-paging/components/z-paging-empty-view/z-paging-empty-view.vue
#	uni_modules/z-paging/components/z-paging-swiper-item/z-paging-swiper-item.vue
#	uni_modules/z-paging/components/z-paging-swiper/z-paging-swiper.vue
#	uni_modules/z-paging/components/z-paging/components/z-paging-load-more.vue
#	uni_modules/z-paging/components/z-paging/components/z-paging-refresh.vue
#	uni_modules/z-paging/components/z-paging/css/z-paging-main.css
#	uni_modules/z-paging/components/z-paging/js/modules/back-to-top.js
#	uni_modules/z-paging/components/z-paging/js/modules/common-layout.js
#	uni_modules/z-paging/components/z-paging/js/modules/data-handle.js
#	uni_modules/z-paging/components/z-paging/js/modules/i18n.js
#	uni_modules/z-paging/components/z-paging/js/modules/load-more.js
#	uni_modules/z-paging/components/z-paging/js/modules/nvue.js
#	uni_modules/z-paging/components/z-paging/js/modules/refresher.js
#	uni_modules/z-paging/components/z-paging/js/modules/scroller.js
#	uni_modules/z-paging/components/z-paging/js/modules/virtual-list.js
#	uni_modules/z-paging/components/z-paging/js/z-paging-constant.js
#	uni_modules/z-paging/components/z-paging/js/z-paging-enum.js
#	uni_modules/z-paging/components/z-paging/js/z-paging-main.js
#	uni_modules/z-paging/components/z-paging/js/z-paging-utils.js
#	uni_modules/z-paging/components/z-paging/z-paging.vue
#	uni_modules/z-paging/package.json
#	uni_modules/z-paging/readme.md
This commit is contained in:
YunaiV
2025-05-12 21:26:31 +08:00
46 changed files with 365 additions and 7817 deletions
+87 -4
View File
@@ -7,7 +7,11 @@
:clearable="false"
v-model="message"
placeholder="请输入你要咨询的问题"
:maxlength="maxLength"
:focus="autoFocus"
@focus="handleFocus"
></uni-easyinput>
<text v-if="showCharCount" class="char-count">{{ message.length }}/{{ maxLength }}</text>
</view>
<text class="sicon-basic bq" @tap.stop="onTools('emoji')"></text>
<text
@@ -16,14 +20,21 @@
:class="{ 'is-active': toolsMode === 'tools' }"
@tap.stop="onTools('tools')"
></text>
<button v-if="message" class="ss-reset-button send-btn" @tap="sendMessage">
发送
<button
v-if="message"
class="ss-reset-button send-btn"
@tap="sendMessage"
:disabled="isDisabled || sending"
:class="{ 'disabled': isDisabled || sending }"
>
<text v-if="sending">发送中</text>
<text v-else>发送</text>
</button>
</view>
</template>
<script setup>
import { computed } from 'vue';
import { computed, ref, onUnmounted } from 'vue';
/**
* 消息发送组件
*/
@@ -38,8 +49,25 @@
type: String,
default: '',
},
// 是否自动获取焦点
autoFocus: {
type: Boolean,
default: false
},
// 最大字数限制
maxLength: {
type: Number,
default: 500
},
// 是否显示字数统计
showCharCount: {
type: Boolean,
default: true
}
});
const emits = defineEmits(['update:modelValue', 'onTools', 'sendMessage']);
const message = computed({
get() {
return props.modelValue;
@@ -49,16 +77,55 @@
}
});
// 控制发送状态
const sending = ref(false);
// 是否禁用发送按钮
const isDisabled = computed(() => {
return !message.value.trim() || message.value.length > props.maxLength;
});
// 输入框获取焦点
const handleFocus = () => {
// 输入框获取焦点时关闭工具栏
if (props.toolsMode !== '') {
onTools('');
}
};
// 打开工具菜单
function onTools(mode) {
emits('onTools', mode);
}
// 防抖处理
let sendTimer = null;
// 发送消息
function sendMessage() {
emits('sendMessage');
// 如果正在发送中,或者内容为空,则不处理
if (sending.value || isDisabled.value) return;
// 清除可能存在的定时器
if (sendTimer) clearTimeout(sendTimer);
// 设置发送状态
sending.value = true;
// 执行发送,并添加防抖
sendTimer = setTimeout(() => {
emits('sendMessage');
// 发送完成后重置状态
setTimeout(() => {
sending.value = false;
}, 300);
}, 300);
}
// 组件卸载时清除定时器
onUnmounted(() => {
if (sendTimer) clearTimeout(sendTimer);
});
</script>
<style scoped lang="scss">
@@ -70,6 +137,16 @@
height: 64rpx;
border-radius: 32rpx;
background: var(--ui-BG-1);
position: relative;
.char-count {
position: absolute;
right: 15rpx;
top: 50%;
transform: translateY(-50%);
font-size: 22rpx;
color: #999;
}
}
.bq {
@@ -97,6 +174,12 @@
font-size: 26rpx;
color: #fff;
margin-left: 11rpx;
transition: all 0.3s;
&.disabled {
opacity: 0.6;
background: #cccccc;
}
}
}
</style>
+229 -97
View File
@@ -1,112 +1,140 @@
<template>
<!-- 聊天虚拟列表 -->
<z-paging
ref="pagingRef"
v-model="messageList"
use-chat-record-mode
use-virtual-list
cell-height-mode="dynamic"
default-page-size="20"
:auto-clean-list-when-reload="false"
safe-area-inset-bottom
bottom-bg-color="#f8f8f8"
:back-to-top-style="backToTopStyle"
:auto-show-back-to-top="showNewMessageTip"
@backToTopClick="onBackToTopClick"
@scrolltoupper="onScrollToUpper"
@query="queryList"
>
<template #top>
<!-- 撑一下顶部导航 -->
<view :style="{ height: sys_navBar + 'px' }"></view>
</template>
<!-- style="transform: scaleY(-1)"必须写否则会导致列表倒置 -->
<!-- 注意不要直接在chat-item组件标签上设置style因为在微信小程序中是无效的请包一层view -->
<template #cell="{ item, index }">
<view style="transform: scaleY(-1)">
<!-- 消息渲染 -->
<MessageListItem
:message="item"
:message-index="index"
:message-list="messageList"
></MessageListItem>
<!-- 聊天列表使用scroll-view原生组件整体倒置 -->
<scroll-view :scroll-top="scroll.top" class="chat-scroll-view" scroll-y :refresher-enabled="false"
@scroll="onScroll" @scrolltolower="loadMoreHistory" style="transform: scaleY(-1);">
<!-- 消息列表容器 -->
<view class="message-container">
<!-- 加载更多提示 -->
<view v-if="isLoading" class="loading-more" style="transform: scaleY(-1);">
<text>加载中...</text>
</view>
</template>
<!-- 底部聊天输入框 -->
<template #bottom>
<slot name="bottom"></slot>
</template>
<!-- 查看最新消息 -->
<template #backToTop>
<text>有新消息</text>
</template>
</z-paging>
<!-- 消息列表 -->
<view class="message-list">
<view v-for="(item, index) in messageList" :key="item.id" class="message-item"
style="transform: scaleY(-1);">
<!-- 消息渲染 -->
<MessageListItem :message="item" :message-index="index" :message-list="messageList"></MessageListItem>
</view>
</view>
</view>
</scroll-view>
<!-- 底部聊天输入框 -->
<su-fixed bottom>
<view v-if="showTip" class="back-top ss-flex ss-row-center ss-m-b-10" @tap="scrollToTop">
<text class="back-top-item ss-flex ss-row-center">{{ showNewMessageTip ? '有新消息' : '回到底部' }}</text>
</view>
<slot name="bottom"></slot>
</su-fixed>
</template>
<script setup>
import MessageListItem from '@/pages/chat/components/messageListItem.vue';
import { reactive, ref } from 'vue';
import { onMounted, reactive, ref, computed } from 'vue';
import KeFuApi from '@/sheep/api/promotion/kefu';
import { isEmpty, formatDate } from '@/sheep/helper/utils';
import { isEmpty } from '@/sheep/helper/utils';
import { formatDate } from '@/sheep/util';
import sheep from '@/sheep';
const sys_navBar = sheep.$platform.navbar;
const { safeAreaInsets } = sheep.$platform.device;
const safeAreaInsetsBottom = safeAreaInsets.bottom + 'px'; // 底部安全区域
const messageList = ref([]); // 消息列表
const showTip = ref(false); // 显示提示
const showNewMessageTip = ref(false); // 显示有新消息提示
const refreshMessage = ref(false); // 更新消息列表
const backToTopStyle = reactive({
width: '100px',
'background-color': '#fff',
'border-radius': '30px',
'box-shadow': '0 2px 4px rgba(0, 0, 0, 0.1)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}); // 返回顶部样式
const isLoading = ref(false); // 是否正在加载更多
const hasMore = ref(true); // 是否还有更多数据
const keyboardHeight = ref(0); // 键盘高度
const scroll = ref({
top: 0,
oldTop: 0,
}); // 滚动位置记录
const queryParams = reactive({
no: 1, // 查询次数,只用于触底计算
no: 1,
limit: 20,
createTime: undefined,
}); // 查询参数
// 计算聊天窗口高度
const chatScrollHeight = computed(() => {
const baseHeight = 'calc(100vh - 150px - ' + safeAreaInsetsBottom + ')';
if (keyboardHeight.value > 0) {
// 键盘弹起状态,减去键盘高度
return `calc(${baseHeight} - ${keyboardHeight.value}px)`;
}
return baseHeight;
});
const pagingRef = ref(null); // 虚拟列表
const queryList = async (no, limit) => {
// 组件加载时会自动触发此方法,因此默认页面加载时会自动触发,无需手动调用
queryParams.no = no;
queryParams.limit = limit;
await getMessageList();
};
// 获得消息分页列表
const getMessageList = async () => {
const { data } = await KeFuApi.getKefuMessageList(queryParams);
if (isEmpty(data)) {
pagingRef.value.completeByNoMore([], true);
return;
}
if (queryParams.no > 1 && refreshMessage.value) {
const newMessageList = [];
for (const message of data) {
if (messageList.value.some((val) => val.id === message.id)) {
continue;
}
newMessageList.push(message);
isLoading.value = true;
try {
const { data } = await KeFuApi.getKefuMessageList(queryParams);
if (isEmpty(data)) {
hasMore.value = false;
return;
}
// 新消息追加到开头
messageList.value = [...newMessageList, ...messageList.value];
pagingRef.value.updateCache(); // 更新缓存
refreshMessage.value = false; // 更新好后重置状态
return;
if (queryParams.no > 1 && refreshMessage.value) {
const newMessageList = [];
for (const message of data) {
if (messageList.value.some((val) => val.id === message.id)) {
continue;
}
newMessageList.push(message);
}
// 新消息追加到开头
messageList.value = [...newMessageList, ...messageList.value];
refreshMessage.value = false; // 更新好后重置状态
return;
}
if (queryParams.no > 1) {
// 加载更多历史消息,追加到现有列表末尾(因为是倒置的,所以旧消息在底部/列表末尾)
if (data.length < queryParams.limit) {
hasMore.value = false; // 如果返回的数据少于请求的数量,说明没有更多数据了
}
// 过滤掉已存在的消息
const historyMessages = data.filter(msg =>
!messageList.value.some(existing => existing.id === msg.id),
);
if (historyMessages.length > 0) {
messageList.value = [...messageList.value, ...historyMessages];
}
} else {
// 首次加载
messageList.value = data;
if (data.length < queryParams.limit) {
hasMore.value = false;
}
}
if (data.slice(-1).length > 0) {
// 设置最后一次历史查询的最后一条消息的 createTime
queryParams.createTime = formatDate(data.slice(-1)[0].createTime);
}
} finally {
isLoading.value = false;
}
if (data.slice(-1).length > 0) {
// 设置最后一次历史查询的最后一条消息的 createTime
queryParams.createTime = formatDate(data.slice(-1)[0].createTime);
}
pagingRef.value.completeByNoMore(data, false);
};
/** 加载更多历史数据 */
const loadMoreHistory = async () => {
if (isLoading.value || !hasMore.value) return;
// 增加页码
queryParams.no += 1;
await getMessageList();
};
/** 刷新消息列表 */
const refreshMessageList = async (message = undefined) => {
if (typeof message !== 'undefined') {
// 追加数据
pagingRef.value.addChatRecordData([message], false);
// 追加数据到列表开头(因为是倒置的,所以新消息在顶部/列表开头)
messageList.value.unshift(message);
showNewMessageTip.value = true;
} else {
queryParams.createTime = undefined;
refreshMessage.value = true;
@@ -115,24 +143,128 @@
// 若已是第一页则不做处理
if (queryParams.no > 1) {
showNewMessageTip.value = true;
showTip.value = true;
} else {
onScrollToUpper();
scrollToTop();
}
};
/** 滚动到最新消息 */
const onBackToTopClick = (event) => {
event(false); // 禁用默认操作
pagingRef.value.scrollToBottom();
/** 滚动到顶部(倒置后相当于滚动到最新消息 */
const scrollToTop = () => {
scroll.value.top = scroll.value.oldTop;
setTimeout(() => {
scroll.value.top = 0;
}, 200); // 等待 view 层同步
showTip.value = false;
};
/** 监听滚动到底部事件(因为 scroll 翻转了顶就是底) */
const onScrollToUpper = () => {
// 若已是第一页则不做处理
if (queryParams.no === 1) {
return;
/** 设置键盘高度 */
const setKeyboardHeight = (height) => {
keyboardHeight.value = height;
// 键盘弹起时,滚动到最新消息
if (height > 0) {
scrollToTop();
}
showNewMessageTip.value = false;
};
defineExpose({ getMessageList, refreshMessageList });
/** 监听消息列表滚动 */
const onScroll = (e) => {
const { scrollTop } = e.detail;
scroll.value.oldTop = scrollTop;
// 当滚动位置超过一定值时,显示"新消息"提示
if (scrollTop > 100) {
showTip.value = true;
} else {
showTip.value = false;
}
};
// 监听键盘弹起和收起事件
const setupKeyboardListeners = () => {
// #ifdef H5
// H5环境
window.addEventListener('resize', () => {
// 窗口大小变化可能是由键盘引起的
if (document.activeElement && (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA')) {
// 估算键盘高度,实际上是窗口高度变化
const currentHeight = window.innerHeight;
const viewportHeight = window.visualViewport ? window.visualViewport.height : window.innerHeight;
const keyboardHeight = currentHeight - viewportHeight;
setKeyboardHeight(keyboardHeight > 0 ? keyboardHeight : 0);
} else {
setKeyboardHeight(0);
}
});
// #endif
// #ifdef MP-WEIXIN
// TODO puhui999: 小程序键盘弹起还有点问题,看看怎么适配
// 微信小程序环境
uni.onKeyboardHeightChange((res) => {
setKeyboardHeight(res.height);
});
// #endif
};
onMounted(() => {
queryParams.no = 1; // 确保首次加载是第一页
scroll.value = {
top: 0,
oldTop: 0,
}
getMessageList();
setupKeyboardListeners();
});
</script>
<style lang="scss" scoped>
.chat-scroll-view {
height: v-bind(chatScrollHeight);
width: 100%;
position: relative;
background-color: #f8f8f8;
z-index: 1;
}
.message-container {
width: 100%;
/* 确保容器至少有一屏高度 */
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: flex-end;
}
.message-list {
width: 100%;
display: flex;
flex-direction: column;
padding-bottom: 20px;
}
.message-item {
margin-bottom: 10px;
}
.loading-more {
width: 100%;
height: 40px;
display: flex;
justify-content: center;
align-items: center;
color: #999;
font-size: 14px;
}
.back-top {
.back-top-item{
height: 30px;
width: 100px;
background-color: #fff;
border-radius: 30px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
}
</style>
+36 -24
View File
@@ -3,7 +3,14 @@
<!-- 消息渲染 -->
<view class="message-item ss-flex-col scroll-item">
<view class="ss-flex ss-row-center ss-col-center">
<!-- 日期 -->
<!-- 系统消息 -->
<view
v-if="message.contentType === KeFuMessageContentTypeEnum.SYSTEM"
class="system-message"
>
{{ message.content }}
</view>
<!-- 日期 - 移到消息内容上方显示 -->
<view
v-if="
message.contentType !== KeFuMessageContentTypeEnum.SYSTEM &&
@@ -13,14 +20,8 @@
>
{{ formatDate(message.createTime) }}
</view>
<!-- 系统消息 -->
<view
v-if="message.contentType === KeFuMessageContentTypeEnum.SYSTEM"
class="system-message"
>
{{ message.content }}
</view>
</view>
<!-- 消息体渲染管理员消息和用户消息并左右展示 -->
<view
v-if="message.contentType !== KeFuMessageContentTypeEnum.SYSTEM"
@@ -42,11 +43,12 @@
sheep.$url.static('/static/img/shop/chat/default.png')
"
mode="aspectFill"
lazy-load
></image>
<!-- 内容 -->
<template v-if="message.contentType === KeFuMessageContentTypeEnum.TEXT">
<view class="message-box" :class="{ admin: message.senderType === UserTypeEnum.ADMIN }">
<mp-html :content="replaceEmoji(getMessageContent(message).text || message.content)" />
<mp-html :content="processedContent" :domain="sheep.$url.cdn('')" lazy-load />
</view>
</template>
<template v-if="message.contentType === KeFuMessageContentTypeEnum.IMAGE">
@@ -140,7 +142,16 @@
return false;
});
// 处理表情
// 缓存表情映射
const emojiMap = computed(() => {
const map = new Map();
emojiList.forEach(emoji => {
map.set(emoji.name, emoji.file);
});
return map;
});
// 处理表情 - 进行缓存优化
function replaceEmoji(data) {
let newData = data;
if (typeof newData !== 'object') {
@@ -148,27 +159,28 @@
let zhEmojiName = newData.match(reg);
if (zhEmojiName) {
zhEmojiName.forEach((item) => {
let emojiFile = selEmojiFile(item);
newData = newData.replace(
item,
`<img class="chat-img" style="width: 24px;height: 24px;margin: 0 3px;vertical-align: middle;" src="${sheep.$url.cdn(
'/static/img/chat/emoji/' + emojiFile,
)}"/>`,
);
const emojiFile = emojiMap.value.get(item) || '';
if (emojiFile) {
newData = newData.replace(
item,
`<img class="chat-img" style="width: 24px;height: 24px;margin: 0 3px;vertical-align: middle;" src="${sheep.$url.cdn(
'/static/img/chat/emoji/' + emojiFile,
)}"/>`,
);
}
});
}
}
return newData;
}
function selEmojiFile(name) {
for (let index in emojiList) {
if (emojiList[index].name === name) {
return emojiList[index].file;
}
// 预处理内容,避免重复计算
const processedContent = computed(() => {
if (props.message.contentType === KeFuMessageContentTypeEnum.TEXT) {
return replaceEmoji(getMessageContent.value(props.message).text || props.message.content);
}
return false;
}
return props.message.content;
});
</script>
<style scoped lang="scss">
+8 -1
View File
@@ -13,6 +13,9 @@
v-model="chat.msg"
@on-tools="onTools"
@send-message="onSendMessage"
:auto-focus="false"
:show-char-count="true"
:max-length="500"
></message-input>
</template>
</MessageList>
@@ -29,6 +32,9 @@
v-model="chat.msg"
@on-tools="onTools"
@send-message="onSendMessage"
:auto-focus="false"
:show-char-count="true"
:max-length="500"
></message-input>
</tools-popup>
<!-- 商品订单选择 -->
@@ -77,7 +83,6 @@
content: JSON.stringify({ text: chat.msg }),
};
await KeFuApi.sendKefuMessage(data);
await messageListRef.value.refreshMessageList();
chat.msg = '';
} finally {
chat.showTools = false;
@@ -181,6 +186,8 @@
// 2.3 消息类型:KEFU_MESSAGE_ADMIN_READ
if (type === WebSocketMessageTypeConstants.KEFU_MESSAGE_ADMIN_READ) {
console.log('管理员已读消息');
// 更新消息已读状态
sheep.$helper.toast('客服已读您的消息');
}
},
});