You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
2.2 KiB
JavaScript
72 lines
2.2 KiB
JavaScript
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) => {
|
|
e.preventDefault();
|
|
const text = userInput.value.trim();
|
|
if (!text) return;
|
|
|
|
vscode.postMessage({
|
|
command: 'ask',
|
|
text,
|
|
fileContent: selectedCodeForContext
|
|
});
|
|
|
|
// addMessage('user', text);
|
|
showLoading();
|
|
|
|
userInput.value = '';
|
|
});
|
|
|
|
function addMessage(role, content) {
|
|
const chatBox = document.getElementById('chat-box');
|
|
const msgDiv = document.createElement('div');
|
|
msgDiv.className = `message ${role}`;
|
|
|
|
if (content.includes('```')) {
|
|
const codeContent = content.slice(3, -3).trim();
|
|
msgDiv.innerHTML = `<pre><code>${codeContent}</code></pre>`;
|
|
} else {
|
|
msgDiv.textContent = content;
|
|
}
|
|
|
|
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(); // 自动聚焦输入框
|
|
}
|
|
|
|
});
|
|
}); |