Files
spring-ai-skill/src/main/resources/static/js/chat-ui.js
T
hughhuang(黄健铭)andClaude 6b602f5cd0 feat: 优化系统提示词,强调优先使用 Skill 工具
- 修改 Application.java 中的系统提示词,明确工具优先级
- 强调对于任何用户任务都应优先检查并使用匹配的 Skill
- 移除 AskUserQuestionTool 以解决启动错误
- 添加项目文档 CLAUDE.md
- 更新前端界面和交互逻辑

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-02-04 12:07:53 +08:00

989 lines
32 KiB
JavaScript

/**
* UI 渲染模块
* 负责所有 DOM 操作和 UI 组件渲染
*/
const ChatUI = {
// DOM 元素缓存
elements: {},
// 当前活动的过程容器
activeProcessContainer: null,
/**
* 初始化 DOM 元素缓存
*/
init() {
this.elements = {
messagesContainer: document.getElementById('messages'),
chatForm: document.getElementById('chat-form'),
userInput: document.getElementById('user-input'),
sendBtn: document.getElementById('send-btn'),
clearBtn: document.getElementById('clear-btn'),
connectionStatus: document.getElementById('connection-status'),
toolToggle: document.getElementById('tool-toggle'),
menuToggle: document.getElementById('menu-toggle'),
sidebar: document.querySelector('.sidebar'),
newChatBtn: document.getElementById('new-chat-btn')
};
// 初始化 marked.js 配置
this.initMarked();
// 绑定侧边栏事件
this.bindSidebarEvents();
},
/**
* 获取 DOM 元素
*/
get(id) {
return this.elements[id] || document.getElementById(id);
},
/**
* 绑定侧边栏事件
*/
bindSidebarEvents() {
const { menuToggle, sidebar, newChatBtn } = this.elements;
// 移动端菜单切换
if (menuToggle) {
menuToggle.addEventListener('click', () => {
sidebar.classList.toggle('open');
});
}
// 点击外部关闭侧边栏
document.addEventListener('click', (e) => {
if (sidebar && menuToggle &&
!sidebar.contains(e.target) &&
!menuToggle.contains(e.target) &&
sidebar.classList.contains('open')) {
sidebar.classList.remove('open');
}
});
// 快速操作按钮
document.querySelectorAll('.quick-action-btn').forEach(btn => {
btn.addEventListener('click', () => {
const prompt = btn.dataset.prompt;
if (prompt) {
this.elements.userInput.value = prompt;
this.autoResizeInput();
this.elements.userInput.focus();
}
});
});
// 新对话按钮
if (newChatBtn) {
newChatBtn.addEventListener('click', () => {
this.handleNewChat();
});
}
},
/**
* 初始化 Marked.js 配置
*/
initMarked() {
marked.setOptions({
breaks: true,
gfm: true,
highlight: (code, lang) => {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(code, { language: lang }).value;
} catch (err) {
console.error('代码高亮错误:', err);
}
}
return hljs.highlightAuto(code).value;
}
});
},
// ==================== 消息渲染 ====================
/**
* 渲染用户消息
*/
renderUserMessage(content) {
this.hideWelcomeMessage();
this.activeProcessContainer = null; // 重置活动容器
const messageDiv = document.createElement('div');
messageDiv.className = 'message user';
const avatar = document.createElement('div');
avatar.className = 'message-avatar';
avatar.innerHTML = '<i data-lucide="user" class="icon-sm"></i>';
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
contentDiv.textContent = content;
messageDiv.appendChild(avatar);
messageDiv.appendChild(contentDiv);
this.elements.messagesContainer.appendChild(messageDiv);
lucide.createIcons();
this.scrollToBottom();
return messageDiv;
},
/**
* 创建新的 AI 消息容器(包含过程详情和最终回复)
*/
createAssistantMessageContainer() {
this.hideWelcomeMessage();
const messageGroup = document.createElement('div');
messageGroup.className = 'message-group assistant';
// 头像
const avatar = document.createElement('div');
avatar.className = 'message-avatar';
avatar.innerHTML = '<i data-lucide="bot" class="icon-sm"></i>';
// 消息主体
const messageBody = document.createElement('div');
messageBody.className = 'message-body';
// 过程详情(可折叠)
const processDetails = document.createElement('div');
processDetails.className = 'process-details';
// 头部(点击折叠/展开)
const detailsHeader = document.createElement('div');
detailsHeader.className = 'process-details-header';
detailsHeader.innerHTML = `
<span class="process-status">
<i data-lucide="loader-2" class="icon-xs spinning"></i>
<span class="status-text">思考中...</span>
</span>
<span class="process-toggle">
<i data-lucide="chevron-down" class="icon-sm"></i>
</span>
`;
// 步骤列表
const stepsList = document.createElement('div');
stepsList.className = 'process-steps';
// 点击折叠/展开
detailsHeader.addEventListener('click', () => {
processDetails.classList.toggle('collapsed');
const icon = detailsHeader.querySelector('.process-toggle i');
if (processDetails.classList.contains('collapsed')) {
icon.setAttribute('data-lucide', 'chevron-right');
} else {
icon.setAttribute('data-lucide', 'chevron-down');
}
lucide.createIcons();
});
processDetails.appendChild(detailsHeader);
processDetails.appendChild(stepsList);
// 最终回复区域
const finalResponse = document.createElement('div');
finalResponse.className = 'final-response loading';
finalResponse.innerHTML = '<div class="typing-indicator"><span></span><span></span><span></span></div>';
messageBody.appendChild(processDetails);
messageBody.appendChild(finalResponse);
messageGroup.appendChild(avatar);
messageGroup.appendChild(messageBody);
this.elements.messagesContainer.appendChild(messageGroup);
this.activeProcessContainer = {
group: messageGroup,
processDetails: processDetails,
stepsList: stepsList,
detailsHeader: detailsHeader,
finalResponse: finalResponse,
stepCount: 0
};
lucide.createIcons();
this.scrollToBottom();
return this.activeProcessContainer;
},
/**
* 添加思考步骤到过程详情
*/
addThinkingStep(content) {
if (!this.activeProcessContainer) {
this.createAssistantMessageContainer();
}
const { stepsList, detailsHeader } = this.activeProcessContainer;
const step = document.createElement('div');
step.className = 'process-step thinking';
step.innerHTML = `
<div class="step-icon">
<i data-lucide="brain" class="icon-xs"></i>
</div>
<div class="step-content">${this.escapeHtml(content)}</div>
`;
stepsList.appendChild(step);
lucide.createIcons();
this.scrollToBottom();
// 更新状态
this.updateProcessStatus('thinking');
},
/**
* 添加工具调用步骤
*/
addToolCallStep(toolName, args, isTodoWrite = false) {
if (!this.activeProcessContainer) {
this.createAssistantMessageContainer();
}
const { stepsList } = this.activeProcessContainer;
const step = document.createElement('div');
step.className = `process-step tool-call${isTodoWrite ? ' todo-step' : ''}`;
let icon = 'wrench';
let title = `调用工具: ${toolName}`;
let details = '';
if (isTodoWrite) {
icon = 'clipboard-list';
title = '任务列表';
const todoList = this.renderTodoList(args);
if (todoList) {
details = '<div class="step-todo-list"></div>';
}
}
step.innerHTML = `
<div class="step-icon">
<i data-lucide="${icon}" class="icon-xs"></i>
</div>
<div class="step-content">
<div class="step-title">${title}</div>
${isTodoWrite ? '' : `<div class="step-args"><code>${this.escapeHtml(ChatUtils.formatJson(args))}</code></div>`}
${details}
</div>
`;
// 如果是 TodoWrite,渲染任务列表
if (isTodoWrite) {
const todoListContainer = step.querySelector('.step-todo-list');
const todoList = this.renderTodoList(args);
if (todoList && todoListContainer) {
todoListContainer.appendChild(todoList);
}
}
stepsList.appendChild(step);
lucide.createIcons();
this.scrollToBottom();
this.updateProcessStatus('calling-tool');
},
/**
* 添加工具响应步骤
*/
addToolResponseStep(toolName, response, isTodoWrite = false) {
if (!this.activeProcessContainer) return;
const { stepsList } = this.activeProcessContainer;
const step = document.createElement('div');
step.className = 'process-step tool-response';
if (isTodoWrite) {
// 更新任务列表为进度视图
step.className += ' todo-progress-step';
const todoProgress = this.createTodoProgressElement(response);
step.appendChild(todoProgress);
} else {
let displayResponse = typeof response === 'string' ? response : ChatUtils.formatJson(response);
displayResponse = this.truncateText(displayResponse, 200);
step.innerHTML = `
<div class="step-icon">
<i data-lucide="check-circle" class="icon-xs"></i>
</div>
<div class="step-content">
<div class="step-title">工具返回: ${toolName}</div>
<div class="step-result">${this.escapeHtml(displayResponse)}</div>
</div>
`;
}
stepsList.appendChild(step);
lucide.createIcons();
this.scrollToBottom();
this.updateProcessStatus('got-result');
},
/**
* 设置最终回复内容
*/
setFinalResponse(content) {
if (!this.activeProcessContainer) {
this.createAssistantMessageContainer();
}
const { finalResponse, detailsHeader } = this.activeProcessContainer;
finalResponse.className = 'final-response';
finalResponse.innerHTML = this.renderMarkdown(content);
this.addCodeCopyButtons(finalResponse);
// 更新头部状态为完成
const statusText = detailsHeader.querySelector('.status-text');
const statusContainer = detailsHeader.querySelector('.process-status');
if (statusText) statusText.textContent = '已完成';
// 替换图标为完成状态(兼容 SVG 和原始 i 标签)
if (statusContainer) {
// 清除现有图标内容,重新创建 check-circle 图标
const iconWrapper = document.createElement('span');
iconWrapper.innerHTML = '<i data-lucide="check-circle" class="icon-xs"></i>';
// 移除旧的图标元素(第一个子元素,通常是 SVG 或 i 标签)
const oldIcon = statusContainer.querySelector('svg, i');
if (oldIcon) oldIcon.remove();
// 在文本前插入新图标
statusContainer.insertBefore(iconWrapper.firstElementChild, statusText);
}
lucide.createIcons();
this.scrollToBottom();
// 重置活动容器
this.activeProcessContainer = null;
},
/**
* 更新过程状态
*/
updateProcessStatus(status) {
if (!this.activeProcessContainer) return;
const { detailsHeader } = this.activeProcessContainer;
const statusText = detailsHeader.querySelector('.status-text');
const statusMap = {
'thinking': '思考中...',
'calling-tool': '调用工具...',
'got-result': '处理结果...'
};
if (statusText && statusMap[status]) {
statusText.textContent = statusMap[status];
}
},
// ==================== 旧接口兼容 ====================
/**
* 渲染 AI 消息(兼容旧接口)
*/
renderAssistantMessage(content, options = {}) {
if (options.isLoading) {
this.createAssistantMessageContainer();
return this.activeProcessContainer.group;
}
// 对于已完成的历史消息,创建一个已完成状态的容器
this.createAssistantMessageContainer();
const { group, finalResponse, detailsHeader, processDetails } = this.activeProcessContainer;
// 设置回复内容
finalResponse.className = 'final-response';
finalResponse.innerHTML = this.renderMarkdown(content);
this.addCodeCopyButtons(finalResponse);
// 更新头部状态为已完成(用于历史消息)
const statusText = detailsHeader?.querySelector('.status-text');
const statusContainer = detailsHeader?.querySelector('.process-status');
if (statusText) statusText.textContent = '已完成';
if (statusContainer) {
const iconWrapper = document.createElement('span');
iconWrapper.innerHTML = '<i data-lucide="check-circle" class="icon-xs"></i>';
const oldIcon = statusContainer.querySelector('svg, i');
if (oldIcon) oldIcon.remove();
statusContainer.insertBefore(iconWrapper.firstElementChild, statusText);
}
// 默认折叠历史消息的过程详情
processDetails?.classList.add('collapsed');
const toggleIcon = detailsHeader?.querySelector('.process-toggle i');
if (toggleIcon) {
toggleIcon.setAttribute('data-lucide', 'chevron-right');
}
lucide.createIcons();
this.scrollToBottom();
// 重置活动容器
this.activeProcessContainer = null;
return group;
},
/**
* 渲染工具调用(兼容旧接口,转发到新方法)
*/
renderToolCall(name, args, options = {}) {
this.addToolCallStep(name, args, options.isTodoWrite);
},
/**
* 渲染工具响应(兼容旧接口,转发到新方法)
*/
renderToolResult(name, result, options = {}) {
this.addToolResponseStep(name, result, options.isTodoWrite);
},
// ==================== TodoWrite 渲染 ====================
/**
* 渲染 TodoWrite 任务列表
*/
renderTodoList(args) {
try {
const data = typeof args === 'string' ? JSON.parse(args) : args;
const todos = this.extractTodos(data);
if (!todos || todos.length === 0) return null;
const listDiv = document.createElement('div');
listDiv.className = 'todo-list-compact';
todos.forEach(todo => {
const item = document.createElement('div');
item.className = `todo-item-compact ${todo.status}`;
const icons = {
pending: '<i data-lucide="circle" class="icon-xs"></i>',
in_progress: '<i data-lucide="loader-2" class="icon-xs spinning"></i>',
completed: '<i data-lucide="check-circle" class="icon-xs"></i>'
};
item.innerHTML = `
<span class="todo-icon">${icons[todo.status] || icons.pending}</span>
<span class="todo-text">${this.escapeHtml(todo.content)}</span>
`;
listDiv.appendChild(item);
});
return listDiv;
} catch (e) {
console.error('渲染任务列表失败:', e);
return null;
}
},
/**
* 创建 TodoWrite 进度元素
*/
createTodoProgressElement(response) {
try {
const data = typeof response === 'string'
? this.extractJsonFromString(response)
: response;
const todos = this.extractTodos(data);
if (!todos || todos.length === 0) {
return document.createTextNode('任务更新');
}
const container = document.createElement('div');
container.className = 'step-todo-progress';
// 计算进度
const total = todos.length;
const completed = todos.filter(t => t.status === 'completed').length;
const inProgress = todos.filter(t => t.status === 'in_progress').length;
const percentage = Math.round((completed / total) * 100);
// 进度条
container.innerHTML = `
<div class="step-progress-bar">
<div class="step-progress-fill" style="width: ${percentage}%"></div>
</div>
<div class="step-progress-info">
<span>${completed}/${total} 完成</span>
<span>${percentage}%</span>
</div>
`;
// 任务列表(只显示进行中或未完成的)
const activeTodos = todos.filter(t => t.status !== 'completed');
if (activeTodos.length > 0) {
const listDiv = document.createElement('div');
listDiv.className = 'todo-list-compact';
activeTodos.slice(0, 3).forEach(todo => {
const item = document.createElement('div');
item.className = `todo-item-compact ${todo.status}`;
const icons = {
pending: '<i data-lucide="circle" class="icon-xs"></i>',
in_progress: '<i data-lucide="loader-2" class="icon-xs spinning"></i>',
completed: '<i data-lucide="check-circle" class="icon-xs"></i>'
};
item.innerHTML = `
<span class="todo-icon">${icons[todo.status] || icons.pending}</span>
<span class="todo-text">${this.escapeHtml(todo.content)}</span>
`;
listDiv.appendChild(item);
});
if (activeTodos.length > 3) {
const more = document.createElement('div');
more.className = 'todo-more';
more.textContent = `还有 ${activeTodos.length - 3} 个任务...`;
listDiv.appendChild(more);
}
container.appendChild(listDiv);
}
return container;
} catch (e) {
console.error('渲染任务进度失败:', e);
return document.createTextNode('任务更新');
}
},
/**
* 从数据中提取 todos
*/
extractTodos(data) {
if (!data) return null;
if (data.todos) {
if (data.todos.todos) return data.todos.todos;
if (Array.isArray(data.todos)) return data.todos;
}
return null;
},
/**
* 从字符串中提取 JSON
*/
extractJsonFromString(str) {
const match = str.match(/\{[\s\S]*"todos"[\s\S]*\}/);
if (match) {
return ChatUtils.safeJsonParse(match[0], {});
}
return {};
},
// ==================== 辅助功能 ====================
/**
* 隐藏欢迎消息
*/
hideWelcomeMessage() {
const welcomeMessage = this.elements.messagesContainer.querySelector('.welcome-message');
if (welcomeMessage) {
welcomeMessage.style.display = 'none';
}
},
/**
* 渲染 Markdown
*/
renderMarkdown(content) {
const html = marked.parse(content);
return DOMPurify.sanitize(html);
},
/**
* 添加代码复制按钮
*/
addCodeCopyButtons(container) {
container.querySelectorAll('pre code').forEach((block) => {
hljs.highlightElement(block);
const pre = block.parentElement;
if (pre.querySelector('.copy-button')) return;
// 确保 pre 有相对定位
pre.style.position = 'relative';
// 检测语言并设置 data-language
const language = block.className.match(/language-(\w+)/);
if (language) {
pre.setAttribute('data-language', language[1]);
}
const copyBtn = document.createElement('button');
copyBtn.className = 'copy-button';
copyBtn.innerHTML = '<i data-lucide="copy" class="icon-xs"></i>';
copyBtn.title = '复制';
copyBtn.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(block.textContent);
copyBtn.innerHTML = '<i data-lucide="check" class="icon-xs"></i>';
copyBtn.classList.add('copied');
lucide.createIcons();
setTimeout(() => {
copyBtn.innerHTML = '<i data-lucide="copy" class="icon-xs"></i>';
copyBtn.classList.remove('copied');
lucide.createIcons();
}, 2000);
} catch (err) {
copyBtn.innerHTML = '<i data-lucide="x" class="icon-xs"></i>';
lucide.createIcons();
}
});
pre.appendChild(copyBtn);
});
},
/**
* 显示错误消息
*/
showError(message, duration = 3000) {
const errorDiv = document.createElement('div');
errorDiv.className = 'error-message';
errorDiv.textContent = message;
this.elements.messagesContainer.appendChild(errorDiv);
this.scrollToBottom();
setTimeout(() => {
errorDiv.remove();
}, duration);
},
/**
* 更新连接状态
*/
updateConnectionStatus(connected) {
const status = this.elements.connectionStatus;
const statusText = status.querySelector('.status-text');
const statusDot = status.querySelector('.status-dot');
if (statusText && statusDot) {
if (connected) {
statusText.textContent = '处理中...';
statusDot.style.background = 'var(--accent)';
} else {
statusText.textContent = '已连接';
statusDot.style.background = 'var(--secondary)';
}
}
},
/**
* 清空消息区域
*/
clearMessages() {
this.activeProcessContainer = null;
this.elements.messagesContainer.innerHTML = `
<div class="welcome-message">
<div class="welcome-icon">
<i data-lucide="sparkles" class="icon-xl"></i>
</div>
<h2 class="welcome-title">有什么可以帮你的?</h2>
<p class="welcome-subtitle">我可以帮你执行定价流程、管理任务、查询数据等</p>
<div class="quick-actions">
<button class="quick-action-btn" data-prompt="请帮我为&quot;深圳某某科技有限公司&quot;执行完整的定价流程">
<i data-lucide="calculator" class="icon-sm"></i>
<span>执行定价流程</span>
</button>
<button class="quick-action-btn" data-prompt="分析最近3个月的定价数据,找出异常客户">
<i data-lucide="bar-chart-3" class="icon-sm"></i>
<span>数据分析</span>
</button>
<button class="quick-action-btn" data-prompt="获取&quot;测试企业&quot;的风险成本率">
<i data-lucide="search" class="icon-sm"></i>
<span>查询风险成本</span>
</button>
<button class="quick-action-btn" data-prompt="请解释历史行为定价法的适用场景">
<i data-lucide="book-open" class="icon-sm"></i>
<span>定价方法说明</span>
</button>
</div>
</div>
`;
this.bindSidebarEvents();
lucide.createIcons();
},
/**
* 处理新对话
*/
async handleNewChat() {
// 通过 API 创建新会话
try {
const conversation = await ChatAPI.createConversation('新对话');
this.activeProcessContainer = null;
this.clearMessages();
this.loadConversationList(); // 刷新列表
if (this.elements.sidebar) {
this.elements.sidebar.classList.remove('open');
}
} catch (error) {
console.error('创建新会话失败:', error);
// 降级到本地生成
const newId = ChatUtils.regenerateConversationId();
ChatAPI.setConversationId(newId);
this.activeProcessContainer = null;
this.clearMessages();
}
},
// ==================== 会话列表管理 ====================
/**
* 渲染会话列表
*/
renderConversationList(conversations, currentId) {
const navList = document.getElementById('conversation-list');
if (!navList) return;
if (conversations.length === 0) {
navList.innerHTML = '<li class="nav-item-empty">暂无历史对话</li>';
return;
}
navList.innerHTML = conversations.map(conv => {
const isActive = conv.id === currentId;
const date = this.formatDate(conv.updatedAt);
return `
<li class="nav-item ${isActive ? 'active' : ''}" data-conversation-id="${conv.id}">
<i data-lucide="message-square" class="icon-sm"></i>
<span class="nav-item-text" title="${this.escapeHtml(conv.title)}">
${this.escapeHtml(conv.title)}
</span>
<button class="btn-delete-conv" title="删除">
<i data-lucide="x" class="icon-xs"></i>
</button>
</li>
`;
}).join('');
// 绑定点击事件
navList.querySelectorAll('.nav-item').forEach(item => {
item.addEventListener('click', (e) => {
// 如果点击的是删除按钮,不触发切换
if (e.target.closest('.btn-delete-conv')) return;
const convId = item.dataset.conversationId;
this.switchToConversation(convId);
});
});
// 绑定删除事件
navList.querySelectorAll('.btn-delete-conv').forEach(btn => {
btn.addEventListener('click', async (e) => {
e.stopPropagation();
const item = btn.closest('.nav-item');
const convId = item.dataset.conversationId;
await this.deleteConversation(convId);
});
});
lucide.createIcons();
},
/**
* 加载会话列表
*/
async loadConversationList() {
try {
const conversations = await ChatAPI.listConversations();
this.renderConversationList(conversations, ChatAPI.conversationId);
} catch (error) {
console.error('加载会话列表失败:', error);
}
},
/**
* 切换到指定会话
*/
async switchToConversation(conversationId) {
try {
// 获取会话消息
const messages = await ChatAPI.getMessages(conversationId);
// 更新当前会话 ID
ChatAPI.setConversationId(conversationId);
// 清空并重新渲染消息
this.activeProcessContainer = null;
this.elements.messagesContainer.innerHTML = '';
// 渲染历史消息
messages.forEach(msg => {
if (msg.role === 'user') {
this.renderUserMessage(msg.content);
} else if (msg.role === 'assistant') {
this.renderAssistantMessage(msg.content);
}
});
// 如果没有消息,显示欢迎界面
if (messages.length === 0) {
this.clearMessages();
}
// 刷新会话列表(更新选中状态)
await this.loadConversationList();
// 关闭移动端侧边栏
if (this.elements.sidebar) {
this.elements.sidebar.classList.remove('open');
}
// 滚动到底部
this.scrollToBottom();
} catch (error) {
console.error('切换会话失败:', error);
this.showError('加载会话失败');
}
},
/**
* 删除会话
*/
async deleteConversation(conversationId) {
if (!confirm('确定要删除这个会话吗?')) return;
try {
await ChatAPI.deleteConversation(conversationId);
// 重新加载会话列表
const conversations = await ChatAPI.listConversations();
// 如果删除的是当前会话
if (conversationId === ChatAPI.conversationId) {
// 如果还有其他会话,切换到最近的会话
if (conversations.length > 0) {
const newestConv = conversations[0]; // 列表已按更新时间排序
await this.switchToConversation(newestConv.id);
} else {
// 没有任何会话了,创建新会话
await this.handleNewChat();
}
} else {
// 删除的不是当前会话,只刷新列表
this.renderConversationList(conversations, ChatAPI.conversationId);
}
} catch (error) {
console.error('删除会话失败:', error);
this.showError('删除会话失败');
}
},
/**
* 格式化日期
*/
formatDate(dateString) {
if (!dateString) return '';
const date = new Date(dateString);
const now = new Date();
const diff = now - date;
// 小于 1 分钟
if (diff < 60000) return '刚刚';
// 小于 1 小时
if (diff < 3600000) return `${Math.floor(diff / 60000)} 分钟前`;
// 小于 24 小时
if (diff < 86400000) return `${Math.floor(diff / 3600000)} 小时前`;
// 小于 7 天
if (diff < 604800000) return `${Math.floor(diff / 86400000)} 天前`;
// 显示具体日期
return date.toLocaleDateString('zh-CN', {
month: 'short',
day: 'numeric'
});
},
/**
* 滚动到底部
*/
scrollToBottom() {
const container = this.elements.messagesContainer;
container.scrollTop = container.scrollHeight;
},
/**
* 设置输入框状态
*/
setInputState(options) {
const { disabled = false, value = null } = options;
const input = this.elements.userInput;
const btn = this.elements.sendBtn;
if (value !== null) {
input.value = value;
input.style.height = 'auto';
}
input.disabled = disabled;
btn.disabled = disabled || !input.value.trim();
},
/**
* 自动调整输入框高度
*/
autoResizeInput() {
const input = this.elements.userInput;
input.style.height = 'auto';
input.style.height = Math.min(input.scrollHeight, 150) + 'px';
},
/**
* 获取工具开关状态
*/
isToolEnabled() {
return this.elements.toolToggle.checked;
},
/**
* HTML 转义
*/
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
},
/**
* 截断文本
*/
truncateText(text, maxLength) {
if (!text || text.length <= maxLength) return text;
return text.substring(0, maxLength) + '...';
}
};
// 导出模块
window.ChatUI = ChatUI;