Release Web 2.0.2 task logs
This commit is contained in:
+31
-27
@@ -3,6 +3,7 @@ import {apiPath, webPath} from './paths.js';
|
||||
import {el, $, $$, clone, getPath, setPath, pathKey, textValue, number, chinaTime, download, csvBlob, optionsList, detailsList, tabKeys} from './dom.js';
|
||||
import {PageView, PAGES} from './pages.js';
|
||||
import {notice, dialog, confirm, filePicker, fileBase64} from './ui.js';
|
||||
import {createLogState, mergeLogs, visibleLogs, syncLogLines, logText, attachTaskLog} from './task-logs.js';
|
||||
|
||||
const state = {accounts:new Map(),active:null,schema:null,meta:null,ready:false,polling:false,seq:0,redirecting:false,webStatusError:null,statusMessage:'连接中'};
|
||||
const current = () => state.accounts.get(state.active);
|
||||
@@ -72,7 +73,7 @@ function renderPageConnection(page) {
|
||||
|
||||
function makeAccount(summary) {
|
||||
return {id:summary.id,summary,config:null,revision:null,edits:new Map(),pages:new Map(),page:'login',jobs:new Map(),savePromise:null,saveError:null,
|
||||
logs:{entries:[],next:0,debug:false,loading:false},loadingConfig:false,transportErrors:new Map()};
|
||||
logs:createLogState(),loadingConfig:false,transportErrors:new Map()};
|
||||
}
|
||||
|
||||
function setStatus(message) { state.statusMessage=message;renderStatus(); }
|
||||
@@ -270,6 +271,7 @@ function getPage(account,key) {
|
||||
const page=new PageView(account,key,{edit:editConfig,perform,load:loadPage,action:pageAction,command,
|
||||
schema:pageKey=>state.schema?.pages?.find(page=>page.key===pageKey)?.form || []});
|
||||
account.pages.set(key,page);$('#page-host').append(page.root);
|
||||
attachTaskLog(page);
|
||||
}
|
||||
return account.pages.get(key);
|
||||
}
|
||||
@@ -294,12 +296,14 @@ function selectPage(key) {
|
||||
account.page=key;
|
||||
state.accounts.forEach(other=>other.pages.forEach(page=>{page.root.hidden=other.id!==account.id||page.key!==key;}));
|
||||
const page=getPage(account,key);page.root.hidden=false;
|
||||
page.taskLog?.render();
|
||||
$$('.page-tab').forEach(tab=>{const selected=tab.dataset.page===key;tab.setAttribute('aria-selected',String(selected));tab.tabIndex=selected?0:-1;});
|
||||
loadPage(page,true);
|
||||
}
|
||||
|
||||
async function selectAccount(id) {
|
||||
const previous=current();previous?.pages.get('login')?.login?.clearPassword();
|
||||
if(previous && !$('#log-panel').hidden && $('#log-lines').dataset.account===previous.id)previous.logs.total.scrollTop=$('#log-lines').scrollTop;
|
||||
if(previous?.edits.size)flushConfig(previous).catch(error);
|
||||
state.active=id;const account=current();if(!account)return;
|
||||
$('#page-host').querySelector('.initial-state')?.remove();
|
||||
@@ -374,11 +378,11 @@ async function exportYields(account=current()) {
|
||||
async function command(name,account=current()) {
|
||||
try {
|
||||
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
|
||||
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.1'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`}),el('p',{class:'info-note',text:'与桌面助手共用核心策略。配置在服务端自动保存;每次成功登录后自动执行已勾选功能,可在顶部“停止”。服务重启后须先成功登录才执行。'})),{info:true});
|
||||
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.2'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`}),el('p',{class:'info-note',text:'与桌面助手共用核心策略。配置在服务端自动保存;每次成功登录后自动执行已勾选功能,可在顶部“停止”。服务重启后须先成功登录才执行。'})),{info:true});
|
||||
if(name==='updates')return await showUpdates();
|
||||
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
|
||||
if(!account)throw new Error('请先新增或选择账号。');
|
||||
if(name==='debug'){account.logs.debug=!account.logs.debug;account.logs.entries=[];account.logs.next=0;account.logs.generation=(account.logs.generation || 0)+1;$('#debug-log').checked=account.logs.debug;setLogVisible(true);renderLogs(true);await fetchLogs(account);return;}
|
||||
if(name==='debug'){account.logs.debug=!account.logs.debug;account.logs.next=0;account.logs.generation=(account.logs.generation || 0)+1;$('#debug-log').checked=account.logs.debug;setLogVisible(true);renderLogs(true);currentPage()?.taskLog?.render();await fetchLogs(account);return;}
|
||||
if(name==='save'){await flushConfig(account);notice('策略已保存。');return;}
|
||||
if(name==='stop'||name==='start')return await perform(account,name);
|
||||
if(name==='start-all'||name==='stop-all'){
|
||||
@@ -478,8 +482,10 @@ function setLogVisible(visible) {
|
||||
function applyLogLayout(account=current(),visibleOverride) {
|
||||
if(account&&account.id!==state.active)return;
|
||||
const visible=visibleOverride ?? account?.config?.log_visible ?? true;
|
||||
$('#log-panel').hidden=!visible;$('#log-resizer').hidden=!visible;$('#log-toggle').textContent=visible?'隐藏日志':'显示日志';$('#log-toggle').setAttribute('aria-expanded',String(visible));
|
||||
if(!visible && account && !$('#log-panel').hidden && $('#log-lines').dataset.account===account.id)account.logs.total.scrollTop=$('#log-lines').scrollTop;
|
||||
$('#log-panel').hidden=!visible;$('#log-resizer').hidden=!visible;$('#log-toggle').textContent=visible?'隐藏总日志':'显示总日志';$('#log-toggle').setAttribute('aria-expanded',String(visible));
|
||||
const size=account?.config?.log_sizes?.[1];if(size)setLogHeight(size);
|
||||
if(visible)renderLogs();
|
||||
}
|
||||
|
||||
function setLogHeight(height) {
|
||||
@@ -489,29 +495,27 @@ function setLogHeight(height) {
|
||||
|
||||
function renderLogs(reset=false) {
|
||||
const account=current(),root=$('#log-lines');if(!account){root.replaceChildren();return;}
|
||||
const log=account.logs;
|
||||
if(reset){root.replaceChildren();log.rendered=0;}
|
||||
const follow=$('#log-follow').checked&& (reset || root.scrollHeight-root.scrollTop-root.clientHeight<45);
|
||||
for(const entry of log.entries.slice(log.rendered || 0)){
|
||||
const line=el('div',{class:`log-entry ${entry.level || entry.kind || ''}`,'data-entry-id':entry.id});
|
||||
const stamp=entry.time || entry.timestamp || entry.at || '';
|
||||
line.append(el('span',{class:'log-time',text:chinaTime(stamp),title:String(stamp)}),document.createTextNode(entry.message || entry.operation || textValue(entry)));
|
||||
if(entry.details_available || entry.detail_url || entry.debug_url){line.classList.add('inspectable');line.tabIndex=0;line.setAttribute('role','button');line.title='查看脱敏请求 / 响应 JSON';line.addEventListener('click',()=>showDebugEntry(account,entry));line.addEventListener('keydown',event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();showDebugEntry(account,entry);}});}
|
||||
root.append(line);
|
||||
}
|
||||
log.rendered=log.entries.length;
|
||||
while(root.childElementCount>600)root.firstElementChild.remove();
|
||||
$('#log-count').textContent=`${Math.min(600,log.entries.length)} 条`;$('#debug-log').checked=log.debug;$('#log-heading').textContent=log.debug?'调试日志(已脱敏)':'运行日志';
|
||||
if(follow)root.scrollTop=root.scrollHeight;
|
||||
if($('#log-panel').hidden)return;
|
||||
const log=account.logs,view=log.total;
|
||||
const switching=root.dataset.account!==account.id;
|
||||
const scrollTop=switching?view.scrollTop:root.scrollTop;
|
||||
reset=reset || switching;
|
||||
const token=JSON.stringify([log.revision,view.clearedThrough,log.debug]);
|
||||
if(!reset && view.rendered===token)return;
|
||||
const entries=visibleLogs(log,view);
|
||||
syncLogLines(root,entries,{reset,follow:view.follow,scrollTop:reset?scrollTop:undefined,inspect:log.debug?entry=>showDebugEntry(account,entry):null});
|
||||
root.dataset.account=account.id;view.rendered=token;
|
||||
$('#log-follow').checked=view.follow;
|
||||
const count=`${Math.min(600,entries.length)} 条`;
|
||||
if($('#log-count').textContent!==count)$('#log-count').textContent=count;
|
||||
$('#debug-log').checked=log.debug;$('#log-heading').textContent=log.debug?'总日志(调试 / 已脱敏)':'总日志';
|
||||
}
|
||||
|
||||
async function fetchLogs(account) {
|
||||
if(account.logs.loading)return;account.logs.loading=true;const generation=account.logs.generation || 0;
|
||||
try{const response=await api.logs(account.id,account.logs.next,account.logs.debug);if(generation!==(account.logs.generation || 0))return;
|
||||
const seen=new Set(account.logs.entries.map(entry=>entry.id));
|
||||
account.logs.entries.push(...(response.entries || []).filter(entry=>entry.id==null||!seen.has(entry.id)));account.logs.next=response.next;
|
||||
if(account.id===state.active)renderLogs();
|
||||
if(account.logs.entries.length>1200){account.logs.entries=account.logs.entries.slice(-600);if(account.id===state.active)renderLogs(true);}
|
||||
mergeLogs(account.logs,response.entries || [],response.next);
|
||||
if(account.id===state.active){renderLogs();currentPage()?.taskLog?.render();}
|
||||
transportError(account,'logs','日志',null);
|
||||
}catch(failure){if(generation===(account.logs.generation || 0))transportError(account,'logs','日志',failure);}finally{account.logs.loading=false;}
|
||||
}
|
||||
@@ -577,7 +581,7 @@ async function bootstrap() {
|
||||
$('#app').hidden=false;
|
||||
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
|
||||
if(state.redirecting)return;
|
||||
$('#app-version').textContent=meta.version || '2.0.1';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
|
||||
$('#app-version').textContent=meta.version || '2.0.2';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
|
||||
await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接');
|
||||
}catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
|
||||
}
|
||||
@@ -595,10 +599,10 @@ $('#refresh-interval').addEventListener('change',event=>{if(current())editConfig
|
||||
$('#save-status').tabIndex=0;$('#save-status').addEventListener('click',()=>command('save'));$('#save-status').addEventListener('keydown',event=>{if(event.key==='Enter')command('save');});
|
||||
$('#debug-toggle').addEventListener('click',()=>command('debug'));$('#debug-log').addEventListener('change',()=>command('debug'));
|
||||
$('#log-toggle').addEventListener('click',()=>setLogVisible($('#log-panel').hidden));
|
||||
$('#clear-log').addEventListener('click',()=>{if(current()){current().logs.entries=[];current().logs.rendered=0;renderLogs(true);}});
|
||||
$('#download-log').addEventListener('click',()=>{const account=current();if(account)download(new Blob([account.logs.entries.map(entry=>[entry.time || entry.timestamp || '',entry.message || entry.operation || ''].join(' ')).join('\n')],{type:'text/plain;charset=utf-8'}),'牧场日志.txt');});
|
||||
$('#log-lines').addEventListener('scroll',()=>{const node=$('#log-lines');if(node.scrollHeight-node.scrollTop-node.clientHeight>55)$('#log-follow').checked=false;});
|
||||
$('#log-follow').addEventListener('change',()=>{if($('#log-follow').checked)$('#log-lines').scrollTop=$('#log-lines').scrollHeight;});
|
||||
$('#clear-log').addEventListener('click',()=>{const log=current()?.logs;if(log){log.total.clearedThrough=log.highWater;renderLogs();}});
|
||||
$('#download-log').addEventListener('click',()=>{const log=current()?.logs;if(log)download(new Blob([logText(visibleLogs(log,log.total))],{type:'text/plain;charset=utf-8'}),'牧场日志.txt');});
|
||||
$('#log-lines').addEventListener('scroll',()=>{const node=$('#log-lines'),account=current();if(!account || $('#log-panel').hidden || node.dataset.account!==account.id)return;account.logs.total.scrollTop=node.scrollTop;if(node.scrollHeight-node.scrollTop-node.clientHeight>55){$('#log-follow').checked=false;account.logs.total.follow=false;}});
|
||||
$('#log-follow').addEventListener('change',()=>{const account=current(),node=$('#log-lines');if(!account || $('#log-panel').hidden || node.dataset.account!==account.id)return;account.logs.total.follow=$('#log-follow').checked;if($('#log-follow').checked)node.scrollTop=node.scrollHeight;});
|
||||
let resize;
|
||||
$('#log-resizer').addEventListener('pointerdown',event=>{resize={y:event.clientY,height:$('#log-panel').getBoundingClientRect().height};event.currentTarget.setPointerCapture(event.pointerId);event.preventDefault();});
|
||||
$('#log-resizer').addEventListener('pointermove',event=>{if(resize)setLogHeight(resize.height+resize.y-event.clientY);});
|
||||
|
||||
@@ -26,13 +26,13 @@
|
||||
</div></details>
|
||||
<details class="menu"><summary accesskey="h">帮助<span class="access-key">(H)</span></summary><div class="menu-popup"><button data-command="updates">检查版本更新…</button><button data-command="debug">调试日志</button><button data-command="about">关于…</button></div></details>
|
||||
</nav>
|
||||
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.1</span></span>
|
||||
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.2</span></span>
|
||||
<span id="access-mode" class="muted">正在连接本地服务</span>
|
||||
</header>
|
||||
<div class="account-bar"><div id="account-tabs" class="account-tabs" role="tablist" aria-label="账号"></div><button id="add-account" class="compact" title="新增账号">+ 新增账号</button></div>
|
||||
<div class="toolbar" aria-label="角色状态和运行控制">
|
||||
<div class="player-line"><span id="connection" class="connection">未登录</span><strong id="player-name">—</strong><span>等级 <b id="player-level">—</b></span><span class="experience">经验 <b id="player-exp">—</b><progress id="experience-progress" max="1" value="0" aria-label="角色经验"></progress></span><span>金币 <b id="player-money">—</b></span><span>氪金 <b id="player-ke">—</b></span><span>体力 <b id="player-ti">—</b></span></div>
|
||||
<div class="run-controls"><label>刷新 <select id="refresh-interval" aria-label="随机刷新间隔" title="整体刷新完成后,从 0 到所选上限随机等待;空坑装填与到期同步独立执行"><option value="30">随机30秒</option><option value="60">随机60秒</option><option value="120">随机2分钟</option><option value="300">随机5分钟</option></select></label><button id="strategy-toggle" class="run-button" disabled>开启</button><button id="refresh">刷新 / 预览策略</button><button id="debug-toggle">调试日志</button><button id="log-toggle" aria-expanded="true" aria-controls="log-panel">隐藏日志</button></div>
|
||||
<div class="run-controls"><label>刷新 <select id="refresh-interval" aria-label="随机刷新间隔" title="整体刷新完成后,从 0 到所选上限随机等待;空坑装填与到期同步独立执行"><option value="30">随机30秒</option><option value="60">随机60秒</option><option value="120">随机2分钟</option><option value="300">随机5分钟</option></select></label><button id="strategy-toggle" class="run-button" disabled>开启</button><button id="refresh">刷新 / 预览策略</button><button id="debug-toggle">调试日志</button><button id="log-toggle" aria-expanded="true" aria-controls="log-panel">隐藏总日志</button></div>
|
||||
</div>
|
||||
<div class="summary-line"><span id="data-summary">等待连接服务</span><span id="save-status" role="status">配置未载入</span></div>
|
||||
<main id="workspace" class="workspace">
|
||||
@@ -40,7 +40,7 @@
|
||||
<div id="page-host" class="page-host"><div class="initial-state" role="status">正在载入工作台…</div></div>
|
||||
</main>
|
||||
<div id="log-resizer" class="log-resizer" role="separator" tabindex="0" aria-label="调整日志高度" aria-orientation="horizontal" aria-valuemin="64" aria-valuemax="480" aria-valuenow="150" title="上下拖动调整日志高度;也可使用方向键"></div>
|
||||
<section id="log-panel" class="log-panel" aria-label="运行日志"><div class="log-toolbar"><strong id="log-heading">运行日志</strong><label><input id="debug-log" type="checkbox">调试 / 脱敏</label><label><input id="log-follow" type="checkbox" checked>自动滚动</label><span id="log-count" class="muted"></span><span class="spacer"></span><button id="download-log" class="small">下载日志</button><button id="clear-log" class="small">清空显示</button></div><div id="log-lines" class="log-lines" tabindex="0" role="log" aria-live="off" aria-label="日志内容"></div></section>
|
||||
<section id="log-panel" class="log-panel" aria-label="总日志"><div class="log-toolbar"><strong id="log-heading">总日志</strong><label><input id="debug-log" type="checkbox">调试 / 脱敏</label><label><input id="log-follow" type="checkbox" checked>自动滚动</label><span id="log-count" class="muted" aria-live="off"></span><span class="spacer"></span><button id="download-log" class="small">下载日志</button><button id="clear-log" class="small" title="只清空本账号总日志显示,保留各任务日志及服务端历史">清空显示</button></div><div id="log-lines" class="log-lines" tabindex="0" role="log" aria-live="off" aria-label="总日志内容"></div></section>
|
||||
<footer class="status-bar"><span id="status-text" role="status">连接中</span><span id="job-status" class="muted"></span><span class="spacer"></span><span>游戏 <span id="game-version">1.9.68</span></span><span id="clock"></span></footer>
|
||||
</div>
|
||||
<div id="notice" class="notice" role="status" hidden></div>
|
||||
|
||||
@@ -12,3 +12,19 @@
|
||||
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important}}
|
||||
.page-content{display:flex;flex-direction:column;gap:7px;flex:1;min-height:0}.statistics-table-host{display:flex;flex-direction:column;flex:1;min-height:100px}.count-id{width:100px}.statistics-city>summary,.statistics-stage>summary{cursor:pointer;font-size:12px;padding:6px 7px;line-height:1.5;overflow-wrap:anywhere}.statistics-city>summary{background:#eef1f5;border-bottom:1px solid #d8dee6;font-weight:600}.statistics-stage{margin-left:10px}.statistics-stage>summary:hover{background:#edf3fa}.statistics-levels{padding-left:12px}.statistics-levels button{padding:5px 8px}.debug-json{margin:0;font:12px/1.6 Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere}.log-entry.inspectable{cursor:pointer}.log-entry.inspectable:hover{background:#e8f0f9}.member-draft-note{font-size:11px;color:#805300}.counts-lines{display:flex;flex-direction:column;gap:3px;margin-bottom:4px}
|
||||
.chart-axis{font-size:11px;fill:#55616e;font-variant-numeric:tabular-nums}
|
||||
.task-log-panel{flex:0 0 auto;min-width:0;border:1px solid var(--border);background:#fff;overflow-anchor:none}
|
||||
.has-task-log>.page-content{flex:1 0 160px;min-height:160px;overflow:auto}
|
||||
.has-task-log[data-page=login]>.page-content{flex:0 0 auto;overflow:visible}
|
||||
.task-log-heading{flex-wrap:wrap;gap:6px 12px}
|
||||
.task-log-heading h3{margin:0;font-size:13px;font-weight:600}
|
||||
.task-log-status{font-size:12px;overflow-wrap:anywhere}
|
||||
.task-log-body{position:relative;min-width:0}
|
||||
.task-log-controls{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;padding:6px 8px;border-bottom:1px solid var(--border);font-size:12px}
|
||||
.task-log-controls label{display:flex;align-items:center;gap:5px;min-width:0}
|
||||
.task-log-controls input[type=search]{width:185px;min-width:100px;max-width:100%}
|
||||
.task-log-lines{height:190px;min-height:120px;max-height:35vh;overflow-anchor:none;overscroll-behavior:contain}
|
||||
.task-log-viewport{position:relative}
|
||||
.task-log-empty{position:absolute;top:6px;left:10px;right:10px;margin:0;pointer-events:none;font-size:12px}
|
||||
.task-log-help{margin:0;padding:4px 8px;border-top:1px solid var(--border);font-size:12px;line-height:1.5}
|
||||
#log-lines{overflow-anchor:none;overscroll-behavior:contain}
|
||||
@media(max-width:700px){.task-log-controls button,.task-log-heading button{min-height:32px}.task-log-lines{height:165px}.task-log-status{flex:1 1 180px}}
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
import {el, chinaTime, textValue, download} from './dom.js';
|
||||
|
||||
const BUFFER_LIMIT = 1200;
|
||||
const RENDER_LIMIT = 600;
|
||||
const categories = new Set(['general', 'login', 'hatching', 'mainline', 'gifts', 'commissions', 'exploration', 'maps', 'ranch', 'daily']);
|
||||
const titles = {login:'登录日志', daily:'每日事务日志', ranch:'牧场日志', hatching:'孵蛋日志', mainline:'主线日志', gifts:'赠礼日志', commissions:'委托日志', exploration:'探险日志', maps:'扫荡日志'};
|
||||
let panelId = 0;
|
||||
|
||||
export function createLogState() {
|
||||
return {entries:[], next:0, highWater:0, retainedAfter:0, revision:0, debug:false, loading:false,
|
||||
total:{clearedThrough:0, follow:true, scrollTop:0}};
|
||||
}
|
||||
|
||||
const levelOf = entry => String(entry.level || entry.kind || (entry.debug ? 'debug' : 'info')).toLowerCase();
|
||||
const messageOf = entry => String(entry.message || entry.operation || textValue(entry));
|
||||
const stampOf = entry => entry.time || entry.timestamp || entry.at || '';
|
||||
const debugEntry = entry => entry.debug || levelOf(entry) === 'debug';
|
||||
const lineSignature = (entry, inspect) => JSON.stringify([stampOf(entry), messageOf(entry), levelOf(entry),
|
||||
Boolean(inspect && (entry.details_available || entry.detail_url || entry.debug_url))]);
|
||||
|
||||
// All panels share this one bounded history. A cursor rewind for debug must not
|
||||
// reintroduce evicted records or move any panel's local clear watermark.
|
||||
export function mergeLogs(log, entries, next) {
|
||||
const bySequence = new Map(log.entries.map(entry => [entry.seq, entry]));
|
||||
let changed = false;
|
||||
for (const source of entries) {
|
||||
const numeric = Number(source.seq ?? source.id);
|
||||
const seq = Number.isFinite(numeric) ? numeric : log.highWater + 1;
|
||||
if (seq <= log.retainedAfter) continue;
|
||||
const entry = {...source, seq, category:categories.has(source.category) ? source.category : 'general'};
|
||||
log.highWater = Math.max(log.highWater, seq);
|
||||
if (JSON.stringify(bySequence.get(seq)) !== JSON.stringify(entry)) {
|
||||
bySequence.set(seq, entry);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
log.entries = [...bySequence.values()].sort((a, b) => a.seq - b.seq);
|
||||
if (log.entries.length > BUFFER_LIMIT) {
|
||||
const removed = log.entries.splice(0, log.entries.length - BUFFER_LIMIT);
|
||||
log.retainedAfter = Math.max(log.retainedAfter, removed.at(-1).seq);
|
||||
}
|
||||
log.revision++;
|
||||
}
|
||||
log.next = next ?? log.next;
|
||||
log.highWater = Math.max(log.highWater, Number(log.next) || 0);
|
||||
}
|
||||
|
||||
export function visibleLogs(log, view, page) {
|
||||
return log.entries.filter(entry => entry.seq > view.clearedThrough && (log.debug || !debugEntry(entry))
|
||||
&& (!page || entry.category === page || page === 'login' && entry.category === 'general')
|
||||
&& (!view.level || levelOf(entry) === view.level)
|
||||
&& (!view.search || messageOf(entry).toLocaleLowerCase().includes(view.search.toLocaleLowerCase())));
|
||||
}
|
||||
|
||||
export function logLine(entry, inspect) {
|
||||
const level = levelOf(entry);
|
||||
const line = el('div', {class:`log-entry ${['error','warning','debug'].includes(level) ? level : ''}`,
|
||||
'data-entry-id':entry.id, 'data-sequence':entry.seq});
|
||||
line.logSignature = lineSignature(entry, inspect);
|
||||
const stamp = stampOf(entry);
|
||||
line.append(el('span', {class:'log-time', text:chinaTime(stamp), title:String(stamp)}), document.createTextNode(messageOf(entry)));
|
||||
if (inspect && (entry.details_available || entry.detail_url || entry.debug_url)) {
|
||||
line.classList.add('inspectable');
|
||||
line.tabIndex = 0;
|
||||
line.setAttribute('role', 'button');
|
||||
line.title = '查看脱敏请求 / 响应 JSON';
|
||||
line.addEventListener('click', () => inspect(entry));
|
||||
line.addEventListener('keydown', event => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {event.preventDefault();inspect(entry);}
|
||||
});
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
// Append/remove keyed rows, retaining both row identity and the visible reading
|
||||
// anchor. Only the log's own scroll position changes; ancestors are never scrolled.
|
||||
export function syncLogLines(root, entries, {follow, reset=false, scrollTop, inspect} = {}) {
|
||||
const previousTop = scrollTop ?? root.scrollTop;
|
||||
const top = root.getBoundingClientRect().top;
|
||||
const anchor = follow ? null : [...root.children].find(node => node.getBoundingClientRect().bottom > top);
|
||||
const anchorTop = anchor?.getBoundingClientRect().top;
|
||||
if (reset) root.replaceChildren();
|
||||
const shown = entries.slice(-RENDER_LIMIT);
|
||||
const wanted = new Set(shown.map(entry => String(entry.seq)));
|
||||
for (const node of [...root.children]) if (!wanted.has(node.dataset.sequence)) node.remove();
|
||||
const existing = new Map([...root.children].map(node => [node.dataset.sequence, node]));
|
||||
let previous = null;
|
||||
for (const entry of shown) {
|
||||
let node = existing.get(String(entry.seq));
|
||||
if (node && node.logSignature !== lineSignature(entry, inspect)) {
|
||||
const replacement = logLine(entry, inspect);
|
||||
node.replaceWith(replacement);
|
||||
node = replacement;
|
||||
}
|
||||
if (!node) node = logLine(entry, inspect);
|
||||
const next = previous ? previous.nextElementSibling : root.firstElementChild;
|
||||
if (next !== node) root.insertBefore(node, next);
|
||||
previous = node;
|
||||
}
|
||||
if (follow) root.scrollTop = root.scrollHeight;
|
||||
else if (!reset && anchor?.isConnected) root.scrollTop += anchor.getBoundingClientRect().top - anchorTop;
|
||||
else root.scrollTop = previousTop;
|
||||
}
|
||||
|
||||
export function logText(entries) {
|
||||
return entries.map(entry => [stampOf(entry), messageOf(entry)].join(' ')).join('\n');
|
||||
}
|
||||
|
||||
export class TaskLogPanel {
|
||||
constructor(page) {
|
||||
this.page = page;
|
||||
this.log = page.account.logs;
|
||||
this.title = titles[page.key];
|
||||
this.view = {clearedThrough:0, follow:true, search:'', level:'', seenThrough:0};
|
||||
const id = `task-log-${++panelId}`;
|
||||
this.heading = el('h3', {id:`${id}-heading`, text:this.title});
|
||||
this.status = el('span', {class:'task-log-status muted', role:'status', 'aria-atomic':'true'});
|
||||
this.toggle = el('button', {type:'button', text:'隐藏', 'aria-label':`隐藏${this.title}`, 'aria-expanded':'true', 'aria-controls':`${id}-body`,
|
||||
onClick:() => this.setHidden(!this.body.hidden)});
|
||||
this.follow = el('button', {type:'button', text:'暂停跟随', 'aria-label':`${this.title}:暂停自动滚动`, 'aria-pressed':'true',
|
||||
onClick:() => this.setFollow(!this.view.follow)});
|
||||
this.search = el('input', {type:'search', 'aria-label':`${this.title}搜索`, placeholder:'筛选日志文字',
|
||||
onInput:() => {this.view.search = this.search.value;this.render();}});
|
||||
this.level = el('select', {'aria-label':`${this.title}级别`, onChange:() => {this.view.level = this.level.value;this.render();}},
|
||||
...[['','全部级别'],['info','信息'],['warning','警告'],['error','错误'],['debug','调试']].map(([value,text]) => el('option', {value,text})));
|
||||
const clear = el('button', {type:'button', text:'清空显示', 'aria-label':`清空当前账号${this.title}显示`,
|
||||
title:'只清空本账号本页显示,保留总日志及其他页面记录', onClick:() => {
|
||||
this.view.clearedThrough = this.log.highWater;
|
||||
this.view.seenThrough = this.log.highWater;
|
||||
this.render();
|
||||
}});
|
||||
const save = el('button', {type:'button', text:'下载日志', 'aria-label':`下载当前账号${this.title}`, title:'下载本页清空后保留、符合当前日志筛选的记录',
|
||||
onClick:() => download(new Blob([logText(this.entries())], {type:'text/plain;charset=utf-8'}), `${page.account.summary.label || page.account.id}-${this.title}.txt`)});
|
||||
this.lines = el('div', {class:'log-lines task-log-lines', role:'log', 'aria-live':'off', 'aria-label':`${this.title}内容`, tabindex:0,
|
||||
onScroll:() => {
|
||||
if (this.view.follow && this.lines.scrollHeight - this.lines.scrollTop - this.lines.clientHeight > 24) this.setFollow(false);
|
||||
}});
|
||||
this.empty = el('p', {class:'task-log-empty muted', text:'暂无日志;运行任务后将在此显示。'});
|
||||
this.body = el('div', {id:`${id}-body`, class:'task-log-body'},
|
||||
el('div', {class:'task-log-controls'}, el('label', {}, el('span', {text:'搜索'}), this.search),
|
||||
el('label', {}, el('span', {text:'级别'}), this.level), this.follow, save, clear), el('div', {class:'task-log-viewport'}, this.lines, this.empty),
|
||||
el('p', {class:'task-log-help muted', text:`${page.key === 'login' ? '含登录和常规记录(旧记录、未知分类);' : page.key === 'ranch' ? '含潜能突破和牧场记录;' : ''}仅清空本账号本页显示;下载遵循日志筛选。最多显示最近 600 条。`}));
|
||||
this.root = el('section', {class:'task-log-panel', 'data-task-log':page.key, 'aria-labelledby':`${id}-heading`},
|
||||
el('div', {class:'log-toolbar task-log-heading'}, this.heading, this.status, el('span', {class:'spacer'}), this.toggle), this.body);
|
||||
page.root.classList.add('has-task-log');
|
||||
page.root.append(this.root);
|
||||
}
|
||||
|
||||
entries() { return visibleLogs(this.log, this.view, this.page.key); }
|
||||
active() { return !this.page.root.hidden && !this.page.root.closest('[hidden]'); }
|
||||
|
||||
setHidden(hidden) {
|
||||
this.body.hidden = hidden;
|
||||
this.toggle.textContent = hidden ? '显示' : '隐藏';
|
||||
this.toggle.setAttribute('aria-label', `${hidden ? '显示' : '隐藏'}${this.title}`);
|
||||
this.toggle.setAttribute('aria-expanded', String(!hidden));
|
||||
this.render();
|
||||
}
|
||||
|
||||
setFollow(follow) {
|
||||
this.view.follow = follow;
|
||||
this.view.seenThrough = this.log.highWater;
|
||||
this.follow.textContent = follow ? '暂停跟随' : '跟随最新';
|
||||
this.follow.setAttribute('aria-label', `${this.title}:${follow ? '暂停自动滚动' : '跟随最新日志'}`);
|
||||
this.follow.setAttribute('aria-pressed', String(follow));
|
||||
this.render();
|
||||
if (follow && !this.body.hidden) this.lines.scrollTop = this.lines.scrollHeight;
|
||||
}
|
||||
|
||||
render() {
|
||||
if (!this.active()) return;
|
||||
const entries = this.entries();
|
||||
const pending = !this.view.follow ? entries.filter(entry => entry.seq > this.view.seenThrough).length : 0;
|
||||
const status = `${this.title}:${entries.length} 条${entries.length > RENDER_LIMIT ? '(显示最近 600 条)' : ''};${this.view.follow ? '跟随最新' : '已暂停跟随'}${pending ? `,新增 ${pending} 条` : ''}`;
|
||||
if (this.status.textContent !== status) this.status.textContent = status;
|
||||
if (this.body.hidden) return;
|
||||
const token = JSON.stringify([this.log.revision, this.log.debug, this.view.clearedThrough, this.view.search, this.view.level]);
|
||||
if (token !== this.rendered) {
|
||||
syncLogLines(this.lines, entries, {follow:this.view.follow});
|
||||
this.rendered = token;
|
||||
this.empty.hidden = entries.length > 0;
|
||||
this.empty.textContent = this.view.search || this.view.level ? '没有符合当前筛选的日志。' : '暂无日志;运行任务后将在此显示。';
|
||||
}
|
||||
if (this.view.follow) this.view.seenThrough = this.log.highWater;
|
||||
}
|
||||
}
|
||||
|
||||
export function attachTaskLog(page) {
|
||||
if (Object.hasOwn(titles, page.key)) page.taskLog = new TaskLogPanel(page);
|
||||
}
|
||||
Reference in New Issue
Block a user