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); }