442 lines
13 KiB
JavaScript
442 lines
13 KiB
JavaScript
/**
|
|||
|
|
* UI 渲染模块
|
||
|
|
* 负责所有 DOM 操作和 UI 组件渲染
|
||
|
|
*/
|
||
|
|
|
||
|
|
const ChatUI = {
|
||
|
|
// DOM 元素缓存
|
||
|
|
elements: {},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 初始化 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')
|
||
|
|
};
|
||
|
|
|
||
|
|
// 初始化 marked.js 配置
|
||
|
|
this.initMarked();
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 获取 DOM 元素
|
||
|
|
*/
|
||
|
|
get(id) {
|
||
|
|
return this.elements[id] || document.getElementById(id);
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 初始化 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) {
|
||
|
|
const messageDiv = document.createElement('div');
|
||
|
|
messageDiv.className = 'message user animate-in';
|
||
|
|
|
||
|
|
const contentDiv = document.createElement('div');
|
||
|
|
contentDiv.className = 'message-content';
|
||
|
|
contentDiv.textContent = content;
|
||
|
|
|
||
|
|
messageDiv.appendChild(contentDiv);
|
||
|
|
this.elements.messagesContainer.appendChild(messageDiv);
|
||
|
|
this.scrollToBottom();
|
||
|
|
|
||
|
|
return messageDiv;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 渲染 AI 消息
|
||
|
|
*/
|
||
|
|
renderAssistantMessage(content, options = {}) {
|
||
|
|
const messageDiv = document.createElement('div');
|
||
|
|
messageDiv.className = `message assistant animate-in ${options.isLoading ? 'loading' : ''}`;
|
||
|
|
|
||
|
|
const contentDiv = document.createElement('div');
|
||
|
|
contentDiv.className = 'message-content';
|
||
|
|
|
||
|
|
if (options.isLoading) {
|
||
|
|
contentDiv.innerHTML = this.getTypingIndicator();
|
||
|
|
} else {
|
||
|
|
contentDiv.innerHTML = this.renderMarkdown(content);
|
||
|
|
this.addCodeCopyButtons(contentDiv);
|
||
|
|
}
|
||
|
|
|
||
|
|
messageDiv.appendChild(contentDiv);
|
||
|
|
this.elements.messagesContainer.appendChild(messageDiv);
|
||
|
|
this.scrollToBottom();
|
||
|
|
|
||
|
|
return messageDiv;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 更新消息内容
|
||
|
|
*/
|
||
|
|
updateMessage(messageElement, content) {
|
||
|
|
const contentDiv = messageElement.querySelector('.message-content');
|
||
|
|
contentDiv.innerHTML = this.renderMarkdown(content);
|
||
|
|
this.addCodeCopyButtons(contentDiv);
|
||
|
|
this.scrollToBottom();
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 获取打字指示器 HTML
|
||
|
|
*/
|
||
|
|
getTypingIndicator() {
|
||
|
|
return '<div class="typing-indicator"><span></span><span></span><span></span></div>';
|
||
|
|
},
|
||
|
|
|
||
|
|
// ==================== 工具调用渲染 ====================
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 渲染工具调用
|
||
|
|
*/
|
||
|
|
renderToolCall(name, args, options = {}) {
|
||
|
|
const { isTodoWrite = false } = options;
|
||
|
|
const div = document.createElement('div');
|
||
|
|
div.className = isTodoWrite ? 'todo-write-call animate-in' : 'tool-call animate-in';
|
||
|
|
|
||
|
|
const header = document.createElement('div');
|
||
|
|
header.className = isTodoWrite ? 'todo-write-header' : 'tool-call-header';
|
||
|
|
header.innerHTML = isTodoWrite
|
||
|
|
? '📋 任务列表'
|
||
|
|
: `⚙️ 调用工具: ${name}`;
|
||
|
|
|
||
|
|
div.appendChild(header);
|
||
|
|
|
||
|
|
// 如果是 TodoWrite,渲染任务列表
|
||
|
|
if (isTodoWrite) {
|
||
|
|
const todoList = this.renderTodoList(args);
|
||
|
|
if (todoList) {
|
||
|
|
div.appendChild(todoList);
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
// 普通工具调用,渲染参数
|
||
|
|
const details = document.createElement('div');
|
||
|
|
details.className = 'tool-call-details';
|
||
|
|
details.textContent = '参数: ' + ChatUtils.formatJson(args);
|
||
|
|
div.appendChild(details);
|
||
|
|
}
|
||
|
|
|
||
|
|
this.elements.messagesContainer.appendChild(div);
|
||
|
|
this.scrollToBottom();
|
||
|
|
|
||
|
|
return div;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 渲染工具响应
|
||
|
|
*/
|
||
|
|
renderToolResult(name, result, options = {}) {
|
||
|
|
const { isTodoWrite = false } = options;
|
||
|
|
|
||
|
|
if (isTodoWrite) {
|
||
|
|
return this.renderTodoProgress(result);
|
||
|
|
}
|
||
|
|
|
||
|
|
const div = document.createElement('div');
|
||
|
|
div.className = 'tool-result animate-in';
|
||
|
|
|
||
|
|
const header = document.createElement('div');
|
||
|
|
header.className = 'tool-result-header';
|
||
|
|
header.innerHTML = `📄 工具返回: ${name}`;
|
||
|
|
|
||
|
|
const content = document.createElement('div');
|
||
|
|
content.className = 'tool-result-content';
|
||
|
|
content.textContent = typeof result === 'string' ? result : ChatUtils.formatJson(result);
|
||
|
|
|
||
|
|
div.appendChild(header);
|
||
|
|
div.appendChild(content);
|
||
|
|
this.elements.messagesContainer.appendChild(div);
|
||
|
|
this.scrollToBottom();
|
||
|
|
|
||
|
|
return div;
|
||
|
|
},
|
||
|
|
|
||
|
|
// ==================== 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';
|
||
|
|
|
||
|
|
todos.forEach(todo => {
|
||
|
|
const item = this.createTodoItem(todo);
|
||
|
|
listDiv.appendChild(item);
|
||
|
|
});
|
||
|
|
|
||
|
|
return listDiv;
|
||
|
|
} catch (e) {
|
||
|
|
console.error('渲染任务列表失败:', e);
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 渲染 TodoWrite 进度
|
||
|
|
*/
|
||
|
|
renderTodoProgress(response) {
|
||
|
|
try {
|
||
|
|
const data = typeof response === 'string'
|
||
|
|
? this.extractJsonFromString(response)
|
||
|
|
: response;
|
||
|
|
|
||
|
|
const todos = this.extractTodos(data);
|
||
|
|
if (!todos || todos.length === 0) {
|
||
|
|
return this.renderToolResult('TodoWrite', response);
|
||
|
|
}
|
||
|
|
|
||
|
|
const div = document.createElement('div');
|
||
|
|
div.className = 'todo-write-progress animate-in';
|
||
|
|
|
||
|
|
// 计算进度
|
||
|
|
const total = todos.length;
|
||
|
|
const completed = todos.filter(t => t.status === 'completed').length;
|
||
|
|
const percentage = Math.round((completed / total) * 100);
|
||
|
|
|
||
|
|
// 进度头部
|
||
|
|
const header = document.createElement('div');
|
||
|
|
header.className = 'todo-progress-header';
|
||
|
|
header.innerHTML = `📊 任务进度: ${completed}/${total} (${percentage}%)`;
|
||
|
|
|
||
|
|
// 进度条
|
||
|
|
const progressBar = this.createProgressBar(percentage);
|
||
|
|
|
||
|
|
// 任务列表
|
||
|
|
const listDiv = document.createElement('div');
|
||
|
|
listDiv.className = 'todo-list';
|
||
|
|
todos.forEach(todo => {
|
||
|
|
listDiv.appendChild(this.createTodoItem(todo));
|
||
|
|
});
|
||
|
|
|
||
|
|
div.appendChild(header);
|
||
|
|
div.appendChild(progressBar);
|
||
|
|
div.appendChild(listDiv);
|
||
|
|
|
||
|
|
this.elements.messagesContainer.appendChild(div);
|
||
|
|
this.scrollToBottom();
|
||
|
|
|
||
|
|
return div;
|
||
|
|
} catch (e) {
|
||
|
|
console.error('渲染任务进度失败:', e);
|
||
|
|
return this.renderToolResult('TodoWrite', response);
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 创建任务项
|
||
|
|
*/
|
||
|
|
createTodoItem(todo) {
|
||
|
|
const item = document.createElement('div');
|
||
|
|
item.className = `todo-item todo-${todo.status}`;
|
||
|
|
|
||
|
|
const icons = {
|
||
|
|
pending: '[ ]',
|
||
|
|
in_progress: '[→]',
|
||
|
|
completed: '[✓]'
|
||
|
|
};
|
||
|
|
|
||
|
|
item.innerHTML = `
|
||
|
|
<span class="todo-status">${icons[todo.status] || '[ ]'}</span>
|
||
|
|
<span class="todo-content">${todo.content}</span>
|
||
|
|
`;
|
||
|
|
|
||
|
|
return item;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 创建进度条
|
||
|
|
*/
|
||
|
|
createProgressBar(percentage) {
|
||
|
|
const container = document.createElement('div');
|
||
|
|
container.className = 'progress-bar-container';
|
||
|
|
|
||
|
|
const bar = document.createElement('div');
|
||
|
|
bar.className = 'progress-bar';
|
||
|
|
bar.style.width = `${percentage}%`;
|
||
|
|
|
||
|
|
container.appendChild(bar);
|
||
|
|
return container;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 从数据中提取 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 {};
|
||
|
|
},
|
||
|
|
|
||
|
|
// ==================== 辅助功能 ====================
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 渲染 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;
|
||
|
|
const copyBtn = document.createElement('button');
|
||
|
|
copyBtn.className = 'copy-button';
|
||
|
|
copyBtn.textContent = '复制';
|
||
|
|
|
||
|
|
copyBtn.addEventListener('click', async () => {
|
||
|
|
try {
|
||
|
|
await navigator.clipboard.writeText(block.textContent);
|
||
|
|
copyBtn.textContent = '已复制!';
|
||
|
|
copyBtn.classList.add('copied');
|
||
|
|
setTimeout(() => {
|
||
|
|
copyBtn.textContent = '复制';
|
||
|
|
copyBtn.classList.remove('copied');
|
||
|
|
}, 2000);
|
||
|
|
} catch (err) {
|
||
|
|
copyBtn.textContent = '复制失败';
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
pre.style.position = 'relative';
|
||
|
|
pre.appendChild(copyBtn);
|
||
|
|
});
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 显示错误消息
|
||
|
|
*/
|
||
|
|
showError(message, duration = 3000) {
|
||
|
|
const errorDiv = document.createElement('div');
|
||
|
|
errorDiv.className = 'error-message animate-in';
|
||
|
|
errorDiv.textContent = '❌ ' + message;
|
||
|
|
|
||
|
|
this.elements.messagesContainer.appendChild(errorDiv);
|
||
|
|
this.scrollToBottom();
|
||
|
|
|
||
|
|
setTimeout(() => {
|
||
|
|
errorDiv.classList.add('animate-out');
|
||
|
|
setTimeout(() => errorDiv.remove(), 300);
|
||
|
|
}, duration);
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 更新连接状态
|
||
|
|
*/
|
||
|
|
updateConnectionStatus(connected) {
|
||
|
|
const status = this.elements.connectionStatus;
|
||
|
|
if (connected) {
|
||
|
|
status.textContent = '已连接';
|
||
|
|
status.className = 'status-indicator connected';
|
||
|
|
} else {
|
||
|
|
status.textContent = '未连接';
|
||
|
|
status.className = 'status-indicator disconnected';
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 清空消息区域
|
||
|
|
*/
|
||
|
|
clearMessages() {
|
||
|
|
this.elements.messagesContainer.innerHTML = '';
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 滚动到底部
|
||
|
|
*/
|
||
|
|
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;
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
// 导出模块
|
||
|
|
window.ChatUI = ChatUI;
|