聊天记录展示

This commit is contained in:
2025-10-15 18:55:01 +08:00
parent d984cb1457
commit 5714ae08bb
8 changed files with 285 additions and 137 deletions
+26 -14
View File
@@ -138,11 +138,11 @@ export class ChatController {
if (roleId && roleId > 0) {
ChatAIService.Instance.setCurrentRole(roleId);
// 从ChatHistoryManager加载对话记录到ChatModel中
this.loadDialogsFromHistory(roleId);
// 从ChatHistoryManager加载最近10条对话记录到ChatModel中
this.loadDialogsFromHistory(roleId, 10);
// 同步到DialogManager
//this.syncDialogData();
// 同步对话数据到DialogManager和UI
this.syncDialogData();
logger.log(`ChatController initialized with role ${roleId}`);
} else {
@@ -165,15 +165,15 @@ export class ChatController {
return false;
}
// 更新AI服务的当前角色
ChatAIService.Instance.setCurrentRole(roleId);
// 从ChatHistoryManager加载对话记录到ChatModel中
this.loadDialogsFromHistory(roleId);
// 从ChatHistoryManager加载最近10条对话记录到ChatModel中
this.loadDialogsFromHistory(roleId, 10);
// 同步对话数据到DialogManager
//this.syncDialogData();
// 同步对话数据到DialogManager和UI
this.syncDialogData();
logger.log(`ChatController switched to role ${roleId}`);
return true;
@@ -371,8 +371,9 @@ export class ChatController {
/**
* 从ChatHistoryManager加载对话记录到ChatModel中
* @param roleId 角色ID,不传则使用当前角色
* @param limit 加载消息数量限制,默认10条(0表示加载全部)
*/
public loadDialogsFromHistory(roleId?: number): void {
public loadDialogsFromHistory(roleId?: number, limit: number = 10): void {
const targetRoleId = roleId || this.chatModel.getCurrentRoleId();
if (!targetRoleId) {
logger.warn("Cannot load dialogs: no active role");
@@ -380,7 +381,15 @@ export class ChatController {
}
// 从ChatHistoryManager加载聊天记录
const chatHistory = ChatHistoryManager.Instance.loadHistory(targetRoleId);
let chatHistory = ChatHistoryManager.Instance.loadHistory(targetRoleId);
// 如果设置了限制,只取最近的N条消息
if (limit > 0 && chatHistory.length > limit) {
chatHistory = chatHistory.slice(-limit);
logger.log(
`Limited chat history to recent ${limit} messages for role ${targetRoleId}`
);
}
// 清空ChatModel中的对话记录
this.chatModel.clearDialogs(targetRoleId);
@@ -398,8 +407,8 @@ export class ChatController {
}
/**
* 同步ChatModel的对话数据到DialogManager
* 用于确保DialogManager和ChatModel的数据一致性
* 同步ChatModel的对话数据到DialogManager和UI
* 用于确保DialogManager和ChatModel的数据一致性,并更新UI显示
*/
public syncDialogData(): void {
if (!this.dialogManager || !this.chatModel.validate()) {
@@ -410,7 +419,10 @@ export class ChatController {
}
const dialogs = this.chatModel.getDialogs();
this.dialogManager.syncFromChatModel(dialogs);
// 使用loadHistoryDialogs方法加载历史对话到DialogManager
this.dialogManager.loadHistoryDialogs(dialogs);
logger.log(
`Synced ${dialogs.length} dialogs from ChatModel to DialogManager`
);
+37 -13
View File
@@ -4,12 +4,11 @@ export interface Dialog {
}
export class DiaLogData {
public playerDialog: Dialog = null;
public aiDialogs: Dialog[] = [];
// 统一的对话数组,保存所有历史对话
private dialogs: Dialog[] = [];
public cleanDialog() {
this.playerDialog = null;
this.aiDialogs = [];
this.dialogs = [];
}
public pushDialog(
@@ -17,17 +16,42 @@ export class DiaLogData {
str: string,
isLoading: boolean = false
) {
if (isPlayer) {
this.playerDialog = { isPlayer: true, content: str };
} else {
this.aiDialogs.push({ isPlayer: false, content: str });
}
// 追加新对话到数组末尾
this.dialogs.push({ isPlayer, content: str });
}
public GetPlayerDialog() {
return this.playerDialog;
/**
* 获取最后一条玩家对话(兼容旧接口)
*/
public GetPlayerDialog(): Dialog | null {
// 从后往前查找最后一条玩家消息
for (let i = this.dialogs.length - 1; i >= 0; i--) {
if (this.dialogs[i].isPlayer) {
return this.dialogs[i];
}
}
return null;
}
public GetAIDialog() {
return this.aiDialogs;
/**
* 获取所有AI对话(兼容旧接口)
*/
public GetAIDialog(): Dialog[] {
// 返回所有AI消息
return this.dialogs.filter(dialog => !dialog.isPlayer);
}
/**
* 获取所有对话记录
*/
public getAllDialogs(): Dialog[] {
return [...this.dialogs];
}
/**
* 批量设置对话记录(用于加载历史)
*/
public setDialogs(dialogs: Dialog[]): void {
this.dialogs = [...dialogs];
}
}
@@ -44,16 +44,14 @@ export class DialogManager {
*
* @param {boolean} isPlayer - 是否为玩家消息
* @param {string} str - 消息内容
* @param {boolean} fromPlayer - 是否来自玩家输入(用于清理对话
* @param {boolean} fromPlayer - 是否来自玩家输入(已废弃,保留参数兼容性
*/
public updateDialog(
isPlayer: boolean,
str: string,
fromPlayer: boolean = false
): void {
if (fromPlayer) {
this.dialogData.cleanDialog();
}
// 移除清空逻辑,改为追加模式以支持历史记录显示
this.dialogData.pushDialog(isPlayer, str);
}
@@ -62,16 +60,14 @@ export class DialogManager {
*
* @param {boolean} isPlayer - 是否为玩家消息
* @param {string} str - 消息内容
* @param {boolean} fromPlayer - 是否来自玩家输入(用于清理对话
* @param {boolean} fromPlayer - 是否来自玩家输入(已废弃,保留参数兼容性
*/
public updateDialogWithSegments(
isPlayer: boolean,
str: string,
fromPlayer: boolean = false
): void {
if (fromPlayer) {
this.dialogData.cleanDialog();
}
// 移除清空逻辑,改为追加模式以支持历史记录显示
// 如果是玩家消息,直接添加单个气泡
if (isPlayer) {
@@ -182,4 +178,43 @@ export class DialogManager {
logger.log("DialogManager: Synced dialogs from ChatModel");
}
/**
* 加载历史对话记录(用于初始化显示)
* @param dialogs 历史对话数组
*/
public loadHistoryDialogs(dialogs: Dialog[]): void {
// 清空当前对话
this.dialogData.cleanDialog();
// 遍历历史对话,对AI消息进行分段处理
let totalSegments = 0;
dialogs.forEach((dialog) => {
if (dialog.isPlayer) {
// 玩家消息直接添加
this.dialogData.pushDialog(dialog.isPlayer, dialog.content);
totalSegments++;
} else {
// AI消息进行分段处理
const segments = this.splitMessageIntoSegments(dialog.content);
if (segments.length <= 1) {
// 单段消息直接添加
this.dialogData.pushDialog(dialog.isPlayer, dialog.content);
totalSegments++;
} else {
// 多段消息,每段作为独立气泡
segments.forEach((segment) => {
this.dialogData.pushDialog(dialog.isPlayer, segment);
totalSegments++;
});
}
}
});
logger.log(
`DialogManager: Loaded ${dialogs.length} history dialogs (expanded to ${totalSegments} segments)`
);
// 通知UI更新
Utils.sendInnerMsg(InnerMsgCode.Chat_DialogRefresh);
}
}
@@ -43,13 +43,16 @@ export class ChatContentsLayout extends Component {
private isPressing: boolean = false;
// 长按计时器
private longPressTimer: number = null;
// 已显示的AI对话数量(用于避免重复显示)
private displayedAIDialogCount: number = 0;
fixMaxWidth: number;
protected start(): void {
this.lBubble.node.active = false;
this.rBubble.node.active = false;
this.fixMaxWidth = 534.4;
// 设置气泡最大宽度为屏幕宽度的70%
this.fixMaxWidth = view.getVisibleSize().width * 0.7;
// 获取或添加UIOpacity组件到content节点
this.contentOpacity =
@@ -77,37 +80,44 @@ export class ChatContentsLayout extends Component {
}
/**
* 更新玩家输入的对话
* 更新玩家输入的对话(追加模式,不清空历史)
* @param dialog 玩家输入的对话数据
*/
updatePlayerDialog(dialog: Dialog): void {
// 清理所有现有气泡到缓存池
this.clearAllBubbles();
if (!dialog) return;
// 清理所有延时任务
this.clearDelayedTasks();
// 不再清空气泡,改为追加模式以支持历史记录
// 创建玩家气泡(插入到首位,Layout会让它显示在最下面)
// 创建玩家气泡
const playerBubble = this.createOrGetBubble(true);
playerBubble.node.active = true;
playerBubble.updateBubbleContent(dialog.content, true);
this.bubbles.push(playerBubble);
// 滚动到底部
this.scheduleOnce(() => {
this.scrollView.scrollToBottom();
}, 0);
}
/**
* 更新AI回复的对话
* 更新AI回复的对话(智能追加,避免重复显示)
* @param dialogs AI回复的对话数据数组
*/
updateAIDialogs(dialogs: Dialog[]): void {
// 清除等待回复气泡
// if (this.waitingBubble) {
// this.removeWaitingBubble();
// }
if (!dialogs || dialogs.length === 0) return;
// 清理之前的延时任务
this.clearDelayedTasks();
// 逐个添加AI对话,带延时
this.addAIDialogsWithDelay(dialogs, 0);
// 只添加新的AI对话(避免重复显示历史记录)
const newDialogs = dialogs.slice(this.displayedAIDialogCount);
if (newDialogs.length > 0) {
// 更新已显示数量
this.displayedAIDialogCount = dialogs.length;
// 逐个添加新的AI对话,带延时
this.addAIDialogsWithDelay(newDialogs, 0);
}
this.node.position = Vec3.ZERO;
// 滚动到底部(等待下一帧Layout更新完成)
@@ -117,9 +127,9 @@ export class ChatContentsLayout extends Component {
}
/**
* 清理所有气泡到缓存池
* 清理所有气泡到缓存池(改为public,供外部调用)
*/
private clearAllBubbles(): void {
public clearAllBubbles(): void {
for (const bubble of this.bubbles) {
if (bubble && bubble.node) {
bubble.node.active = false;
@@ -129,10 +139,48 @@ export class ChatContentsLayout extends Component {
this.bubbles = [];
//this.waitingBubble = null;
// 重置AI对话计数器
this.displayedAIDialogCount = 0;
// 清理多余的缓存气泡
this.cleanupExcessCachedBubbles();
}
/**
* 加载所有历史对话(用于初始化)
* @param dialogs 所有对话记录
*/
public loadAllDialogs(dialogs: Dialog[]): void {
if (!dialogs || dialogs.length === 0) return;
// 清空现有气泡
this.clearAllBubbles();
this.clearDelayedTasks();
// 倒序遍历对话,从最后一个开始插入(保持正确的显示顺序)
for (let i = dialogs.length - 1; i >= 0; i--) {
const dialog = dialogs[i];
const bubble = this.createOrGetBubble(dialog.isPlayer);
bubble.node.active = true;
bubble.updateBubbleContent(dialog.content, dialog.isPlayer);
// 每个气泡插入到首位,确保旧消息在上面,新消息在下面
bubble.node.setSiblingIndex(0);
this.bubbles.push(bubble);
// 统计AI对话数量
if (!dialog.isPlayer) {
this.displayedAIDialogCount++;
}
}
// 滚动到底部
this.scheduleOnce(() => {
this.scrollView.scrollToBottom();
}, 0.1);
console.log(`ChatContentsLayout: Loaded ${dialogs.length} history dialogs`);
}
/**
* 从缓存池获取或创建新的气泡
* @param isPlayer 是否为玩家气泡
@@ -198,12 +246,12 @@ export class ChatContentsLayout extends Component {
const aiBubble = this.createOrGetBubble(false);
aiBubble.node.active = true;
aiBubble.updateBubbleContent(dialog.content, false);
// AI消息插入到首位,显示在最上面
aiBubble.node.setSiblingIndex(0);
// AI消息自然追加到末尾,显示在最下面(与玩家消息保持一致)
this.bubbles.push(aiBubble);
this.scheduleOnce(() => {
this.scrollView.scrollToBottom();
}, 0);
this.bubbles.push(aiBubble);
// 递归处理下一条对话
this.addAIDialogsWithDelay(dialogs, index + 1);
@@ -129,6 +129,12 @@ export class ChatPanel extends li_BaseView implements IChatPanelCallback {
this,
this.onChatCountChange
);
Utils.addInnerEL(
InnerMsgCode.Chat_DialogRefresh,
this,
this.onDialogRefresh
);
}
onDestroy(): void {
@@ -147,6 +153,11 @@ export class ChatPanel extends li_BaseView implements IChatPanelCallback {
this,
this.onEmotionInitialized
);
Utils.removeInnerEL(
InnerMsgCode.Chat_DialogRefresh,
this,
this.onDialogRefresh
);
// 停止视频播放,释放资源
if (this.videoLayer) {
@@ -402,6 +413,22 @@ export class ChatPanel extends li_BaseView implements IChatPanelCallback {
}
}
}
/**
* 对话刷新事件处理(用于加载历史记录)
*/
private onDialogRefresh = (): void => {
if (!this.layout) return;
// 获取所有对话记录
const dialogManager = DialogManager.getInstance();
const allDialogs = dialogManager["dialogData"].getAllDialogs();
logger.log(`ChatPanel: Loading ${allDialogs.length} history dialogs to UI`);
// 加载所有对话到UI
this.layout.loadAllDialogs(allDialogs);
};
protected onEnable(): void {
if (!this.manager) this.manager = DialogManager.getInstance();
@@ -98,7 +98,7 @@ export class ShowPanel extends li_BaseView {
// 阻止事件冒泡
event.propagationStopped = true;
// 阻止浏览器默认行为(如拖动、滚动)
event.preventDefault();
//event.preventDefault();
}
protected onClose() {