feat(P4): 前端 Monaco 编辑器(CDN,5s 超时回退 CodeMirror)+ LSP 集成(诊断波浪线 debounce/补全/hover/语言切换 java/python/cpp)+ ED 编辑器抽象

这个提交包含在:
langxm
2026-10-14 03:25:03 +08:00
父节点 1668b2a645
当前提交 3e7639ff76
+118 -14
查看文件
@@ -227,7 +227,9 @@ body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14
<div class="editor-status"> <div class="editor-status">
<span id="stMorph">当前形态:对话</span> <span id="stMorph">当前形态:对话</span>
<span id="stLang">Java</span> <span>语言:<select id="codeLang" style="border:1px solid var(--line);border-radius:6px;padding:2px 6px;font-size:12px;font-family:inherit;background:#fff" onchange="onLangChange()">
<option value="java" selected>Java</option><option value="python">Python</option><option value="cpp">C++</option>
</select></span>
<span id="stMode" style="color:var(--blue)">学习模式</span> <span id="stMode" style="color:var(--blue)">学习模式</span>
<span style="flex:1"></span> <span style="flex:1"></span>
<span id="stSaved" class="badge green">代码自动保留 ✓</span> <span id="stSaved" class="badge green">代码自动保留 ✓</span>
@@ -244,6 +246,7 @@ body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14
<div class="sheet-body" id="sheetBody">加载中…</div> <div class="sheet-body" id="sheetBody">加载中…</div>
</div> </div>
<script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs/loader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/clike/clike.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/clike/clike.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/python/python.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/python/python.min.js"></script>
@@ -275,7 +278,8 @@ var SUBMISSIONS=[]; // 多版本代码
/* ---- 真实后端配置:本地联调 127.0.0.1:18100;部署同域自动为空 ---- */ /* ---- 真实后端配置:本地联调 127.0.0.1:18100;部署同域自动为空 ---- */
var API_BASE = (location.hostname==='127.0.0.1'||location.hostname==='localhost'||location.protocol==='file:') ? 'http://127.0.0.1:18100' : ''; var API_BASE = (location.hostname==='127.0.0.1'||location.hostname==='localhost'||location.protocol==='file:') ? 'http://127.0.0.1:18100' : '';
var UID='guest', LAST_RID=null, CUR_PROBLEM=null; var UID='guest', LAST_RID=null, CUR_PROBLEM=null;
var CM=null; var CM=null, ED=null, ED_IS_MONACO=false, CUR_LANG='java';
var MONACO_BOOTED=false, MONACO_LIB=null;
var PROBLEM={hydro_pid:'1021', title:'makes10(热身 106)'}; var PROBLEM={hydro_pid:'1021', title:'makes10(热身 106)'};
/* ================= 初始化 ================= */ /* ================= 初始化 ================= */
@@ -297,12 +301,7 @@ function init(){
if(d&&d.is_admin){ var t=document.getElementById('teacherEntry'); if(t) t.style.display='inline'; } if(d&&d.is_admin){ var t=document.getElementById('teacherEntry'); if(t) t.style.display='inline'; }
}).catch(function(){}); }).catch(function(){});
} }
CM = CodeMirror(document.getElementById('cmWrap'), { initEditor();
mode:'text/x-java', theme:'default', lineNumbers:true, indentUnit:2, tabSize:2,
value: defaultCode(),
extraKeys:{'Cmd-Enter':()=>doAction(), 'Ctrl-Enter':()=>doAction()}
});
CM.on('change', function(){ setMorph('code'); document.getElementById('stSaved').textContent='代码自动保留 ✓'; });
// 对话形态输入监听:自动识别代码/LaTeX // 对话形态输入监听:自动识别代码/LaTeX
document.getElementById('dialogArea').addEventListener('input', function(e){ document.getElementById('dialogArea').addEventListener('input', function(e){
var v=e.target.value; var v=e.target.value;
@@ -320,6 +319,111 @@ function init(){
loadLatexChips(); // LaTeX 常用公式合集(按学科) loadLatexChips(); // LaTeX 常用公式合集(按学科)
latexLive(); // 预览区默认示例 latexLive(); // 预览区默认示例
} }
/* ================= 编辑器:Monaco(CDN)优先,CodeMirror 回退 ================= */
function initEditor(){
if(window.require && document.getElementById('cmWrap')){
try{
window.require.config({paths:{vs:'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs'}});
var t=setTimeout(function(){ if(!MONACO_BOOTED) bootCodeMirror(); },6000);
window.require(['vs/editor/editor.main'], function(){
MONACO_BOOTED=true; clearTimeout(t);
try{ bootMonaco(); }catch(e){ bootCodeMirror(); }
}, function(){ clearTimeout(t); bootCodeMirror(); });
}catch(e){ bootCodeMirror(); }
} else bootCodeMirror();
}
function bootCodeMirror(){
CM = CodeMirror(document.getElementById('cmWrap'), {
mode:'text/x-java', theme:'default', lineNumbers:true, indentUnit:2, tabSize:2,
value: defaultCode(),
extraKeys:{'Cmd-Enter':()=>doAction(), 'Ctrl-Enter':()=>doAction()}
});
CM.on('change', function(){ setMorph('code'); document.getElementById('stSaved').textContent='代码自动保留 ✓'; lspCheck(); });
ED = {
setValue:function(v){ CM.setValue(v); },
getValue:function(){ return CM.getValue(); },
setCursor:function(p){ CM.setCursor(p); },
getLine:function(i){ return CM.getLine(i); },
lineCount:function(){ return CM.lineCount(); },
focus:function(){ CM.focus(); },
setLang:function(l){ try{ CM.setOption('mode', l==='python'?'text/x-python':(l==='cpp'?'text/x-c++src':'text/x-java')); }catch(e){} }
};
ED_IS_MONACO=false;
}
function bootMonaco(){
MONACO_LIB = window.monaco;
var ed = MONACO_LIB.editor.create(document.getElementById('cmWrap'), {
value: defaultCode(), language: 'java', automaticLayout:true,
fontSize:13.5, minimap:{enabled:false}, scrollBeyondLastLine:false,
tabSize:2, suggestOnTriggerCharacters:true, quickSuggestions:true,
fixedOverflowWidgets:true
});
ed.addCommand(MONACO_LIB.KeyMod.CmdCmd|MONACO_LIB.KeyCode.Enter, function(){ doAction(); });
ed.addCommand(MONACO_LIB.KeyMod.CtrlCmd|MONACO_LIB.KeyCode.Enter, function(){ doAction(); });
ed.onDidChangeModelContent(function(){ setMorph('code'); document.getElementById('stSaved').textContent='代码自动保留 ✓'; lspCheck(); });
ED = {
setValue:function(v){ ed.setValue(v); },
getValue:function(){ return ed.getValue(); },
setCursor:function(p){ ed.setPosition({lineNumber:p.line+1, column:p.ch+1}); ed.revealLine(p.line+1); },
getLine:function(i){ return ed.getModel().getLineContent(i+1); },
lineCount:function(){ return ed.getModel().getLineCount(); },
focus:function(){ ed.focus(); },
setLang:function(l){ MONACO_LIB.editor.setModelLanguage(ed.getModel(), l); }
};
ED_IS_MONACO=true;
registerLsp(ed);
}
function onLangChange(){
CUR_LANG=document.getElementById('codeLang').value;
if(ED){ ED.setLang(CUR_LANG); ED.setValue(ED.getValue()); lspCheck(); }
}
/* ================= LSP 集成:诊断(报错波浪线)/补全/hover ================= */
var lspTimer=null, lspSeq=0;
function lspCheck(){
if(!ED || !ED_IS_MONACO) return; // 仅 Monaco 支持 LSP markers/补全;CM 回退只保留本地预检
clearTimeout(lspTimer);
lspTimer=setTimeout(function(){
var code=ED.getValue(); if(!code || !code.trim()) return;
var seq=++lspSeq;
fetch(API_BASE+'/api/lsp/diagnostics',{method:'POST',headers:authHeaders({'Content-Type':'application/json'}),body:JSON.stringify({lang:CUR_LANG,code:code})})
.then(function(r){ return r.json(); }).then(function(d){
if(seq!==lspSeq) return; if(!d.ok) return;
var markers=(d.diagnostics||[]).map(function(x){
var sev = x.severity===1?MONACO_LIB.MarkerSeverity.Error : x.severity===2?MONACO_LIB.MarkerSeverity.Warning : x.severity===3?MONACO_LIB.MarkerSeverity.Info : MONACO_LIB.MarkerSeverity.Hint;
return {severity:sev, message:x.message,
startLineNumber:x.range.start.line+1, startColumn:x.range.start.character+1,
endLineNumber:x.range.end.line+1, endColumn:x.range.end.character+1};
});
MONACO_LIB.editor.setModelMarkers(ED.__ed.getModel(),'fluent-lsp',markers);
}).catch(function(){});
},800);
}
function registerLsp(ed){
ED.__ed=ed;
var langs=['java','python','cpp'];
MONACO_LIB.languages.registerCompletionItemProvider(langs, {
triggerCharacters:['.','(',','],
provideCompletionItems:function(model,pos){
return fetch(API_BASE+'/api/lsp/complete',{method:'POST',headers:authHeaders({'Content-Type':'application/json'}),body:JSON.stringify({lang:CUR_LANG,code:model.getValue(),line:pos.lineNumber-1,character:pos.column-1})})
.then(function(r){ return r.json(); }).then(function(d){
if(!d.ok||!d.items) return {suggestions:[]};
return {suggestions:d.items.map(function(it){
return {label:it.label, kind:MONACO_LIB.languages.CompletionItemKind[it.kind]||MONACO_LIB.languages.CompletionItemKind.Text,
insertText:it.insertText||it.label, detail:it.detail||'', sortText:it.sortText||it.label};
})};
}).catch(function(){ return {suggestions:[]}; });
}
});
MONACO_LIB.languages.registerHoverProvider(langs, {
provideHover:function(model,pos){
return fetch(API_BASE+'/api/lsp/hover',{method:'POST',headers:authHeaders({'Content-Type':'application/json'}),body:JSON.stringify({lang:CUR_LANG,code:model.getValue(),line:pos.lineNumber-1,character:pos.column-1})})
.then(function(r){ return r.json(); }).then(function(d){
if(!d.ok||!d.text) return null;
return {contents:[{value:d.text}]};
}).catch(function(){ return null; });
}
});
}
function defaultCode(){ function defaultCode(){
return "public boolean makes10(int a, int b) {\n // 若 a 或 b 等于 10,或 a+b 等于 10,返回 true;否则返回 false\n return false;\n}\n"; return "public boolean makes10(int a, int b) {\n // 若 a 或 b 等于 10,或 a+b 等于 10,返回 true;否则返回 false\n return false;\n}\n";
} }
@@ -357,7 +461,7 @@ function setMorph(m){
var ta=document.getElementById('dialogArea'); var ta=document.getElementById('dialogArea');
var v=ta.value.trim(); var v=ta.value.trim();
if(v){ if(v){
if(m==='code'){ CM.setValue(v); CM.setCursor({line:CM.lastLine(), ch:(CM.getLine(CM.lastLine())||'').length}); } if(m==='code'){ ED.setValue(v); ED.setCursor({line:ED.lineCount()-1, ch:(ED.getLine(ED.lineCount()-1)||'').length}); }
else if(m==='latex'){ document.getElementById('latexArea').value=v; latexLive(); } else if(m==='latex'){ document.getElementById('latexArea').value=v; latexLive(); }
ta.value=''; ta.value='';
} }
@@ -371,7 +475,7 @@ function setMorph(m){
if(m==='code'){ document.getElementById('actionHint').textContent='Cmd/Ctrl+Enter 提交且保留代码'; } if(m==='code'){ document.getElementById('actionHint').textContent='Cmd/Ctrl+Enter 提交且保留代码'; }
else if(m==='latex'){ document.getElementById('actionHint').textContent='提交作答 · 教师端/AI 按 rubric 初评'; } else if(m==='latex'){ document.getElementById('actionHint').textContent='提交作答 · 教师端/AI 按 rubric 初评'; }
else { document.getElementById('actionHint').textContent='Enter 发送并清空'; } else { document.getElementById('actionHint').textContent='Enter 发送并清空'; }
if(m==='code'){ setTimeout(function(){ CM.refresh(); CM.focus(); },30); } if(m==='code'){ setTimeout(function(){ ED.focus(); lspCheck(); },30); }
if(m==='latex'){ latexLive(); } if(m==='latex'){ latexLive(); }
if(m==='dialog'){ document.getElementById('dialogArea').focus(); } if(m==='dialog'){ document.getElementById('dialogArea').focus(); }
} }
@@ -398,7 +502,7 @@ function sendDialog(){
/* ================= 代码形态:自动预检 → 提交判题 ================= */ /* ================= 代码形态:自动预检 → 提交判题 ================= */
function submitCode(){ function submitCode(){
if(PENDING) return; if(PENDING) return;
var code=CM.getValue(); LAST_CODE=code; VER++; var code=ED.getValue(); LAST_CODE=code; VER++;
PENDING=true; var dot=document.getElementById('sendDot'); dot.disabled=true; PENDING=true; var dot=document.getElementById('sendDot'); dot.disabled=true;
addMsg('user', '<div style="font-family:var(--mono);font-size:12px;white-space:pre-wrap">提交代码(Java)· 版本 v'+VER+'</div>'); addMsg('user', '<div style="font-family:var(--mono);font-size:12px;white-space:pre-wrap">提交代码(Java)· 版本 v'+VER+'</div>');
addMsg('sys', '🔍 自动本地预检中(语法 → 静态分析 → 样例自测)…'); addMsg('sys', '🔍 自动本地预检中(语法 → 静态分析 → 样例自测)…');
@@ -511,8 +615,8 @@ function pollJudge(rid, code, sysMsg, n){
function fallbackJudge(code){ /* 后端不可达时的本地演示(prototype mockJudge) */ function fallbackJudge(code){ /* 后端不可达时的本地演示(prototype mockJudge) */
var result=mockJudge(code); renderJudgeCard(result, code); var result=mockJudge(code); renderJudgeCard(result, code);
} }
function loadVersion(i){ CM.setValue(SUBMISSIONS[i].code); setMorph('code'); toast('已载入版本 v'+(i+1)+' 到编辑器'); } function loadVersion(i){ ED.setValue(SUBMISSIONS[i].code); setMorph('code'); lspCheck(); toast('已载入版本 v'+(i+1)+' 到编辑器'); }
function copyToEditor(){ CM.setValue(LAST_CODE); setMorph('code'); CM.refresh(); toast('已复制回编辑器(可继续修改)'); } function copyToEditor(){ ED.setValue(LAST_CODE); setMorph('code'); lspCheck(); toast('已复制回编辑器(可继续修改)'); }
function askAnalyze(){ addMsg('sys','已请求 AI 分析上次评测(评测上下文自动带入)…'); aiExplain(true); } function askAnalyze(){ addMsg('sys','已请求 AI 分析上次评测(评测上下文自动带入)…'); aiExplain(true); }
function nextProblem(){ addMsg('sys','(原型演示)AI 自适应推荐:完成本章 3/5 → 建议 04-2 边界条件微练习,或进入 05 方法。'); } function nextProblem(){ addMsg('sys','(原型演示)AI 自适应推荐:完成本章 3/5 → 建议 04-2 边界条件微练习,或进入 05 方法。'); }
@@ -652,7 +756,7 @@ function setMode(m){
addMsg('sys', m==='learn'?'已切换到 <b>学习模式</b>:AI 可诊断代码、给思路引导':'已切换到 <b>严格模式</b>:竞赛模拟,AI 不分析代码、不给提示'); addMsg('sys', m==='learn'?'已切换到 <b>学习模式</b>:AI 可诊断代码、给思路引导':'已切换到 <b>严格模式</b>:竞赛模拟,AI 不分析代码、不给提示');
} }
function aiExplain(fromCard){ function aiExplain(fromCard){
var code=CM.getValue()||LAST_CODE; if(!code){toast('先写代码');return;} var code=ED.getValue()||LAST_CODE; if(!code){toast('先写代码');return;}
if(LAST_RID){ if(LAST_RID){
addMsg('sys','🔍 已请求 AI 分析上次评测(rid='+LAST_RID+')…'); addMsg('sys','🔍 已请求 AI 分析上次评测(rid='+LAST_RID+')…');
fetch(API_BASE+'/api/chat/explain',{method:'POST',headers:authHeaders({'Content-Type':'application/json'}),body:JSON.stringify({rid:LAST_RID, mode:MODE==='strict'?'strict':'learning'})}) fetch(API_BASE+'/api/chat/explain',{method:'POST',headers:authHeaders({'Content-Type':'application/json'}),body:JSON.stringify({rid:LAST_RID, mode:MODE==='strict'?'strict':'learning'})})