|
|
let selectedCodeForContext = '';
|
|
|
const vscode = acquireVsCodeApi();
|
|
|
|
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
|
const chatForm = document.getElementById('chat-form');
|
|
|
const userInput = document.getElementById('user-input');
|
|
|
const chatBox = document.getElementById('chat-box');
|
|
|
const loading = document.getElementById('loading');
|
|
|
|
|
|
chatForm.addEventListener('submit', (e) => {
|
|
|
console.log(1111)
|
|
|
e.preventDefault();
|
|
|
const text = userInput.value.trim();
|
|
|
if (!text) return;
|
|
|
|
|
|
vscode.postMessage({
|
|
|
command: 'ask',
|
|
|
text,
|
|
|
fileContent: selectedCodeForContext
|
|
|
});
|
|
|
|
|
|
// addMessage('user', text);
|
|
|
showLoading();
|
|
|
|
|
|
userInput.value = '';
|
|
|
});
|
|
|
|
|
|
// 判断内容是否为 Markdown(简单判断)
|
|
|
function isMarkdown(content) {
|
|
|
if (!content || content.trim() === '') return false;
|
|
|
|
|
|
const markdownPatterns = [
|
|
|
/^#/m, // 标题 #
|
|
|
/\*\*[^*]+\*\*/g, // 加粗 **text**
|
|
|
/__[^_]+__/g, // 加粗 __text__
|
|
|
/^- /gm, // 无序列表
|
|
|
/^\* /gm, // 无序列表
|
|
|
/^\d+\. /gm, // 有序列表
|
|
|
/```/g // 代码块
|
|
|
];
|
|
|
|
|
|
return markdownPatterns.some(pattern => pattern.test(content));
|
|
|
}
|
|
|
|
|
|
function addMessage(role, content) {
|
|
|
const msgDiv = document.createElement('div');
|
|
|
msgDiv.className = `message ${role}`;
|
|
|
|
|
|
// 渲染内容
|
|
|
if (isMarkdown(content)) {
|
|
|
console.log("content:",content)
|
|
|
msgDiv.innerHTML = marked.parse(content);
|
|
|
console.log("msgDiv.innerHTML:",msgDiv.innerHTML )
|
|
|
} else {
|
|
|
const div = document.createElement('div');
|
|
|
div.textContent = content;
|
|
|
msgDiv.appendChild(div);
|
|
|
}
|
|
|
|
|
|
chatBox.appendChild(msgDiv);
|
|
|
|
|
|
// 高亮代码块
|
|
|
const codeBlocks = msgDiv.querySelectorAll('pre code');
|
|
|
codeBlocks.forEach(block => {
|
|
|
hljs.highlightElement(block);
|
|
|
});
|
|
|
|
|
|
// 滚动到底部
|
|
|
chatBox.scrollTop = chatBox.scrollHeight;
|
|
|
}
|
|
|
|
|
|
function showLoading() {
|
|
|
loading.classList.remove('hidden');
|
|
|
}
|
|
|
|
|
|
function hideLoading() {
|
|
|
loading.classList.add('hidden');
|
|
|
}
|
|
|
|
|
|
window.addEventListener('message', (event) => {
|
|
|
const message = event.data;
|
|
|
console.log(message)
|
|
|
if (message.command === 'addMessage') {
|
|
|
addMessage(message.role, message.content);
|
|
|
} else if (message.command === 'hideLoading') {
|
|
|
hideLoading();
|
|
|
} else if (message.command === 'addToInput') {
|
|
|
userInput.value = message.content; // 插入选中内容到输入框
|
|
|
selectedCodeForContext = message.content;
|
|
|
userInput.focus(); // 自动聚焦输入框
|
|
|
}
|
|
|
|
|
|
});
|
|
|
}); |