// main.js import { createPanel } from './scripts/panel.js'; import { handleCommand, COMMANDS } from './scripts/commands.js'; import { initVoice } from './scripts/voice.js'; import { translateToCommand } from './scripts/ai.js'; const init = async () => { const ui = createPanel(); let spaceTimer = null; let isRecording = false; // 统一定义 UI 更新引用,方便 handleCommand 调用 const uiRefs = { updateStatus: (text) => { const statusText = document.getElementById("statusText"); if (statusText) { statusText.innerText = text; statusText.style.color = "#409eff"; // 使用蓝色区分对话与就绪状态 } } }; /** * 处理 AI 流程的主函数 */ async function startProcess(text) { if (!text) return; ui.setLoading(true); try { // 获取 AI 响应结果(包含内容和语音开关状态) const aiResponse = await translateToCommand(text); if (aiResponse && aiResponse.content) { // 将内容、UI 引用以及语音开关状态传给指令处理器 handleCommand(aiResponse.content, uiRefs, aiResponse.voiceEnabled); } else { uiRefs.updateStatus("未识别到有效指令"); } } catch (err) { console.error("处理流程错误:", err); uiRefs.updateStatus("处理指令时出错"); } finally { ui.setLoading(false); } } // 初始化语音识别模块 const voiceCtrl = initVoice(ui, (text) => { ui.setRecording(false); isRecording = false; ui.input.value = text; startProcess(text); }); // 输入框回车触发 ui.input.addEventListener("keydown", (e) => { if (e.key === "Enter") { const text = ui.input.value.trim(); ui.input.value = ""; startProcess(text); } }); // 按钮点击触发录音 ui.btn.onclick = () => { if (!isRecording) { voiceCtrl.start(); ui.setRecording(true); isRecording = true; // 4秒自动停止录音保护 setTimeout(() => { if (isRecording) { voiceCtrl.stop(); ui.setRecording(false); isRecording = false; } }, 4000); } else { voiceCtrl.stop(); ui.setRecording(false); isRecording = false; } }; // 空格长按触发录音逻辑 window.addEventListener("keydown", (e) => { if (e.code === "Space" && e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA") { if (spaceTimer || isRecording) return; spaceTimer = setTimeout(() => { if (voiceCtrl.supportSpeech) { voiceCtrl.start(); ui.setRecording(true); isRecording = true; } }, 500); // 判定为长按 } }); window.addEventListener("keyup", (e) => { if (e.code === "Space") { if (spaceTimer) { clearTimeout(spaceTimer); spaceTimer = null; } if (isRecording) { // 延迟停止以捕捉最后一段语音 setTimeout(() => { voiceCtrl.stop(); ui.setRecording(false); isRecording = false; }, 300); } } }); }; // 启动初始化 if (document.readyState === "complete" || document.readyState === "interactive") { init(); } else { window.addEventListener("DOMContentLoaded", init); }