Files
myrzx_bot/ranch_web/static/pages.js
T

382 lines
28 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {el, $, $$, textValue, number, chinaTime, getPath, pathKey, optionsList, detailsList, tabKeys, empty} from './dom.js';
import {PolicyForm, control} from './forms.js';
import {DataTable, GroupedTables} from './table.js';
import {dialog, contextMenu, notice} from './ui.js';
export const PAGES = [
['login', '登录'], ['incubator', '培育室'], ['bag', '背包'], ['ranch', '牧场'], ['daily', '每日事务'],
['hatching', '自动孵蛋'], ['mainline', '自动主线'], ['battles', '战斗记录'], ['gifts', '自动赠礼'],
['commissions', '自动委托'], ['exploration', '自动探险'], ['maps', '自动扫荡'], ['statistics', '数据分析'], ['plans', '执行计划'], ['yields', '收益资料'],
];
export const initialQuery = page => page === 'bag' ? {category: 'eggs'} : page === 'mainline' ? {category: 'mainline', state: 'current'} : page === 'ranch' ? {grouped: false} : page === 'maps' ? {category: 'all', only_unlocked: true} : {};
class LoginPage {
constructor(host, page) {
this.page = page;
this.root = el('div', {class: 'login-layout'});
this.autoReloginMessage = el('p', {role: 'status'});
this.autoReloginCountdown = el('p', {'data-auto-relogin-countdown': '', role: 'timer', 'aria-live': 'off', hidden: true});
this.autoReloginCredentials = el('p', {'data-auto-relogin-credentials': '', role: 'status', hidden: true,
text: '缺少服务端记住的账号和密码。请勾选“记住账号和密码”并完成登录,才能自动重登原区服角色。'});
this.autoReloginStatus = el('div', {class: 'page-summary', 'data-auto-relogin-status': ''}, this.autoReloginMessage, this.autoReloginCountdown, this.autoReloginCredentials);
this.account = el('input', {type: 'text', name: 'game-account', autocomplete: 'username', 'aria-label': '游戏账号'});
this.password = el('input', {type: 'password', name: 'game-password', autocomplete: 'current-password', 'aria-label': '游戏密码'});
this.remember = el('input', {type: 'checkbox', checked: true});
const show = el('input', {type: 'checkbox'});
this.showPassword = show;
show.addEventListener('change', () => { this.password.type = show.checked ? 'text' : 'password'; });
const field = (label, input) => el('label', {class: 'field'}, el('span', {class: 'field-label', text: label}), input);
const login = el('button', {type: 'submit', text: '账号密码登录 / 获取区服', class: 'primary'});
this.loginButton = login;
const form = el('form', {class: 'policy-form'}, field('第一步:游戏账号', this.account), field('密码', this.password),
el('div', {class: 'login-options'}, el('label', {}, this.remember, '记住账号和密码'), el('label', {}, show, '显示密码')),
el('div', {class: 'login-actions'}, login));
form.addEventListener('submit', async event => {
event.preventDefault();
if (!this.account.value.trim()) { this.account.focus(); return; }
const payload = {account: this.account.value.trim(), password: this.password.value, remember: this.remember.checked};
this.password.value = '';
login.disabled = true;
try { const result = await page.perform('login', payload); if (result) this.update(result); }
catch (error) { page.error(error); }
finally { login.disabled = false; }
});
this.servers = el('select', {'aria-label': '区服 / 角色'}, el('option', {value: '', text: '请先获取区服'}));
this.enter = el('button', {type: 'button', text: '进入选中区服', disabled: true, onClick: () => page.perform('enter_server', {server_id: this.servers.value}).catch(page.error)});
this.saved = el('select', {'aria-label': '已保存的账号 / 区服 / 角色'}, el('option', {value: '', text: '成功读取角色后自动保存会话'}));
this.restore = el('button', {type: 'button', text: '恢复选中会话(无需重新输密码)', disabled: true, onClick: () => page.perform('restore_session', {session_id: this.saved.value}).catch(page.error)});
this.root.append(form,
field('第二步:区服 / 角色', el('div', {class: 'server-row'}, this.servers, this.enter)),
el('p', {class: 'info-note', text: '账号验证 → 获取官方区服 → 选择区服 → 进入区服 → 读取角色。在线时默认自动刷新状态并自动执行已勾选功能;顶部“停止”仅暂停执行,重新登录和服务重启后仍保持暂停,直到再次“开启”。'}),
el('div', {class: 'session-block policy-form'}, field('已保存账号 / 区服 / 角色', this.saved), el('div', {class: 'login-actions'}, this.restore)),
el('div', {class: 'page-toolbar'}, el('button', {type: 'button', text: '退出登录', onClick: () => page.perform('logout').catch(page.error)}),
el('button', {type: 'button', text: '退出并清除登录记录…', onClick: () => page.options.command('forget-login', page.account)})),
el('p', {class: 'info-note', text: '记住的账号密码和登录会话由服务端加密保存。浏览器不会保存游戏凭据。账号登录并保存原区服、原角色后会持续保持登录:掉线、退出登录或服务重启,均按设定时长自动重登并恢复监控;默认等待 30 分钟,可修改为 10 分钟等时长。关闭页面不影响自动重登。只有“退出并清除登录记录”或删除账号才取消自动重登;手动停止的执行仍保持暂停。'}));
host.append(this.autoReloginStatus, this.root);
}
update(data) {
const login = data.login || data.details?.login || data;
if (login.account && !this.account.value && document.activeElement !== this.account) this.account.value = login.account;
if (login.has_saved_password !== undefined) {
this.hasSavedPassword = login.has_saved_password;
this.password.placeholder = login.has_saved_password ? '已在服务端加密保存;留空使用已保存密码' : '输入游戏密码';
}
if (Array.isArray(login.servers)) this.updateOptions(this.servers, login.servers.map(server => ({value: server.id ?? server.server_id, label: `${server.name}${server.role_name ? ` · ${server.role_name}` : ''}`})), '请先获取区服');
if (Array.isArray(login.saved_sessions)) this.updateOptions(this.saved, login.saved_sessions.map(session => ({value: session.id ?? session.session_id, label: session.label || [session.account, session.server_name || session.server, session.role_name || session.name].filter(Boolean).join(' · ')})), '暂无已保存会话');
this.enter.disabled = !this.servers.value;
this.restore.disabled = !this.saved.value;
this.updateStatus();
}
updateStatus() {
const status = this.page.account.summary?.auto_relogin_status;
const message = status?.message || '已保存的账号会持续自动重登,等待服务端状态;可设置重登等待时长。';
if (this.autoReloginMessage.textContent !== message) this.autoReloginMessage.textContent = message;
this.autoReloginCredentials.hidden = this.hasSavedPassword !== false;
const attemptAt = typeof status?.next_attempt_at === 'string' ? Date.parse(status.next_attempt_at) : NaN;
this.autoReloginCountdown.hidden = !Number.isFinite(attemptAt);
if (!this.autoReloginCountdown.hidden) {
const remaining = Math.max(0, Math.ceil((attemptAt - Date.now()) / 1000));
const countdown = remaining ? `${remaining} 秒后自动重新登录(${chinaTime(status.next_attempt_at, {date: true})},北京时间)` : '等待服务端执行自动重登';
if (this.autoReloginCountdown.textContent !== countdown) this.autoReloginCountdown.textContent = countdown;
}
}
updateOptions(select, options, placeholder) {
const signature = JSON.stringify(options);
if (select.dataset.signature === signature) return;
const previous = select.value;
select.replaceChildren(...options.map(option => el('option', {value: option.value, text: option.label})));
if (!options.length) select.append(el('option', {value: '', text: placeholder}));
if (options.some(option => String(option.value) === previous)) select.value = previous;
select.dataset.signature = signature;
}
clearPassword() { this.password.value = ''; this.password.type = 'password'; this.showPassword.checked = false; }
}
export class PageView {
constructor(account, key, options) {
this.account = account;
this.key = key;
this.options = options;
this.query = initialQuery(key);
this.filters = new Map();
this.data = null;
this.root = el('section', {class: 'page-panel', role: 'tabpanel', 'aria-label': PAGES.find(page => page[0] === key)[1], 'data-page': key, hidden: true});
this.header = el('div', {class: 'page-header'});
this.title = el('h2', {text: PAGES.find(page => page[0] === key)[1]});
this.loading = el('span', {class: 'page-loading', role: 'status', text: '正在读取…', 'data-loading': 'true'});
this.header.append(this.title, this.loading);
this.errorBox = el('div', {class: 'page-error', role: 'alert', hidden: true});
this.error = error => { this.showError(error.message || String(error)); notice(error.message || String(error), true); };
this.subtabs = el('div', {class: 'subtabs', role: 'tablist', 'aria-label': '子页面', hidden: true});
this.filterHost = el('div', {class: 'filter-bar'});
this.summary = el('p', {class: 'page-summary'});
this.runtimeStatus=el('div',{class:'page-summary',hidden:true});
this.formHost = el('div', {class: 'policy-form'});
this.actionsHost = el('div', {class: 'page-toolbar'});
this.content = el('div', {class: 'page-content'});
this.notes = el('div', {class: 'info-note'});
this.context = {get: (path, fallback) => getPath(account.config, path, fallback), set: (path, value, field, row) => options.edit(account, path, value, field, row),
dirty: path => account.edits.has(pathKey(path)), onError: this.error, onSelection: () => this.syncActions(),
onContext: (event, selected, row) => this.openContext(event, selected, row), onDetail: row => this.showDetail(row)};
this.form = new PolicyForm(this.formHost, this.context);
this.root.append(this.header, this.errorBox, this.subtabs, this.filterHost, this.summary, this.runtimeStatus, this.formHost, this.actionsHost, this.content, this.notes);
if (key === 'login') this.login = new LoginPage(this.content, this);
tabKeys(this.subtabs, '.subtab');
}
perform(operation, payload = {}) { return this.options.perform(this.account, operation, payload, {page: this}); }
showError(message) { this.errorBox.replaceChildren(el('span', {text: message}), el('button', {text: '重新读取', type: 'button', onClick: () => this.options.load(this, true)})); this.errorBox.hidden = false; }
clearError() { this.errorBox.hidden = true; }
setQuery(key, value) {
if (this.query[key] === value) return;
this.query[key] = value;
this.generation = (this.generation || 0) + 1;
clearTimeout(this.queryTimer);
this.queryTimer = setTimeout(() => this.options.load(this, true), key === 'search' ? 220 : 0);
}
updateFilters(filters) {
const included = new Set();
filters.forEach(field => {
if (this.key === 'bag' && field.key === 'category') return;
included.add(field.key);
if (!Object.hasOwn(this.query, field.key)) this.query[field.key] = field.value;
let item = this.filters.get(field.key);
const signature = JSON.stringify({...field, value: undefined});
if (!item || item.signature !== signature && !item.root.contains(document.activeElement)) {
const entry = control({...field, type: field.type === 'text' ? 'text' : field.type, path: [field.key]}, {
get: () => this.query[field.key] ?? field.value,
set: (_, value) => this.setQuery(field.key, value), onError: this.error,
});
if (field.key === 'search') { entry.root.type = 'search'; entry.root.placeholder = this.key === 'maps' ? '关卡、名称或掉落物品' : '按名称或编号筛选'; }
const root = el('label', {}, el('span', {text: field.label}), entry.root);
item?.root.remove();
item = {root, entry, signature};
this.filters.set(field.key, item);
this.filterHost.append(root);
}
item.entry.sync();
});
for (const [key, item] of this.filters) if (!included.has(key)) { item.root.remove(); this.filters.delete(key); }
this.filterHost.hidden = !included.size;
}
updateSubtabs(data) {
let tabs = data.tabs || [];
if (this.key === 'bag') tabs = [{key:'eggs',title:'魔物蛋'}, {key:'usable',title:'可使用'}, {key:'consumables',title:'消耗品'}, {key:'materials',title:'材料'}, {key:'other',title:'其他'}, {key:'equipment',title:'装备'}];
if (!tabs.length && this.key === 'hatching') tabs = ['孵蛋策略','牧场策略','喂养策略'].map(title => ({key:title,title}));
if (!tabs.length && this.key === 'mainline') tabs = [{key:'tasks',title:'任务状态'}, {key:'policy',title:'推进策略'}];
const signature = JSON.stringify(tabs);
if (this.tabSignature !== signature) {
if (!this.activeSubtab || !tabs.some(tab => tab.key === this.activeSubtab)) this.activeSubtab = this.key === 'bag' ? this.query.category || tabs[0]?.key : tabs[0]?.key;
this.subtabs.replaceChildren(...tabs.map(tab => el('button', {type: 'button', class: 'subtab', role: 'tab', 'data-key': tab.key, text: tab.title || tab.label,
onClick: () => { this.activeSubtab = tab.key; if (this.key === 'bag') this.setQuery('category', tab.key); this.render(this.data || data); }})));
this.tabSignature = signature;
}
$$('.subtab', this.subtabs).forEach(button => { const selected = button.dataset.key === this.activeSubtab; button.setAttribute('aria-selected', selected); button.tabIndex = selected ? 0 : -1; });
this.subtabs.hidden = !tabs.length;
}
selectedRows() { return this.table?.selectedRows() || []; }
updateActions(actions) {
const operations = [...actions];
if(this.key==='hatching'){
if(this.data?.details?.preset)operations.push({operation:'apply_preset',label:this.data.details.preset.label});
operations.push({operation:'configure_bag',label:'去背包配置孵蛋规则'});
}
if(this.key==='gifts')operations.push({operation:'configure_bag',label:'去背包选择物品'},{operation:'configure_ranch',label:'去牧场选择目标'});
if(this.key==='ranch')operations.push({operation:'reveal_breakthrough',label:'潜能突破设置'});
if (this.key === 'yields') {
if (!operations.some(action => action.operation === 'import_yields')) operations.push({operation: 'import_yields', label: '导入自定义 CSV / XLSX'});
operations.push({operation: 'download_yields', label: '下载收益 CSV'});
}
if (this.key === 'maps') operations.push({operation: 'expand_regions', label: '展开地区'}, {operation: 'collapse_regions', label: '折叠地区'});
const signature = JSON.stringify(operations);
if (signature !== this.actionSignature) {
this.actionsHost.replaceChildren();
operations.filter(action => !['login', 'enter_server', 'restore_session', 'logout', 'forget_login'].includes(action.operation)).forEach(action => {
const currencies = action.currencies ? optionsList(action.currencies) : [null];
currencies.forEach(currency => {
const button = el('button', {type: 'button', text: `${action.label}${currency ? `(${currency.label})` : ''}`, 'data-operation': action.operation,
'data-selection': action.selection, onClick: () => this.options.action(this, action, currency?.value).catch(this.error)});
this.actionsHost.append(button);
});
});
this.actionSignature = signature;
}
this.syncActions();
}
syncActions() {
const selected = this.selectedRows().length > 0;
$$('button[data-selection]', this.actionsHost).forEach(button => { button.disabled = !selected; });
}
render(data, loading = false) {
if (!data) { this.loading.textContent = '正在读取…'; this.loading.dataset.loading = 'true'; return; }
this.data = data;
this.loading.dataset.loading = String(loading);
this.loading.textContent = loading ? '后台更新中…' : '已载入';
this.updateSubtabs(data);
this.updateFilters(data.filters || []);
this.summary.textContent = typeof data.summary === 'string' ? data.summary : textValue(data.summary || '');
this.updateRuntimeStatus(data.details || {});
let fields = data.form || this.options.schema(this.key);
if (this.key === 'login') fields = fields.filter(field => !(field.path?.[0] === 'auto_relogin' && field.path[1] === 'enabled'));
fields=fields.map(field=>field.path?.[0]==='policy'&&field.path[1]==='buy_ten'?{...field,disabled:!this.account.config?.policy?.allow_single_draw}:field);
if (this.key === 'hatching' && this.activeSubtab) fields = fields.filter(field => !field.group || field.group === this.activeSubtab);
const policyTab = this.key === 'mainline' && ['policy', 'settings', '推进策略'].includes(this.activeSubtab);
this.form.update(this.key === 'mainline' && !policyTab ? [] : fields);
this.updateActions(data.actions || []);
if (this.login) { this.login.update(data); return; }
this.content.hidden = policyTab;
if (policyTab) return;
const notes = data.notes || data.details?.note || data.details?.notes || data.details?.help || data.hint || '';
const noteText=Array.isArray(notes)?notes.join('\n'):typeof notes==='string'?notes:textValue(notes);
this.notes.textContent=[noteText,...(data.battle_mode?[data.battle_mode.label,data.battle_mode.damage_rule]:[])].filter(Boolean).join('\n');
this.notes.style.whiteSpace = 'pre-wrap';
this.notes.hidden = !this.notes.textContent;
const groups = data.groups || [];
const grouped = this.key === 'maps' || this.key === 'ranch' && (this.query.grouped === true || this.query.grouped === 'true');
const mode = this.key === 'statistics' ? 'statistics' : grouped ? 'grouped' : 'table';
if (this.contentMode !== mode) {
if (this.content.contains(document.activeElement)) return;
this.content.replaceChildren();
this.contentMode = mode;
this.table = mode === 'grouped' ? new GroupedTables(this.content, this.context, {collapsed: this.key === 'maps'}) : mode === 'table' ? new DataTable(this.content, this.context, {emptyMessage: this.key === 'plans' ? '当前没有执行计划。请配置策略并刷新 / 预览,查看下一步或等待原因。' : '当前筛选下没有条目。可调整筛选,或登录后刷新状态。'}) : null;
if (mode === 'statistics') this.buildStatistics();
}
if (mode === 'statistics') this.renderStatistics(data);
else if (grouped) {
const labels = Object.fromEntries(groups.map(group => [String(group.id), group.label || group.name]));
this.table.update(data.columns || [], data.rows || [], row => row.group ?? row.region ?? row.city_name ?? row.city ?? '其他', labels, Object.fromEntries(groups.map(group=>[String(group.id),group])));
} else this.table.update(data.columns || [], data.rows || []);
}
updateRuntimeStatus(details) {
const lines=[];
if(this.key==='hatching'){
if(this.activeSubtab==='喂养策略' && Array.isArray(details.feed_status))lines.push(['feed_status','当前喂养状态:'+textValue(details.feed_status[1])]);
if(this.activeSubtab==='孵蛋策略' && details.last_draw!==undefined)lines.push(['last_draw','最近抽蛋:'+textValue(details.last_draw)]);
}
if(this.key==='gifts' && Object.hasOwn(details,'next_ready_at')){
const ready=details.next_ready_at;
lines.push(['next_ready_at',ready===null?'下次赠礼:当前没有符合条件的目标或物品,等待状态更新':'下次可赠礼:'+chinaTime(ready,{date:true})+'(北京时间)']);
}
this.runtimeStatus.replaceChildren(...lines.map(([key,text])=>el('p',{'data-view-status':key,text})));
this.runtimeStatus.hidden=!lines.length;
}
showDetail(row) {
const data = this.data.details?.[row.id] || row.details;
if (!data) return;
const labels = {name:'名称',species:'种类',id:'魔物ID',level:'等级 / 当前上限',quality:'资质 攻/防/血/敏',reference_stats:'参考攻击 / 防御 / 生命 / 敏捷',growth:'成长数值',likes:'喜欢的物品',feel:'好感 / 上限',feed_exp:'喂养经验',scope:'管理范围'};
const title=this.key==='ranch'?'魔物详情':this.key==='mainline'?'任务详情':this.key==='battles'?'战斗详情':'详情';
dialog(title, el('div', {class:'detail-sections'}, detailsList(data, labels), this.key==='ranch'?el('p', {class:'info-note',text:'参考属性不含装备、羁绊或全局加成。'}):null), {info:true});
}
openContext(event, selected, row) {
const items = [{label:'刷新本页',run:()=>this.perform('refresh',{page:this.key})}];
if (this.key === 'ranch') {
items.push({label:'查看魔物详情',run:()=>this.showDetail(row)});
(this.data.actions || []).filter(action => ['lock','unlock','sell','feed'].includes(action.operation)).forEach(action => items.push({label:action.label,disabled:!selected.length,run:()=>this.options.action(this,action)}));
}
(this.data.actions || []).filter(action => action.operation === 'quote_expansion').forEach(action => optionsList(action.currencies).forEach(currency => items.push({label:`${action.label}(${currency.label})…`,run:()=>this.options.action(this,action,currency.value)})));
contextMenu(event,items);
}
buildStatistics() {
this.statisticsPicker = el('div', {class:'statistics-picker',role:'listbox','aria-label':'关卡 / 难度'});
this.chart = el('div',{class:'chart-scroll','aria-label':'掉落统计图'});
this.statisticsTableHost = el('div',{class:'statistics-table-host'});
this.statisticsTable = new DataTable(this.statisticsTableHost,this.context,{selection:false,emptyMessage:'所选关卡尚无已确认样本;完成扫荡后将显示实际统计。'});
this.statisticsSummary = el('p',{class:'page-summary'});
this.content.append(el('div',{class:'statistics-layout'},this.statisticsPicker,el('div',{class:'statistics-main'},this.statisticsSummary,this.chart,this.statisticsTableHost)));
}
renderStatistics(data) {
const stages = data.stages || data.details?.stages || data.details?.tree || [];
const signature = JSON.stringify(stages);
if (signature !== this.statisticsSignature) {
const openCities=new Set($$('.statistics-city[open]',this.statisticsPicker).map(node=>node.dataset.city));
const openStages=new Set($$('.statistics-stage[open]',this.statisticsPicker).map(node=>node.dataset.stage));
this.statisticsPicker.replaceChildren();
const cities = new Map();
stages.forEach(stage => {
const id=String(stage.city_id || '0');
if(!cities.has(id))cities.set(id,{name:stage.city_name || `地区 ${id}`,stages:[]});
cities.get(id).stages.push(stage);
});
cities.forEach((city,id)=>{
const children=el('div',{class:'statistics-city-children'});
const cityRoot=el('details',{class:'statistics-city','data-city':id},el('summary',{text:`${city.name}(${city.stages.length})`}),children);
const buildCity=()=>{
if(children.childElementCount)return;
city.stages.forEach(stage=>{
const levelsHost=el('div',{class:'statistics-levels'});
const stageRoot=el('details',{class:'statistics-stage','data-stage':stage.id},el('summary',{text:`${stage.label || stage.name || stage.id} ${stage.sweep || 0} / ${stage.event || 0}`}),levelsHost);
const buildLevels=()=>{
if(levelsHost.childElementCount)return;
(stage.levels || []).forEach(level=>levelsHost.append(el('button',{type:'button',role:'option','data-stat-stage':stage.id,'data-stat-level':level.level || level.id,
text:`难度 ${level.level || level.id} 扫荡 ${level.sweep || 0} / 事件 ${level.event || 0}`,onClick:()=>{
this.query.stage_id=stage.id;delete this.query.stage;this.query.level=level.level || level.id || '3';
this.generation=(this.generation || 0)+1;this.options.load(this,true);
}})));
};
stageRoot.addEventListener('toggle',()=>{if(stageRoot.open)buildLevels();});
if(openStages.has(stage.id)||(this.query.stage_id || this.query.stage)===stage.id){stageRoot.open=true;buildLevels();}
children.append(stageRoot);
});
};
cityRoot.addEventListener('toggle',()=>{if(cityRoot.open)buildCity();});
if(openCities.has(id)||city.stages.some(stage=>(this.query.stage_id || this.query.stage)===stage.id)){cityRoot.open=true;buildCity();}
this.statisticsPicker.append(cityRoot);
});
this.statisticsSignature = signature;
}
$$('[data-stat-stage]',this.statisticsPicker).forEach(button=>button.setAttribute('aria-selected',String(button.dataset.statStage===(this.query.stage_id || this.query.stage)&&button.dataset.statLevel===String(this.query.level || '3'))));
this.statisticsPicker.hidden = !stages.length;
this.statisticsSummary.textContent = data.details?.summary ? textValue(data.details.summary) : '';
const rows = data.rows || [];
this.statisticsTable.update(data.columns || [],rows);
const metric = this.query.metric || this.query.chart_metric || 'rate';
const series = data.chart?.series || data.chart || data.details?.chart;
const bars = Array.isArray(series) ? series.map(item=>({label:item.label || item.name,value:item.value})) : rows.map(row=>({label:row.name || row.item_name || row.item || row.id,value:metric === 'per_stamina' ? row.per_stamina ?? row.per_ti : row.rate ?? row.drop_rate}));
this.drawChart(bars,metric,data.chart?.max,data.chart?.empty_reason);
}
drawChart(bars,metric,axisMax,emptyReason) {
bars = bars.filter(item=>typeof item.value === 'number' && Number.isFinite(item.value));
const signature = JSON.stringify([bars,metric,axisMax,emptyReason]);
if (this.chartSignature === signature) return;
this.chartSignature = signature;
this.chart.replaceChildren();
if (!bars.length) { this.chart.append(empty(emptyReason || '暂无已确认的统计样本。图表将随实际扫荡记录生成。')); return; }
const ns='http://www.w3.org/2000/svg', width=760, height=Math.max(120,bars.length*29+50), labelWidth=175;
const svg=document.createElementNS(ns,'svg');
svg.setAttribute('viewBox',`0 0 ${width} ${height}`);svg.setAttribute('class','drop-chart');svg.setAttribute('role','img');svg.setAttribute('aria-label',metric==='per_stamina'?'每点体力掉落数量':'实测掉落率');
const title=document.createElementNS(ns,'title');title.textContent=metric==='per_stamina'?'每点体力掉落数量':'实测掉落率';svg.append(title);
const max=typeof axisMax==='number'&&axisMax>0?axisMax:metric==='rate'?1:Math.max(...bars.map(item=>item.value),.0001)*1.15, plotWidth=width-labelWidth-85;
for(let tick=0;tick<=4;tick++){
const x=labelWidth+tick/4*plotWidth;
const line=document.createElementNS(ns,'line');line.setAttribute('x1',String(x));line.setAttribute('x2',String(x));line.setAttribute('y1','24');line.setAttribute('y2',String(height-12));line.setAttribute('class','chart-grid');svg.append(line);
const label=document.createElementNS(ns,'text');label.setAttribute('x',String(x));label.setAttribute('y','15');label.setAttribute('text-anchor','middle');label.setAttribute('class','chart-axis');label.textContent=metric==='rate'?`${Math.round(tick/4*max*100)}%`:number(tick/4*max);svg.append(label);
}
bars.forEach((item,index)=>{
const y=index*29+33;
const text=document.createElementNS(ns,'text');text.setAttribute('x',String(labelWidth-10));text.setAttribute('y',String(y+13));text.setAttribute('text-anchor','end');text.setAttribute('class','chart-label');text.textContent=String(item.label);svg.append(text);
const rect=document.createElementNS(ns,'rect');rect.setAttribute('x',String(labelWidth));rect.setAttribute('y',String(y));rect.setAttribute('width',String(item.value/max*plotWidth));rect.setAttribute('height','19');rect.setAttribute('class','chart-bar');
const tip=document.createElementNS(ns,'title');tip.textContent=`${item.label}:${metric==='per_stamina'?number(item.value):(item.value*100).toFixed(2)+'%'}`;rect.append(tip);svg.append(rect);
const value=document.createElementNS(ns,'text');value.setAttribute('x',String(labelWidth+item.value/max*plotWidth+7));value.setAttribute('y',String(y+13));value.setAttribute('class','chart-value');value.textContent=metric==='per_stamina'?number(item.value):(item.value*100).toFixed(2)+'%';svg.append(value);
});
this.chart.append(svg);
}
}