feat: redesign the web console with Vue and isolated account workspaces

This commit is contained in:
AttilaNet
2026-11-11 09:35:54 +08:00
parent 99aff423d8
commit ff6a828f58
46 changed files with 4549 additions and 748 deletions
-530
View File
@@ -1,530 +0,0 @@
import {api, request} from './api.js';
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';
const state = {accounts:new Map(),active:null,schema:null,meta:null,ready:false,polling:false,seq:0,redirecting:false};
const current = () => state.accounts.get(state.active);
const currentPage = () => { const account=current(); return account?.pages.get(account.page); };
const terminal = new Set(['succeeded','failed','cancelled']);
const jobLabels = {queued:'排队中',running:'执行中',succeeded:'已完成',failed:'失败',cancelled:'已取消'};
const operationLabels = {login:'登录',enter_server:'进入区服',restore_session:'恢复会话',refresh:'刷新 / 预览',start:'开启策略',stop:'停止策略',set_config:'保存配置',import_config:'导入策略',import_yields:'导入收益',claim_daily:'领取每日奖励',quote_expansion:'读取扩建费用',expand:'扩建',sell:'派遣',feed:'喂养',lock:'锁定',unlock:'解锁'};
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};
}
function setStatus(message) { $('#status-text').textContent=message; $('#status-text').title=message; }
function error(error) { if(state.redirecting)return;notice(error.message || String(error),true); setStatus(error.message || String(error)); }
function renderAccountTabs() {
const root=$('#account-tabs');
for (const child of [...root.children]) if (!state.accounts.has(child.dataset.account)) child.remove();
state.accounts.forEach(account=>{
let button=[...root.children].find(child=>child.dataset.account===account.id);
if (!button) {
button=el('button',{type:'button',class:'account-tab',role:'tab','data-account':account.id,onClick:()=>selectAccount(account.id)},el('span',{class:'account-dot'}),el('span',{class:'account-label'}));
root.append(button);
}
const summary=account.summary, selected=state.active===account.id;
$('.account-label',button).textContent=summary.label || summary.player?.name || '账号';
$('.account-dot',button).className=`account-dot${summary.error?' error':summary.running?' running':''}`;
button.setAttribute('aria-selected',String(selected));button.tabIndex=selected?0:-1;
button.title=`${summary.label || '账号'}${summary.demo?' · 离线演示':''}${summary.running?' · 策略运行中':''}${summary.error?' · '+summary.error:''}`;
});
}
function syncSaveStatus(account=current()) {
if (!account || account.id!==state.active) return;
const node=$('#save-status');
const message=account.saveError?'保存失败 · 点击重试':account.savePromise?'保存中…':account.edits.size?'修改待保存…':account.config?'策略已自动保存':'配置载入中…';
node.textContent=message;node.title=account.saveError || message;node.className=account.saveError?'failed':account.edits.size||account.savePromise?'pending':'';
}
function renderSummary() {
const account=current(),summary=account?.summary,player=summary?.player || {};
const connected=summary?.connected,demo=summary?.demo;
$('#connection').textContent=demo?'离线演示':connected?'已登录':'未登录';
$('#connection').className=`connection${demo?' demo':connected?' online':''}`;
$('#player-name').textContent=player.name || '—';$('#player-name').title=player.name || '';
for (const [id,key] of [['player-level','level'],['player-money','money'],['player-ke','ke'],['player-ti','ti']]) $('#'+id).textContent=number(player[key]);
$('#player-exp').textContent=player.exp==null?'—':`${number(player.exp)} / ${number(player.next_exp)}`;
$('#experience-progress').max=Math.max(1,Number(player.next_exp)||1);$('#experience-progress').value=Number(player.exp)||0;
const run=$('#strategy-toggle');run.textContent=summary?.running?'停止':'开启';run.classList.toggle('running',Boolean(summary?.running));run.disabled=!account || !account.config || !connected && !demo;
run.setAttribute('aria-pressed',String(Boolean(summary?.running)));
run.title=summary?.running?'停止自动执行已勾选功能;取消尚未发送的请求':'开启后自动执行各页面已勾选功能';
if (account?.config && document.activeElement!==$('#refresh-interval')) $('#refresh-interval').value=String(account.config.interval);
$('#refresh-interval').disabled=!account?.config;
$('#refresh').disabled=!account;
const task=account?[...account.jobs.values()].at(-1)?.job:null;
$('#job-status').textContent=task?`${operationLabels[task.operation] || task.operation} · ${jobLabels[task.status]}`:summary?.busy?'后台任务执行中':'';
$('#data-summary').textContent=summary?.error || (demo?'当前为离线演示,不连接游戏服务器。':connected?'角色状态自动刷新;配置功能后开启策略。':'请在登录页输入账号密码,或恢复已保存会话。');
syncSaveStatus(account);
}
async function refreshConfig(account) {
if (account.loadingConfig) return;
account.loadingConfig=true;
try {
const response=await api.config(account.id);
account.config=clone(response.config);account.revision=response.revision;
account.edits.forEach(edit=>applyEdit(account.config,edit));
account.pages.forEach(page=>page.data&&page.render(page.data));
if (account.id===state.active) {renderSummary();applyLogLayout(account);}
} finally {account.loadingConfig=false;}
}
function applyEdit(config,edit) {
if(!edit.ifMissing || getPath(config,edit.path)===undefined)setPath(config,edit.path,edit.value);
}
function writeEdit(account,path,value,{ifMissing=false}={}) {
if(ifMissing && (getPath(account.config,path)!==undefined || account.edits.get(pathKey(path))?.ifMissing===false))return;
setPath(account.config,path,value);
account.edits.set(pathKey(path),{path:[...path],value:clone(value),seq:++state.seq,ifMissing});
}
function editConfig(account,path,value,field={},row) {
if (!account.config) throw new Error('配置尚未载入,请稍后再试。');
if (row?.rule_path && row.rule_defaults)Object.entries(row.rule_defaults).forEach(([key,value])=>writeEdit(account,[...row.rule_path,key],value,{ifMissing:true}));
writeEdit(account,path,value);
// Preserve the desktop's linked switches when enabling an individual rule.
if (path[0]==='policy') {
const section=path[1];
if (section==='egg_rules') {
const rule=getPath(account.config,path.slice(0,3),{});
if (rule.enabled && ['enabled','action'].includes(path[3])) {
if (rule.action==='sell') writeEdit(account,['policy','dispatch'],true);
else {writeEdit(account,['policy','collect'],true);if(rule.action==='feed')writeEdit(account,['policy','feed'],true);}
}
}
if (section==='gift_items'&&value===true) writeEdit(account,['policy','gift_enabled'],true);
if (section==='feed_targets'&&value!==undefined) {writeEdit(account,['policy','feed'],true);writeEdit(account,['policy','collect'],true);}
if (section==='gift_targets'&&value!==undefined) writeEdit(account,['policy','gift_enabled'],true);
}
account.saveError=null;clearTimeout(account.saveTimer);
account.saveTimer=setTimeout(()=>flushConfig(account).catch(error),500);
syncSaveStatus(account);
// Update other controls, while every control protects its own focused input.
account.pages.forEach(page=>page.data&&page.render(page.data));
if (path[0]==='log_visible'||path[0]==='log_sizes') applyLogLayout(account);
}
async function flushConfig(account=current()) {
if (!account) return;
clearTimeout(account.saveTimer);
if (account.savePromise) {await account.savePromise;if(account.edits.size)return flushConfig(account);return;}
if (!account.edits.size) return;
const invalid=account.pages.get(account.page)?.root.querySelector(':invalid');
if (invalid) {invalid.reportValidity();throw new Error('请先补全当前输入,再保存或开启策略。');}
const sent=[...account.edits.values()].map(clone),config=clone(account.config);
account.saveError=null;
account.savePromise=(async()=>{
try {
let response=await api.save(account.id,config,account.revision);
if (response.pending && response.job_id) {
const result=await trackJob(account,response.job || {id:response.job_id,status:'queued',operation:'set_config'});
response=result?.config?result:await api.config(account.id);
}
if (!response?.config) response=await api.config(account.id);
sent.forEach(edit=>{if(account.edits.get(pathKey(edit.path))?.seq===edit.seq)account.edits.delete(pathKey(edit.path));});
account.config=clone(response.config);account.revision=response.revision;
account.edits.forEach(edit=>applyEdit(account.config,edit));
account.saveError=null;
} catch(failure) {
if(failure.status===409){
const latest=await api.config(account.id);account.config=clone(latest.config);account.revision=latest.revision;
account.edits.forEach(edit=>applyEdit(account.config,edit));
account.saveError='配置已被另一浏览器更新。已保留你修改的字段,请点击保存状态重试。';
} else account.saveError=failure.message;
throw new Error(account.saveError);
} finally {account.savePromise=null;syncSaveStatus(account);renderSummary();}
})();
syncSaveStatus(account);
await account.savePromise;
if(account.edits.size)return flushConfig(account);
account.pages.forEach(page=>page.data&&page.render(page.data));
const page=account.pages.get(account.page);if(page)loadPage(page,true);
}
function trackJob(account,job) {
if (!job?.id || !job.status) return Promise.resolve(job);
if (terminal.has(job.status)) return job.status==='succeeded'?Promise.resolve(job.result):Promise.reject(new Error(job.error || jobLabels[job.status]));
if(account.jobs.has(job.id))return account.jobs.get(job.id).promise;
let resolve,reject;
const promise=new Promise((yes,no)=>{resolve=yes;reject=no;});
const record={job,promise,resolve,reject,polling:false};account.jobs.set(job.id,record);
pollJob(account,record);renderSummary();
return promise;
}
async function pollJob(account,record) {
if(record.polling)return;record.polling=true;
try {
const job=await api.job(account.id,record.job.id);record.job=job;
if(terminal.has(job.status)){
account.jobs.delete(job.id);
if(job.status==='succeeded')record.resolve(job.result);
else record.reject(new Error(job.error || '任务已取消'));
}
}catch(failure){if([400,401,403,404].includes(failure.status)){account.jobs.delete(record.job.id);record.reject(failure);}}
finally{record.polling=false;renderSummary();}
}
async function perform(account,operation,payload={},options={}) {
if(!account)throw new Error('请先新增或选择一个账号。');
if(operation==='start'){
const invalid=account.pages.get(account.page)?.root.querySelector(':invalid');
if(invalid){invalid.reportValidity();throw new Error('请先完成当前输入,再开启策略。');}
}
if(operation!=='stop')await flushConfig(account);
const job=await api.action(account.id,operation,payload);
setStatus(`${operationLabels[operation] || '操作'}:${jobLabels[job.status] || '已提交'}`);
const result=await trackJob(account,job);
if(!state.accounts.has(account.id))return result;
if(result?.config){account.config=clone(result.config);account.revision=result.revision;}
if(['enter_server','restore_session','logout','forget_login','import_config','import_yields'].includes(operation))await refreshConfig(account);
account.summary=await api.status(account.id);
renderAccountTabs();renderSummary();
const page=options.page || account.pages.get(account.page);if(page)await loadPage(page,true);
if(operation==='login'&&result)account.pages.get('login')?.login?.update(result);
if(operation==='enter_server'||operation==='restore_session')notice('已读取角色。策略保持关闭,请配置功能后开启。');
else if(result?.message)notice(result.message);
setStatus(result?.message || `${operationLabels[operation] || '操作'}已完成`);
return result;
}
function getPage(account,key) {
if(!account.pages.has(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);
}
return account.pages.get(key);
}
async function loadPage(page,force=false) {
if(page.fetching){if(force)page.reload=true;return;}
page.fetching=true;const generation=page.generation || 0;
try {
const response=await api.view(page.account.id,page.key,page.query);
if(generation!==(page.generation||0))return;
page.clearError();page.render(response.data,response.loading);page.lastLoad=Date.now();
if(response.loading){clearTimeout(page.loadTimer);page.loadTimer=setTimeout(()=>loadPage(page),650);}
}catch(failure){page.showError(failure.message);}
finally{page.fetching=false;if(page.reload){page.reload=false;loadPage(page);}}
}
function selectPage(key) {
const account=current();if(!account)return;
if(account.page!==key)account.pages.get(account.page)?.login?.clearPassword();
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-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?.edits.size)flushConfig(previous).catch(error);
state.active=id;const account=current();if(!account)return;
$('#page-host').querySelector('.initial-state')?.remove();
renderAccountTabs();renderSummary();renderLogs(true);applyLogLayout(account);selectPage(account.page);
if(!account.config)try{await refreshConfig(account);}catch(failure){error(failure);}
fetchLogs(account);
}
async function addAccount(demo=false) {
const label=el('input',{type:'text','aria-label':'账号页签名称',placeholder:demo?'离线演示':'账号名称(可留空)',maxlength:80});
const result=await dialog(demo?'新增离线演示账号':'新增账号',el('div',{},el('label',{class:'field'},el('span',{class:'field-label',text:'账号名称'}),label),el('p',{class:'info-note',text:demo?'使用服务端离线演示状态,不连接游戏服务器。':'创建独立账号工作区,然后在登录页连接游戏角色。'})),{confirm:'新增',read:()=>({label:label.value.trim()})});
if(!result)return;
const summary=await api.create(result.label,demo);state.accounts.set(summary.id,makeAccount(summary));await selectAccount(summary.id);notice(demo?'离线演示账号已创建':'账号已创建,请在登录页登录。');
}
async function pageAction(page,action,currency) {
const account=page.account,operation=action.operation;
if(operation==='configure_bag'||operation==='configure_ranch'){selectPage(operation==='configure_bag'?'bag':'ranch');return;}
if(operation==='reveal_breakthrough'){page.root.querySelector('th[data-column=breakthrough_selected]')?.scrollIntoView({block:'nearest',inline:'center'});return;}
if(operation==='apply_preset'){
const preset=page.data.details.preset;
if(account.summary.running)await perform(account,'stop');
Object.entries(preset.patch || {}).forEach(([section,fields])=>Object.entries(fields).forEach(([key,value])=>editConfig(account,[section,key],value)));
editConfig(account,['policy','egg_rules'],preset.egg_rules);
await flushConfig(account);notice('预设已保存。开启顶部策略后运行。');return;
}
if(operation==='expand_regions'||operation==='collapse_regions'){page.table?.expand(operation==='expand_regions');return;}
if(operation==='import_yields'){return importYields(account);}
if(operation==='download_yields'){return exportYields(account);}
const payload=clone(action.payload || {}),selected=page.selectedRows();
if(action.selection==='monster_ids'){
if(!selected.length)throw new Error('请先选择一只或多只魔物。');
payload.monster_ids=selected.map(row=>Number(row.id));
}
if(operation==='quote_expansion'){
payload.currency=currency || 'money';
if(payload.kind==='stack'&&selected.length)payload.position=Number(selected[0].position ?? selected[0].id);
const quote=await perform(account,'quote_expansion',payload,{page});
if(await confirm(payload.kind==='stack'?'确认开启坑位':'确认新建牧场',`${quote.description}\n确认消费并开通?`,{confirm:'确认消费',danger:true}))return perform(account,'expand',{quote_id:quote.quote_id,confirm:true},{page});
return;
}
if(operation==='feed'){
const options=optionsList(action.target_options || page.data.feed_targets).filter(option=>!payload.monster_ids.includes(Number(option.value)));
if(!options.length)throw new Error('没有可接收经验的目标魔物,请检查当前突破上限。');
const select=el('select',{'aria-label':'喂养目标'},...options.map(option=>el('option',{value:option.value,text:option.label})));
const result=await dialog('确认喂养',el('div',{},el('p',{text:`将选中 ${selected.length} 只魔物作为经验素材,无法撤销。`}),el('label',{class:'field'},el('span',{class:'field-label',text:'喂养目标'}),select)),{confirm:'确认喂养',danger:true,read:()=>({target_id:Number(select.value)})});
if(!result)return;payload.target_id=result.target_id;payload.confirm=true;
}else if(action.confirm || operation==='reset_map_pending'){
if(!await confirm(action.label,`${action.confirm || '仅在游戏内核对后处理未完成记录;缺少服务器结算证据时将保留记录。'}${selected.length?'\n已选择 '+selected.length+' 项':''}`,{confirm:'确认',danger:true}))return;
payload.confirm=true;
}
return perform(account,operation,payload,{page});
}
async function importYields(account=current()) {
const file=await filePicker('.csv,.xlsx');if(!file)return;
if(file.size>8*1024*1024)throw new Error('收益资料文件最大为 8 MiB。');
const result=await perform(account,'import_yields',{filename:file.name,content_base64:await fileBase64(file)});
notice(result?.message || '收益资料已导入并保存。');
}
async function exportYields(account=current()) {
if(!account)throw new Error('请先选择账号。');
const page=getPage(account,'yields');await loadPage(page,true);
const deadline=Date.now()+30000;
while(!page.data?.columns?.length&&Date.now()<deadline){await new Promise(resolve=>setTimeout(resolve,250));await loadPage(page);}
if(!page.data?.columns?.length)throw new Error('收益资料尚未载入,请稍后重试。');
const columns=[{key:'type_id',label:'编号'},{key:'name',label:'名称'},{key:'star',label:'星'},{key:'time_total',label:'孵化秒数'},{key:'sell_money',label:'派遣金币'},{key:'sell_exp',label:'强化经验'},{key:'gold_per_hour',label:'金币/小时'},{key:'exp_per_hour',label:'经验/小时'}];
download(csvBlob(columns,page.data.rows || []),'牧场收益资料.csv');
}
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.0.dev1'}`}),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==='save'){await flushConfig(account);notice('策略已保存。');return;}
if(name==='stop'||name==='start')return await perform(account,name);
if(name==='start-all'||name==='stop-all'){await Promise.all([...state.accounts.values()].map(item=>perform(item,name==='start-all'?'start':'stop')));return;}
if(name==='logout')return await perform(account,'logout');
if(name==='forget-login'){
if(await confirm('退出并清除登录记录','将退出当前角色,删除当前账号保存的登录会话和账号密码。培养策略和其他账号不受影响。',{confirm:'清除登录记录',danger:true}))await perform(account,'forget_login');return;
}
if(name==='remove-account'){
if(!await confirm('移除当前账号',`移除“${account.summary.label || '当前账号'}”及其保存的会话和策略?此操作无法撤销。`,{confirm:'移除账号',danger:true}))return;
await api.remove(account.id);account.jobs.forEach(record=>record.reject(new Error('账号已移除')));account.pages.forEach(page=>{clearTimeout(page.loadTimer);page.root.remove();});clearTimeout(account.saveTimer);state.accounts.delete(account.id);state.active=null;
if(state.accounts.size)await selectAccount(state.accounts.keys().next().value);else showNoAccounts();renderAccountTabs();renderSummary();return;
}
if(name==='export-config'){
await flushConfig(account);const result=await trackJob(account,await api.exportConfig(account.id));
download(new Blob([JSON.stringify(result,null,2)],{type:'application/json'}),'牧场策略.json');return;
}
if(name==='import-config'){
const file=await filePicker('.json');if(!file)return;if(file.size>1024*1024)throw new Error('策略文件过大。');
let config;try{config=JSON.parse(await file.text());}catch{throw new Error('策略文件不是有效的 JSON。');}
if(!await confirm('导入当前账号策略','将替换当前账号策略,策略运行保持关闭。',{confirm:'导入策略'}))return;
await flushConfig(account);const result=await trackJob(account,await api.importConfig(account.id,config));await refreshConfig(account);notice('策略已导入,运行保持关闭。');await loadPage(getPage(account,account.page),true);return result;
}
if(name==='import-yields')return await importYields(account);
if(name==='export-yields')return await exportYields(account);
}catch(failure){error(failure);}
}
async function showUpdates() {
const content=el('div',{class:'detail-sections'}),values=el('div'),message=el('p'),check=el('button',{type:'button',text:'检查 GitHub 正式版本'}),apply=el('button',{type:'button',text:'提交更新请求…',disabled:true});
const labels={unchecked:'尚未检查',no_release:'尚无正式版本',up_to_date:'已是最新版本',available:'发现新版本',check_failed:'版本检查失败',unavailable:'更新器未就绪',pending:'等待宿主机处理',applying:'正在更新并检查健康',succeeded:'更新完成,健康检查通过',rolled_back:'更新失败,已回滚',failed:'更新失败'};
const lifetime=new AbortController();
let status,timer,closed=false,busy=false;
const active=()=>!closed && content.isConnected && $('#action-dialog').open;
const bounded=async callback=>{
const controller=new AbortController(),abort=()=>controller.abort();
lifetime.signal.addEventListener('abort',abort,{once:true});
const deadline=setTimeout(abort,5000);
try{return await callback(controller.signal);}
finally{clearTimeout(deadline);lifetime.signal.removeEventListener('abort',abort);}
};
const render=data=>{
if(!active())return;
status=data;
const host=data.host_status;
values.replaceChildren(detailsList({current:data.current_version || state.meta?.version,latest:data.latest_version,checked:data.checked_at,executor:data.executor?.enabled?'已就绪':'未配置或未启用',automatic:data.executor?.auto_apply?'已启用':'未启用',status:labels[data.status] || '状态未确认',...(host?{host:labels[host.status] || '状态未确认',hostVersion:host.version,hostUpdated:host.updated_at}:{})},{current:'当前版本',latest:'最新正式版本',checked:'上次检查',executor:'宿主机更新器',automatic:'定时更新',status:'更新状态',host:'宿主机回报',hostVersion:'宿主机版本',hostUpdated:'回报时间'}));
message.textContent=[...new Set([data.message,data.error,host?.message,host?.error].filter(Boolean))].join('\n');apply.disabled=!data.can_apply;
if(!data.executor?.enabled)message.textContent+=' 当前仅可检查版本;部署器未配置或未启用,无法执行更新。';
};
const schedule=()=>{clearTimeout(timer);if(active())timer=setTimeout(poll,3000);};
const disconnected=async failure=>{
if(!active())return;
message.textContent=failure.status===401?'服务已重新要求管理登录,请登录后继续查看更新状态。':'服务暂时断开,正在等待恢复;每 3 秒重新读取更新状态。';
apply.disabled=true;
try{await bounded(signal=>api.health({signal}));}catch{}
};
async function poll(){
if(!active())return;
if(busy){schedule();return;}
busy=true;
try{render(await bounded(signal=>api.updates({signal})));}
catch(failure){await disconnected(failure);}
finally{busy=false;schedule();}
}
check.addEventListener('click',async()=>{
if(busy)return;busy=true;clearTimeout(timer);check.disabled=true;check.textContent='正在检查…';
try{render(await bounded(signal=>api.checkUpdates({signal})));}
catch(failure){if(active())message.textContent=failure.name==='AbortError'?'版本检查暂未返回,稍后将自动读取最新状态。':failure.message;}
finally{busy=false;check.disabled=false;check.textContent='检查 GitHub 正式版本';schedule();}
});
apply.addEventListener('click',async()=>{
if(busy || !status?.can_apply)return;
const version=status.latest_version;
if(!window.confirm(`提交 ${version} 更新请求?执行器将处理请求并可能重启服务。`))return;
busy=true;clearTimeout(timer);apply.disabled=true;
try{render(await bounded(signal=>api.applyUpdate(version,{signal})));}
catch(failure){await disconnected(failure);}
finally{busy=false;schedule();}
});
content.append(values,message,el('div',{class:'page-toolbar'},check,apply),el('p',{class:'info-note',text:'仅检查 GitHub 正式版本。窗口打开时每 3 秒读取宿主机状态;提交请求后由受控更新器处理,服务恢复且健康检查通过后才显示完成。'}));
const open=dialog('版本与更新',content,{info:true});
poll();
try{await open;}
finally{closed=true;clearTimeout(timer);lifetime.abort();}
}
function setLogVisible(visible) {
const account=current();if(account?.config)editConfig(account,['log_visible'],visible);
else applyLogLayout(null,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));
const size=account?.config?.log_sizes?.[1];if(size)setLogHeight(size);
}
function setLogHeight(height) {
height=Math.max(64,Math.min(Math.min(480,innerHeight*.5),Math.round(height)));
document.documentElement.style.setProperty('--log-height',`${height}px`);$('#log-resizer').setAttribute('aria-valuenow',String(height));return 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;
}
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);}
}catch(failure){if(failure.status!==401)setStatus(failure.message);}finally{account.logs.loading=false;}
}
async function showDebugEntry(account,entry) {
const pre=el('pre',{class:'debug-json',text:'正在读取所选条目的脱敏详情…'});const open=dialog('请求 / 响应详情(已脱敏)',pre,{info:true});
try{
let path;
try{path=apiPath(entry.detail_url || entry.debug_url);}catch{/* Use the account's own endpoint for untrusted URLs. */}
const detail=await (path?request(path):api.debugEntry(account.id,entry.id));
pre.textContent=JSON.stringify(detail.details ?? detail,null,2);
}catch(failure){pre.textContent=failure.message;}
await open;
}
function showNoAccounts() {
state.active=null;$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:'尚未添加账号。新增账号后登录游戏,或使用离线演示查看工作台。'}),el('div',{class:'page-toolbar'},el('button',{text:'新增账号…',onClick:()=>command('add-account')}),el('button',{text:'新增离线演示账号',onClick:()=>command('add-demo')}))));
renderAccountTabs();renderSummary();renderLogs(true);setStatus('等待新增账号');
}
async function syncAccounts() {
const response=await api.accounts(),summaries=Array.isArray(response)?response:response.accounts || [];
const ids=new Set(summaries.map(summary=>summary.id));
for(const [id,account]of state.accounts)if(!ids.has(id)){account.pages.forEach(page=>{clearTimeout(page.loadTimer);page.root.remove();});state.accounts.delete(id);}
summaries.forEach(summary=>{
const account=state.accounts.get(summary.id);if(account){account.summary=summary;if(account.config&&account.revision!==summary.revision&&!account.edits.size&&!account.savePromise)refreshConfig(account).catch(error);}
else state.accounts.set(summary.id,makeAccount(summary));
});
renderAccountTabs();renderSummary();
if(!state.accounts.size)showNoAccounts();else if(!state.accounts.has(state.active))await selectAccount(state.accounts.keys().next().value);
}
async function tick() {
if(!state.ready||state.polling)return;state.polling=true;
try{
const account=current();await Promise.allSettled([syncAccounts(),...([...state.accounts.values()].flatMap(item=>[...item.jobs.values()].map(job=>pollJob(item,job))))]);
if(state.ready&&account&&state.accounts.has(account.id)){fetchLogs(account);const page=account.pages.get(account.page);if(page&&Date.now()-(page.lastLoad||0)>4000)loadPage(page);}
}finally{state.polling=false;}
}
function hideWorkbench() {
state.ready=false;
$('#app').hidden=true;$('#notice').hidden=true;
$$('dialog[open]').forEach(root=>root.close());
$$('.context-menu').forEach(root=>root.remove());
$$('input[type="password"]').forEach(input=>input.value='');
state.accounts.forEach(account=>{clearTimeout(account.saveTimer);account.pages.forEach(page=>clearTimeout(page.loadTimer));});
}
function requireAuth() {
if(state.redirecting)return;
state.redirecting=true;hideWorkbench();location.replace(webPath('/login'));
}
async function bootstrap() {
try{
const auth=await api.auth();if(state.redirecting)return;if(auth.required&&!auth.authenticated){requireAuth();return;}
$('#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.0.dev1';$('#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})));}
}
PAGES.forEach(([key,label])=>$('#page-tabs').append(el('button',{type:'button',class:'page-tab',role:'tab','data-page':key,'aria-selected':String(key==='login'),tabindex:key==='login'?0:-1,text:label,onClick:()=>selectPage(key)})));
tabKeys($('#account-tabs'),'.account-tab');tabKeys($('#page-tabs'),'.page-tab');
$('#menu-bar').addEventListener('click',event=>{const button=event.target.closest('[data-command]');if(button){$$('.menu[open]').forEach(menu=>menu.open=false);command(button.dataset.command);}});
document.addEventListener('click',event=>{if(!event.target.closest('.menu'))$$('.menu[open]').forEach(menu=>menu.open=false);});
document.addEventListener('keydown',event=>{if(event.key==='Escape')$$('.menu[open]').forEach(menu=>menu.open=false);});
$$('.menu').forEach(menu=>menu.addEventListener('toggle',()=>{if(menu.open)$$('.menu').filter(other=>other!==menu).forEach(other=>other.open=false);}));
$('#add-account').addEventListener('click',()=>command('add-account'));
$('#strategy-toggle').addEventListener('click',()=>command(current()?.summary.running?'stop':'start'));
$('#refresh').addEventListener('click',()=>{const account=current();if(account)perform(account,'refresh',{page:account.page}).catch(error);});
$('#refresh-interval').addEventListener('change',event=>{if(current())editConfig(current(),['interval'],Number(event.target.value));});
$('#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;});
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);});
$('#log-resizer').addEventListener('pointerup',()=>{if(!resize)return;resize=null;const account=current();if(account?.config)editConfig(account,['log_sizes'],[$('#workspace').clientHeight,Number($('#log-resizer').getAttribute('aria-valuenow'))]);});
$('#log-resizer').addEventListener('keydown',event=>{if(!['ArrowUp','ArrowDown','Home','End'].includes(event.key))return;event.preventDefault();const height=Number(event.currentTarget.getAttribute('aria-valuenow'));const next=setLogHeight(event.key==='Home'?64:event.key==='End'?480:height+(event.key==='ArrowUp'?16:-16));if(current()?.config)editConfig(current(),['log_sizes'],[$('#workspace').clientHeight,next]);});
window.addEventListener('auth-required',requireAuth);
window.addEventListener('pagehide',hideWorkbench);
window.addEventListener('pageshow',event=>{if(event.persisted){state.redirecting=false;bootstrap();}});
window.addEventListener('beforeunload',event=>{if(!state.redirecting&&[...state.accounts.values()].some(account=>account.edits.size||account.savePromise)){event.preventDefault();event.returnValue='';}});
setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString('zh-CN',{hour12:false});},1000);
setInterval(tick,1000);
bootstrap();
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+34
View File
@@ -0,0 +1,34 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="ranch-web-base-path" content="">
<meta name="color-scheme" content="light">
<meta name="theme-color" content="#172435">
<link rel="icon" href="data:,">
<title>牧羊人之心 · 自动化控制台</title>
<script type="module" crossorigin src="./assets/index-Bx0TuomG.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-Br0WZ5ge.css">
</head>
<body>
<div id="app" hidden></div>
<div id="notice" class="notice" role="status" hidden></div>
<dialog id="action-dialog" aria-labelledby="dialog-title">
<form id="dialog-form">
<header class="dialog-header">
<h1 id="dialog-title"></h1>
<button type="button" class="dialog-close" aria-label="关闭对话框">×</button>
</header>
<div id="dialog-content" class="dialog-content"></div>
<p id="dialog-error" class="error-text" role="alert" hidden></p>
<footer class="dialog-footer">
<button type="button" id="dialog-cancel">取消</button>
<button type="submit" id="dialog-confirm" class="primary">确认</button>
</footer>
</form>
</dialog>
<noscript>请启用 JavaScript 以使用牧场管理控制台。</noscript>
</body>
</html>
+16 -4
View File
@@ -29,7 +29,7 @@ export function control(field, {get, set, onError = () => {}}) {
} else if (['boolean', 'bool', 'checkbox'].includes(type)) {
root = el('input', {type: 'checkbox', 'aria-label': label});
root.addEventListener('change', () => commit(root.checked));
sync = () => { root.checked = Boolean(value()); };
sync = () => { if (document.activeElement !== root) root.checked = Boolean(value()); };
} else if (['select', 'enum'].includes(type)) {
root = el('select', {'aria-label': label});
let optionsSignature;
@@ -58,7 +58,10 @@ export function control(field, {get, set, onError = () => {}}) {
root.append(el('label', {}, check, option.label));
return {check, option};
});
sync = () => items.forEach(({check, option}) => { check.checked = (value() || []).includes(option.value); });
sync = () => {
const selected = value() || [];
items.forEach(({check, option}) => { if (document.activeElement !== check) check.checked = selected.includes(option.value); });
};
} else if (['id_counts', 'counts', 'reserves'].includes(type)) {
root = el('div', {class: 'counts-editor', role: 'group', 'aria-label': label});
const lines = el('div', {class: 'counts-lines'});
@@ -123,7 +126,15 @@ export function control(field, {get, set, onError = () => {}}) {
}
root.dataset.configPath = pathKey(path);
root.title = field.help || field.description || label;
root.disabled = Boolean(field.disabled || field.readonly);
const syncValue = sync;
sync = () => {
if (!root.contains(document.activeElement)) {
const disabled = Boolean(field.disabled || field.readonly);
if (root.matches('input,select,button,textarea')) root.disabled = disabled;
else root.querySelectorAll('input,select,button,textarea').forEach(input => { input.disabled = disabled; });
}
syncValue();
};
sync();
return {root, sync, field};
}
@@ -172,8 +183,9 @@ export class PolicyForm {
this.signature = signature;
}
this.host.hidden = !fields.length;
const latestByPath = new Map(fields.map(field => [pathKey(field.path), field]));
this.controls.forEach(entry => {
const latest = fields.find(field => pathKey(field.path) === pathKey(entry.field.path));
const latest = latestByPath.get(pathKey(entry.field.path));
if (latest) Object.assign(entry.field, latest);
entry.sync();
entry.row.dataset.dirty = String(Boolean(this.context.dirty?.(entry.field.path)));
+31 -47
View File
@@ -1,50 +1,34 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="ranch-web-base-path" content="">
<meta name="color-scheme" content="light">
<title>牧羊人之心牧场助手 · Web</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="/static/styles.css">
<script type="module" src="/static/app.js"></script>
</head>
<body>
<div id="app" class="workbench" aria-label="牧羊人之心牧场助手" hidden>
<header class="window-header">
<nav id="menu-bar" class="menu-bar" aria-label="主菜单">
<details class="menu"><summary accesskey="a">账号<span class="access-key">(A)</span></summary><div class="menu-popup">
<button data-command="add-account">新增账号…</button><button data-command="add-demo">新增离线演示账号</button>
<button data-command="remove-account">移除当前账号…</button><hr><button data-command="logout">退出游戏登录</button><button data-command="forget-login">退出并清除登录记录…</button><hr><button data-command="admin-logout">退出管理工作台</button>
</div></details>
<details class="menu"><summary accesskey="r">策略<span class="access-key">(R)</span></summary><div class="menu-popup">
<button data-command="start">开启当前账号策略</button><button data-command="stop">停止当前账号策略</button><hr><button data-command="start-all">开启全部账号策略</button><button data-command="stop-all">停止全部账号策略</button>
</div></details>
<details class="menu"><summary accesskey="s">配置<span class="access-key">(S)</span></summary><div class="menu-popup">
<button data-command="save">保存当前账号策略</button><button data-command="import-config">导入当前账号策略…</button><button data-command="export-config">导出当前账号策略</button><hr><button data-command="import-yields">导入收益 CSV / XLSX…</button><button data-command="export-yields">下载收益 CSV</button>
</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.0.dev1</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>
<div class="summary-line"><span id="data-summary">等待连接服务</span><span id="save-status" role="status">配置未载入</span></div>
<main id="workspace" class="workspace">
<nav id="page-tabs" class="page-tabs" role="tablist" aria-label="功能页面"></nav>
<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>
<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>
<dialog id="action-dialog" aria-labelledby="dialog-title"><form id="dialog-form"><header class="dialog-header"><h1 id="dialog-title"></h1><button type="button" class="dialog-close" aria-label="关闭对话框">×</button></header><div id="dialog-content" class="dialog-content"></div><p id="dialog-error" class="error-text" role="alert" hidden></p><footer class="dialog-footer"><button type="button" id="dialog-cancel">取消</button><button type="submit" id="dialog-confirm" class="primary">确认</button></footer></form></dialog>
<noscript>此工作台需要启用 JavaScript 才能连接本地服务。</noscript>
</body>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="ranch-web-base-path" content="">
<meta name="color-scheme" content="light">
<meta name="theme-color" content="#172435">
<link rel="icon" href="data:,">
<title>牧羊人之心 · 自动化控制台</title>
<script type="module" crossorigin src="/static/console/assets/index-Bx0TuomG.js"></script>
<link rel="stylesheet" crossorigin href="/static/console/assets/index-Br0WZ5ge.css">
</head>
<body>
<div id="app" hidden></div>
<div id="notice" class="notice" role="status" hidden></div>
<dialog id="action-dialog" aria-labelledby="dialog-title">
<form id="dialog-form">
<header class="dialog-header">
<h1 id="dialog-title"></h1>
<button type="button" class="dialog-close" aria-label="关闭对话框">×</button>
</header>
<div id="dialog-content" class="dialog-content"></div>
<p id="dialog-error" class="error-text" role="alert" hidden></p>
<footer class="dialog-footer">
<button type="button" id="dialog-cancel">取消</button>
<button type="submit" id="dialog-confirm" class="primary">确认</button>
</footer>
</form>
</dialog>
<noscript>请启用 JavaScript 以使用牧场管理控制台。</noscript>
</body>
</html>
+14 -11
View File
@@ -1,26 +1,29 @@
:root {
font-family: "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
font-size: 13px;
color: #202832;
background: #f1f3f5;
font-size: 14px;
color: #17243b;
background: #f4f6fa;
font-synthesis: none;
color-scheme: light;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
body { margin: 0; min-height: 100dvh; display: grid; place-items: center; padding: 24px 16px; }
.admin-login { width: 100%; max-width: 370px; padding: 24px; background: #fff; border: 1px solid #cbd1d8; border-radius: 5px; }
h1 { margin: 0 0 12px; font-size: 18px; font-weight: 600; }
.admin-login { width: 100%; max-width: 420px; padding: 36px; background: #fff; border: 1px solid #dbe2ec; border-radius: 14px; box-shadow: 0 12px 40px rgb(22 34 53 / 6%); }
.login-brand { display: flex; align-items: center; gap: 10px; margin-bottom: 32px; font-weight: 700; color: #2563eb; }
.login-brand svg { width: 28px; height: 28px; }
h1 { margin: 0 0 10px; font-size: 24px; font-weight: 650; letter-spacing: -.5px; }
p { margin: 0; line-height: 1.65; overflow-wrap: anywhere; }
#auth-description { color: #55616e; margin-bottom: 20px; }
#auth-description { color: #526079; margin-bottom: 28px; }
form { display: flex; flex-direction: column; gap: 8px; }
input, button { font: inherit; min-width: 0; min-height: 36px; padding: 7px 10px; border: 1px solid #afb8c2; border-radius: 3px; }
input { width: 100%; background: #fff; color: inherit; caret-color: #245d9b; }
button { margin-top: 8px; background: #245d9b; color: #fff; border-color: #245d9b; cursor: pointer; }
button:hover { background: #1c4d83; }
input, button { font: inherit; min-width: 0; min-height: 44px; padding: 9px 12px; border: 1px solid #bdc9d9; border-radius: 7px; }
input { width: 100%; background: #fff; color: inherit; caret-color: #2563eb; }
button { margin-top: 12px; background: #2563eb; color: #fff; border-color: #2563eb; cursor: pointer; font-weight: 600; }
button:hover { background: #1d4ed8; }
button:disabled { cursor: default; opacity: .58; }
input:focus-visible, button:focus-visible { outline: 2px solid #245d9b; outline-offset: 2px; }
input:focus-visible, button:focus-visible { outline: 2px solid #2563eb; outline-offset: 3px; }
#auth-status { color: #55616e; }
#auth-error { color: #99251e; white-space: pre-wrap; }
noscript { display: block; margin-top: 16px; line-height: 1.65; }
::selection { background: #c5dbf5; color: #142b46; }
@media (max-width: 480px) { .admin-login { padding: 28px 24px; } }
+4 -3
View File
@@ -5,15 +5,16 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="ranch-web-base-path" content="">
<meta name="color-scheme" content="light">
<title>管理登录 · 牧羊人之心牧场助手</title>
<title>管理登录 · 牧羊人之心控制台</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="/static/login.css">
<script type="module" src="/static/login.js"></script>
</head>
<body>
<main class="admin-login" aria-labelledby="auth-title">
<h1 id="auth-title">登录管理工作台</h1>
<p id="auth-description">请输入此 Web 工作台的管理密码。</p>
<div class="login-brand"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M12 21v-9M12 16C5 16 3 11 3 5c6 0 9 3 9 9M12 12c0-6 3-9 9-9 0 6-3 9-9 9"/></svg><span>牧羊人之心控制台</span></div>
<h1 id="auth-title">登录管理控制台</h1>
<p id="auth-description">输入管理密码,进入你的牧羊人之心工作空间。</p>
<form id="auth-form" method="post" action="/api/auth/login" aria-describedby="auth-description">
<label for="admin-password">管理密码</label>
<input id="admin-password" name="password" type="password" autocomplete="current-password" required aria-describedby="auth-error" disabled>
+15 -2
View File
@@ -111,11 +111,21 @@ export class PageView {
clearError() { this.errorBox.hidden = true; }
setQuery(key, value) {
if (this.query[key] === value) return;
if (this.destroyed || 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);
this.queryTimer = setTimeout(() => { if (!this.destroyed) this.options.load(this, true); }, key === 'search' ? 220 : 0);
}
destroy() {
this.destroyed = true;
clearTimeout(this.queryTimer);
this.generation = (this.generation || 0) + 1;
this.table?.destroy?.();
this.statisticsTable?.destroy();
this.login?.clearPassword();
this.root.remove();
}
updateFilters(filters) {
@@ -197,6 +207,7 @@ export class PageView {
}
render(data, loading = false) {
if (this.destroyed) return;
if (!data) { this.loading.textContent = '正在读取…'; this.loading.dataset.loading = 'true'; return; }
this.data = data;
this.loading.dataset.loading = String(loading);
@@ -224,6 +235,8 @@ export class PageView {
const mode = this.key === 'statistics' ? 'statistics' : grouped ? 'grouped' : 'table';
if (this.contentMode !== mode) {
if (this.content.contains(document.activeElement)) return;
this.table?.destroy?.();
this.statisticsTable?.destroy();
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;
-14
View File
@@ -1,14 +0,0 @@
:root{font-family:"Segoe UI","Microsoft YaHei UI","Microsoft YaHei",system-ui,sans-serif;font-size:13px;color:#202832;background:#f1f3f5;font-synthesis:none;color-scheme:light;--border:#cbd1d8;--muted:#55616e;--accent:#245d9b;--tint:#e8f0f9;--log-height:150px;--danger:#b3261e;--green:#20743a}
*{box-sizing:border-box}body{margin:0}button,input,select,textarea{font:inherit;color:inherit}button,select,input[type=number],input[type=text],input[type=password],input[type=search],textarea{border:1px solid #afb8c2;border-radius:3px;background:#fff;min-height:27px}button{padding:3px 10px;cursor:pointer;white-space:nowrap;background:#f8f9fb}button:hover{background:#e9edf2;border-color:#8291a1}button:active{background:#dce4ed}button:disabled,input:disabled,select:disabled{cursor:default;opacity:.58}input,select{padding:2px 6px}input[type=checkbox]{width:14px;height:14px;min-height:0;margin:0 4px 0 0;accent-color:var(--accent);vertical-align:middle;flex-shrink:0}input[type=number]{font-variant-numeric:tabular-nums;min-width:62px;width:88px}input[type=search]{min-width:170px}select{max-width:100%}textarea{padding:6px;resize:vertical;min-height:60px}button:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible,[tabindex]:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:2px}::selection{background:#c5dbf5;color:#142b46}input,textarea{caret-color:var(--accent)}[hidden]{display:none!important}h1,h2,h3,p{margin:0}h1{font-size:16px;font-weight:600}h2,h3{font-size:14px;font-weight:600}p{line-height:1.65}a{color:var(--accent);text-underline-offset:3px}.muted{color:var(--muted);font-size:12px}.spacer{flex:1}.primary{background:#245d9b;color:#fff;border-color:#245d9b}.primary:hover{background:#1c4d83;color:#fff}.danger{color:#94231d;border-color:#c39c99}.error-text{color:#99251e;white-space:pre-wrap;overflow-wrap:anywhere}.small,.compact{min-height:24px;padding:2px 8px;font-size:12px}
.workbench{height:100dvh;min-height:420px;display:flex;flex-direction:column;overflow:hidden}.window-header{display:flex;align-items:center;min-height:29px;gap:16px;padding:0 10px 0 4px;border-bottom:1px solid var(--border);background:#f6f7f9}.window-title{font-size:12px;color:#404c59}.window-title #app-version{margin-left:5px;color:var(--muted)}#access-mode{margin-left:auto}.menu-bar{display:flex;gap:1px}.menu{position:relative}.menu>summary{list-style:none;padding:5px 9px;cursor:pointer;border-radius:2px}.menu>summary::-webkit-details-marker{display:none}.menu[open]>summary,.menu>summary:hover{background:#dfe8f3}.access-key{font-size:11px;margin-left:3px;color:var(--muted)}.menu-popup{position:absolute;top:100%;left:0;z-index:30;min-width:220px;padding:4px;background:#fff;border:1px solid #acb6c1;box-shadow:0 5px 14px #172a4026}.menu-popup button{display:block;width:100%;border:0;border-radius:0;text-align:left;background:transparent;padding:6px 12px}.menu-popup button:hover{background:var(--tint)}.menu-popup hr{border:0;border-top:1px solid var(--border);margin:4px 2px}
.account-bar{display:flex;gap:6px;align-items:center;padding:5px 6px 0;min-height:36px;background:#e7ebef;border-bottom:1px solid var(--border)}.account-tabs{display:flex;overflow-x:auto;gap:3px;align-self:stretch;min-width:0;scrollbar-width:thin}.account-tab{border-radius:4px 4px 0 0;border:1px solid var(--border);border-bottom:0;display:flex;gap:6px;align-items:center;max-width:230px;background:#f1f3f5;min-height:30px;padding:4px 13px}.account-tab[aria-selected=true]{background:#fff;box-shadow:inset 0 2px 0 var(--accent)}.account-tab .account-label{overflow:hidden;text-overflow:ellipsis}.account-dot{width:6px;height:6px;border-radius:50%;background:#7b8490;flex-shrink:0}.account-dot.running{background:var(--green)}.account-dot.error{background:var(--danger)}#add-account{margin:0 0 5px;flex-shrink:0}.toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:8px 18px;padding:8px 8px 5px;background:#fff}.player-line{display:flex;align-items:center;flex-wrap:wrap;gap:12px;min-height:27px;flex:1 1 auto}.player-line>span{white-space:nowrap}.player-line b{font-weight:600;font-variant-numeric:tabular-nums}.player-line>strong{max-width:180px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.connection{font-size:12px;color:var(--muted)}.connection.online{color:#176331}.connection.demo{color:#805300}.experience{display:inline-flex;gap:5px;align-items:center}progress{width:58px;height:6px;accent-color:var(--accent)}progress::-webkit-progress-bar{background:#e2e7ee;border-radius:2px}progress::-webkit-progress-value{background:#467aa9;border-radius:2px}.run-controls{display:flex;align-items:center;gap:5px;flex-wrap:wrap}.run-controls>label{display:flex;align-items:center;gap:5px}.run-button{min-width:76px;font-weight:600;background:var(--green);border-color:#185b2d;color:#fff}.run-button:hover{background:#1b6332;color:#fff;border-color:#185b2d}.run-button.running{background:var(--danger);border-color:#8f1e18}.run-button.running:hover{background:#992019}.run-button:disabled{opacity:1;background:#727b82;border-color:#727b82}.summary-line{display:flex;gap:10px;align-items:center;min-height:25px;padding:2px 8px 5px;background:#fff;font-size:12px;color:var(--muted)}#data-summary{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;flex:1}#save-status{flex-shrink:0}#save-status.pending{color:#805300}#save-status.failed{color:#99251e}
.workspace{display:flex;flex-direction:column;flex:1;min-height:155px;padding:0 6px;overflow:hidden;background:#fff}.page-tabs{display:flex;flex-shrink:0;overflow-x:auto;gap:0;border-bottom:1px solid #9eabb9;scrollbar-width:thin}.page-tab{border-radius:3px 3px 0 0;border:1px solid transparent;background:#f1f3f5;padding:6px 10px;min-height:30px;margin-right:1px;font-size:12px}.page-tab[aria-selected=true]{background:#fff;border-color:#9eabb9;border-bottom-color:#fff;color:#174d83;box-shadow:inset 0 2px 0 #245d9b;font-weight:600}.page-tab:hover{background:#e8f0f9}.page-host{flex:1;min-height:0;overflow:hidden;position:relative}.page-panel{height:100%;display:flex;flex-direction:column;overflow:auto;padding:7px 2px 4px;gap:7px;scrollbar-gutter:stable}.page-header{display:flex;gap:8px;align-items:center;flex-wrap:wrap;min-height:25px}.page-header h2{margin-right:7px}.page-summary{color:var(--muted);font-size:12px;line-height:1.6;white-space:pre-wrap;overflow-wrap:anywhere}.page-toolbar,.filter-bar{display:flex;flex-wrap:wrap;gap:5px 9px;align-items:center}.filter-bar label{display:inline-flex;gap:5px;align-items:center}.page-loading{font-size:12px;color:var(--muted);margin-left:auto}.page-loading[data-loading=true]::before{content:"";display:inline-block;width:7px;height:7px;background:#688aaf;border-radius:50%;margin-right:5px}.subtabs{display:flex;gap:2px;border-bottom:1px solid var(--border);flex-shrink:0}.subtab{background:#f0f2f5;border:1px solid var(--border);border-bottom:0;border-radius:3px 3px 0 0;font-size:12px;padding:4px 10px}.subtab[aria-selected=true]{background:#e8f0f9;color:#174d83;border-color:#94adc7}.initial-state,.empty-state{padding:24px 18px;color:var(--muted);line-height:1.8}.empty-state p{max-width:65ch}.empty-state button{margin-top:12px}.page-error{padding:8px 10px;background:#fff4f3;border:1px solid #ddbbb7;color:#8e251f;display:flex;align-items:center;gap:10px;white-space:pre-wrap}.info-note{font-size:12px;color:var(--muted);line-height:1.65;padding:5px 0;max-width:115ch}.inline-note{color:var(--muted);font-size:12px}
.table-scroll{overflow:auto;min-height:80px;flex:1;border:1px solid var(--border);background:#fff;position:relative}.data-table{border-collapse:separate;border-spacing:0;width:100%;font-size:12px;white-space:nowrap;text-align:left;font-variant-numeric:tabular-nums}.data-table th{position:sticky;top:0;z-index:2;background:#eef1f5;color:#303d4c;font-weight:500;border-bottom:1px solid #bac4cf;border-right:1px solid #d5dbe2;height:28px;padding:3px 8px;white-space:nowrap}.data-table th button{font:inherit;border:0;background:transparent;padding:0;min-height:20px;display:flex;align-items:center;gap:6px;width:100%;text-align:left}.data-table th .sort-mark{color:#506a85;font-size:10px;min-width:8px}.data-table td{border-bottom:1px solid #e4e8ed;border-right:1px solid #eef0f3;padding:2px 7px;height:29px;max-width:300px;overflow:hidden;text-overflow:ellipsis}.data-table tr:nth-child(even)>td{background:#fafbfc}.data-table tr:hover>td{background:#f0f5fa}.data-table tr[aria-selected=true]>td{background:#dfecfa}.data-table td.number{text-align:right}.data-table td.cell-edit{padding:2px 4px;overflow:visible}.data-table td.cell-edit input[type=number]{min-height:24px;height:24px;width:76px;font-size:12px}.data-table td.cell-edit select{min-height:24px;height:24px;font-size:12px;max-width:220px}.data-table td.cell-edit input[type=text]{min-height:24px;width:140px;font-size:12px}.data-table .selection-cell{width:29px;min-width:29px;text-align:center;padding:0 5px;position:sticky;left:0;z-index:1}.data-table th.selection-cell{z-index:3}.data-table .cell-wrap{white-space:normal;min-width:190px;line-height:1.5}.data-table .cell-ellipsis{max-width:260px}.data-table .cell-boolean{color:#176331}.table-footer{display:flex;gap:12px;align-items:center;min-height:20px;font-size:12px;color:var(--muted)}.table-footer>button{margin-left:auto}.grouped-tables{display:flex;flex-direction:column;gap:5px;overflow:auto;flex:1;min-height:100px}.table-group{border:1px solid var(--border);background:#fff}.table-group>summary{cursor:pointer;font-weight:600;font-size:12px;padding:7px 9px;background:#eef1f5;position:sticky;top:0;z-index:3}.table-group>summary small{font-weight:400;color:var(--muted);margin-left:10px}.table-group .table-scroll{border:0;max-height:410px}.table-group .data-table th{top:0}.table-group .table-footer{padding:3px 8px}
.policy-form{display:flex;flex-direction:column;gap:9px;flex-shrink:0}.form-section{margin:0;border:1px solid #d6dce3;padding:7px 10px 10px;min-width:0}.form-section legend{font-size:12px;font-weight:600;padding:0 5px;color:#344458}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(270px,1fr));gap:7px 22px;max-width:1100px}.field{display:flex;align-items:center;gap:8px;min-width:0;font-size:12px}.field>.field-label{min-width:135px;flex:0 1 195px;line-height:1.5}.field>.field-input{flex:1;min-width:0;max-width:310px}.field input[type=number].field-input{max-width:130px}.field.checkbox-field{min-height:27px}.field-help{font-size:12px;color:var(--muted);line-height:1.5;display:block;grid-column:1/-1}.field-wide{grid-column:1/-1}.field.invalid input{border-color:var(--danger)}.field[data-dirty=true] .field-label::after{content:" ·";color:#805300}.inline-editor{display:inline-flex;align-items:center;gap:3px}.multi-select{display:flex;flex-wrap:wrap;gap:4px 12px;padding:4px 0;min-width:0}.multi-select label{display:inline-flex;align-items:center;gap:2px}.member-selects{display:flex;gap:3px;flex-wrap:wrap;align-items:center}.member-selects select{width:165px}.member-selects button{min-height:24px}.login-layout{max-width:790px;display:flex;flex-direction:column;gap:10px;padding:4px 8px}.login-layout .form-grid{grid-template-columns:1fr}.login-layout input[type=text],.login-layout input[type=password]{width:320px;max-width:100%}.login-layout .field>.field-label{flex-basis:145px;min-width:145px}.login-layout .field>.field-input{max-width:none}.login-options{display:flex;gap:14px;margin-left:153px;font-size:12px}.login-actions{display:flex;gap:6px;margin-left:153px;flex-wrap:wrap}.server-row{display:flex;gap:6px;flex:1;min-width:0}.server-row select{min-width:180px;flex:1}.session-block{margin-top:4px;padding-top:14px;border-top:1px solid var(--border)}.demo-note{font-size:12px;color:#805300;background:#fff9ea;border:1px solid #e1d0a7;padding:6px 9px;line-height:1.6}.detail-list{display:grid;grid-template-columns:max-content 1fr;gap:6px 18px;font-size:12px}.detail-list dt{color:var(--muted)}.detail-list dd{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}.detail-sections{display:flex;flex-direction:column;gap:12px}.statistics-layout{display:flex;gap:9px;min-height:180px;flex:1}.statistics-picker{width:260px;flex-shrink:0;overflow:auto;border:1px solid var(--border)}.statistics-picker button{display:block;border:0;border-radius:0;width:100%;text-align:left;overflow:hidden;text-overflow:ellipsis;font-size:12px}.statistics-picker button[aria-selected=true]{background:var(--tint);color:#174d83}.statistics-main{min-width:0;flex:1;display:flex;flex-direction:column;gap:8px}.chart-scroll{min-height:120px;max-height:310px;overflow:auto;border:1px solid var(--border);padding:8px}.drop-chart{display:block;min-width:450px;width:100%;height:auto}.chart-label{font-size:12px;fill:#344458}.chart-value{font-size:11px;fill:#344458;font-variant-numeric:tabular-nums}.chart-bar{fill:#4979a4}.chart-grid{stroke:#e3e7ed;stroke-width:1}
.log-resizer{height:7px;min-height:7px;cursor:row-resize;background:#e3e7ec;position:relative;border-top:1px solid #b8c1cb;border-bottom:1px solid #c8d0d9}.log-resizer::after{content:"";position:absolute;width:34px;height:2px;background:#8f9ba8;left:calc(50% - 17px);top:2px}.log-resizer:hover{background:#cedbe9}.log-panel{height:var(--log-height);min-height:64px;max-height:55vh;display:flex;flex-direction:column;background:#fff}.log-toolbar{display:flex;gap:13px;align-items:center;padding:3px 8px;background:#f1f3f5;border-bottom:1px solid var(--border);min-height:29px;font-size:12px}.log-toolbar strong{font-weight:600}.log-toolbar label{display:flex;align-items:center;gap:2px}.log-lines{padding:4px 9px;overflow:auto;flex:1;font:12px/1.65 Consolas,"Microsoft YaHei UI",monospace;white-space:pre-wrap;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.log-entry{min-height:19px}.log-entry .log-time{color:#6a7480;margin-right:8px}.log-entry.error{color:#99251e}.log-entry.warning{color:#805300}.log-entry.debug{color:#55616e}.status-bar{min-height:24px;display:flex;align-items:center;gap:14px;padding:3px 8px;border-top:1px solid var(--border);background:#f1f3f5;font-size:12px;overflow:hidden;white-space:nowrap}.status-bar #status-text{overflow:hidden;text-overflow:ellipsis;max-width:50vw}.status-bar #job-status{overflow:hidden;text-overflow:ellipsis}.notice{position:fixed;right:16px;bottom:35px;max-width:min(540px,calc(100vw - 32px));background:#eef5fc;color:#1d456d;border:1px solid #99b5d1;padding:10px 14px;z-index:80;box-shadow:0 4px 14px #1b2d4326;font-size:13px;line-height:1.5;white-space:pre-wrap}.notice.error{background:#fff2f0;border-color:#d2aaa5;color:#99251e}dialog{border:1px solid #a4afbb;border-radius:5px;padding:0;max-width:min(740px,calc(100vw - 28px));width:560px;max-height:88dvh;background:#fff;color:#202832;box-shadow:0 12px 44px #172a4040}dialog::backdrop{background:#152d493d}dialog>form{display:flex;flex-direction:column;max-height:85dvh}.dialog-header{display:flex;align-items:center;gap:12px;padding:10px 14px;border-bottom:1px solid var(--border);background:#f4f6f8}.dialog-close{margin-left:auto;border:0;background:transparent;padding:0 5px;font-size:22px;line-height:1}.dialog-content{padding:14px;overflow:auto;display:flex;flex-direction:column;gap:12px;min-height:40px}.dialog-content p{font-size:13px;white-space:pre-wrap;overflow-wrap:anywhere}.dialog-content .field{align-items:flex-start}.dialog-content .field input{flex:1;min-width:0}.dialog-content .form-grid{grid-template-columns:1fr}.dialog-footer{display:flex;justify-content:flex-end;gap:7px;padding:10px 14px;border-top:1px solid var(--border);background:#f6f7f9}#dialog-error{padding:0 14px 10px}#auth-dialog{width:370px;padding:18px}#auth-dialog form{gap:13px}#auth-dialog .dialog-footer{margin:0 -18px -18px}#auth-dialog .field{display:flex;flex-direction:column;align-items:stretch;gap:6px}.context-menu{position:fixed;z-index:50;background:#fff;border:1px solid #acb6c1;box-shadow:0 5px 14px #172a4026;padding:4px;min-width:190px}.context-menu button{display:block;width:100%;text-align:left;background:transparent;border:0;border-radius:0;padding:5px 10px}.context-menu button:hover{background:var(--tint)}
@media(min-width:1450px){.toolbar{gap:22px}.player-line{gap:18px}.page-tab{padding-left:13px;padding-right:13px}.form-grid{grid-template-columns:repeat(3,minmax(240px,1fr));max-width:1450px}.login-layout .form-grid{grid-template-columns:1fr}}
@media(max-width:1000px){.window-title{display:none}.toolbar{gap:5px}.run-controls{width:100%}.player-line{gap:10px}.page-tab{padding-left:8px;padding-right:8px}.form-grid{grid-template-columns:repeat(2,minmax(240px,1fr))}.statistics-picker{width:220px}}
@media(max-width:650px){:root{--log-height:120px}.workbench{min-width:340px}.window-header{gap:5px}.menu>summary{padding:5px 7px}.access-key{display:none}#access-mode{font-size:11px}.toolbar{padding:6px}.player-line{gap:7px 10px}.player-line>strong{max-width:135px}.experience progress{display:none}.run-controls{gap:4px}.run-controls>button{padding-left:7px;padding-right:7px;font-size:12px}.form-grid{grid-template-columns:1fr}.field>.field-label{min-width:120px}.field-wide{grid-column:auto}.login-layout{padding:3px}.login-layout .field{align-items:stretch;flex-direction:column;gap:4px}.login-layout .field>.field-label{flex-basis:auto;min-width:0}.login-layout input[type=text],.login-layout input[type=password]{width:100%}.login-options,.login-actions{margin-left:0}.server-row{flex-wrap:wrap}.statistics-layout{flex-direction:column}.statistics-picker{width:100%;max-height:130px}.log-toolbar{gap:7px}#download-log{display:none}.status-bar{gap:8px}.status-bar #game-version{display:none}dialog .field{flex-direction:column;align-items:stretch}dialog .field-label{flex-basis:auto}#save-status{max-width:160px;overflow:hidden;text-overflow:ellipsis}}
@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}
+172 -43
View File
@@ -11,17 +11,24 @@ export function editPath(template, row) {
});
}
function columnEdit(column, row) {
return row.edits?.[column.key] ? {...column.edit, ...row.edits[column.key]} : column.edit;
}
function editableSpec(column, row) {
const edit = column.edit || row.edits?.[column.key] ? {...column.edit, ...row.edits?.[column.key]} : null;
const edit = columnEdit(column, row);
if (!edit) return null;
return {...edit, path: editPath(edit.path, row), label: `${column.label} · ${row.name || row.label || row.id}`,
options: row[edit.options_key] || row[`${column.key}_options`] || edit.options,
disabled: edit.disabled || row[`${column.key}_disabled`] || row.editable === false};
}
function createCellControl(spec, row, context, key) {
const get = (path, fallback) => context.get(path, fallback ?? row[key]);
const set = (path, value, field) => context.set(path, value, field, row);
function createCellControl(spec, getRow, context, key) {
const get = (path, fallback) => context.get(path, fallback ?? getRow()[key]);
const set = (path, value, field) => {
try { context.set(path, value, field, getRow()); }
catch (error) { context.onError?.(error); }
};
const target = ['target', 'priority_target', 'target_priority'].includes(spec.type);
if (target) {
const checkbox = el('input', {type: 'checkbox', 'aria-label': spec.label});
@@ -30,7 +37,7 @@ function createCellControl(spec, row, context, key) {
checkbox.addEventListener('change', () => set(spec.path, checkbox.checked ? spec.default || 100 : undefined, spec));
const sync = () => {
const current = context.get(spec.path);
checkbox.checked = current !== undefined && current !== null && current !== false && current !== 0;
if (document.activeElement !== checkbox) checkbox.checked = current !== undefined && current !== null && current !== false && current !== 0;
checkbox.disabled = Boolean(spec.disabled);
};
sync();
@@ -38,7 +45,7 @@ function createCellControl(spec, row, context, key) {
}
if (['members', 'monster_list', 'team_members'].includes(spec.type)) {
const root = el('div', {class: 'member-selects', 'data-config-path': pathKey(spec.path)});
const options = optionsList(spec.options || row.member_options || row.members_options || []);
const options = optionsList(spec.options || getRow().member_options || getRow().members_options || []);
let drafting=false;
const hint=el('span',{class:'member-draft-note',hidden:true});
const selects = Array.from({length: spec.count || 3}, (_, index) => {
@@ -69,13 +76,16 @@ function createCellControl(spec, row, context, key) {
selects.forEach((select, index) => { if (document.activeElement !== select) select.value = String(selected[index] ?? ''); });
};
sync();
return {root, sync, field: spec};
return {root, sync, field: spec, isDrafting: () => drafting};
}
return control(spec, {get, set, onError: context.onError});
}
const rowId = (row, index) => String(row.id ?? index);
const collator = new Intl.Collator('zh-CN', {numeric: true});
export class DataTable {
constructor(host, context, {selection = true, emptyMessage = '当前筛选下没有条目。'} = {}) {
constructor(host, context, {selection = true, emptyMessage = '当前筛选下没有条目。', pageSize = 50} = {}) {
this.host = host;
this.context = context;
this.selection = selection;
@@ -84,43 +94,107 @@ export class DataTable {
this.nodes = new Map();
this.selected = new Set();
this.sort = null;
this.page = 1;
this.pageSize = [25, 50, 100].includes(pageSize) ? pageSize : 50;
this.pageCount = 1;
this.table = el('table', {class: 'data-table'});
this.head = el('thead');
this.body = el('tbody');
this.table.append(this.head, this.body);
this.empty = el('div', {class: 'empty-state', text: emptyMessage});
this.scroller = el('div', {class: 'table-scroll'}, this.table, this.empty);
this.footer = el('div', {class: 'table-footer'});
this.count = el('span');
this.selectionCount = el('span');
this.footer.append(this.count, this.selectionCount);
this.footer = el('nav', {class: 'table-footer table-pagination', 'aria-label': '表格分页'});
this.count = el('span', {class: 'table-pagination-summary', role: 'status', 'aria-live': 'polite', 'aria-atomic': 'true'});
this.selectionCount = el('span', {class: 'table-selection-summary', role: 'status', 'aria-live': 'polite', hidden: !selection});
this.sizeSelect = el('select', {'aria-label': '每页条目数'}, ...[25, 50, 100].map(size => el('option', {value: size, text: size})));
this.sizeSelect.value = String(this.pageSize);
this.sizeSelect.addEventListener('change', () => {
const size = Number(this.sizeSelect.value);
if (![25, 50, 100].includes(size)) return;
const first = (this.page - 1) * this.pageSize;
this.pageSize = size;
this.setPage(Math.floor(first / size) + 1);
});
this.firstPage = el('button', {type: 'button', text: '首页', onClick: () => this.setPage(1)});
this.previousPage = el('button', {type: 'button', text: '上一页', onClick: () => this.setPage(this.page - 1)});
this.nextPage = el('button', {type: 'button', text: '下一页', onClick: () => this.setPage(this.page + 1)});
this.lastPage = el('button', {type: 'button', text: '末页', onClick: () => this.setPage(this.pageCount)});
this.pageInput = el('input', {type: 'number', min: 1, step: 1, value: 1, 'aria-label': '当前页码'});
this.pageInput.addEventListener('input', () => this.pageInput.setCustomValidity(''));
this.pageInput.addEventListener('change', () => {
const page = Number(this.pageInput.value);
if (!Number.isInteger(page) || page < 1 || page > this.pageCount) {
this.pageInput.setCustomValidity(`请输入 1 到 ${this.pageCount} 之间的页码`);
this.pageInput.reportValidity();
return;
}
this.setPage(page);
});
this.pageInput.addEventListener('blur', () => {
this.pageInput.setCustomValidity('');
this.pageInput.value = String(this.page);
});
this.pageTotal = el('span');
this.footer.append(this.count, this.selectionCount,
el('label', {class: 'table-page-size'}, '每页', this.sizeSelect, '项'),
el('div', {class: 'table-page-controls'}, this.firstPage, this.previousPage,
el('label', {class: 'table-page-current'}, '第', this.pageInput, this.pageTotal), this.nextPage, this.lastPage));
if (selection) {
this.selectFiltered = el('button', {type: 'button', onClick: () => {
this.rows.forEach((row, index) => this.selected.add(rowId(row, index)));
this.syncSelection();
}});
this.clearSelection = el('button', {type: 'button', text: '清除选择', onClick: () => { this.selected.clear(); this.syncSelection(); }});
this.footer.append(el('div', {class: 'table-selection-controls'}, this.selectFiltered, this.clearSelection));
}
host.append(this.scroller, this.footer);
this.onFocusOut = () => queueMicrotask(() => {
if (this.pendingRender && !this.destroyed) this.update(this.columns, this.rows);
});
this.table.addEventListener('focusout', this.onFocusOut);
this.table.addEventListener('contextmenu', event => {
const tr = event.target.closest('tr[data-row-id]');
if (!tr) return;
event.preventDefault();
const id = tr.dataset.rowId;
if (!this.selected.has(id)) {
if (this.selection && !this.selected.has(id)) {
this.selected.clear();
this.selected.add(id);
this.syncSelection();
}
context.onContext?.(event, this.selectedRows(), this.rows.find(row => String(row.id) === id));
context.onContext?.(event, this.selectedRows(), this.rowById.get(id));
});
}
selectedRows() { return this.rows.filter(row => this.selected.has(String(row.id))); }
selectedRows() { return this.rows.filter((row, index) => this.selected.has(rowId(row, index))); }
setPage(page) {
if (this.body.contains(document.activeElement)) document.activeElement.blur();
this.page = Math.max(1, Math.min(Math.max(1, Math.ceil(this.rows.length / this.pageSize)), page));
this.update(this.columns, this.rows);
this.scroller.scrollTop = 0;
}
syncSelection() {
for (const [id, item] of this.nodes) {
item.tr.setAttribute('aria-selected', String(this.selected.has(id)));
if (item.check) item.check.checked = this.selected.has(id);
}
this.selectionCount.textContent = this.selected.size ? `已选择 ${this.selected.size} 项` : '';
const selectionText = this.selected.size ? `已选择 ${this.selected.size} 项(含其他分页)` : '';
if (this.selectionCount.textContent !== selectionText) this.selectionCount.textContent = selectionText;
if (this.allCheck) {
const selected = this.rows.filter(row => this.selected.has(String(row.id))).length;
this.allCheck.checked = selected > 0 && selected === this.rows.length;
this.allCheck.indeterminate = selected > 0 && selected < this.rows.length;
const ids = [...this.nodes.keys()];
const selected = ids.filter(id => this.selected.has(id)).length;
this.allCheck.checked = selected > 0 && selected === ids.length;
this.allCheck.indeterminate = selected > 0 && selected < ids.length;
this.allCheck.disabled = !ids.length;
this.allCheck.setAttribute('aria-label', `选择本页全部 ${ids.length} 项`);
this.allCheck.title = `仅选择本页 ${ids.length} 项;其他分页的选择保持不变`;
}
if (this.selectFiltered) {
this.selectFiltered.textContent = `全选筛选结果(${this.rows.length} 项,含其他分页)`;
this.selectFiltered.disabled = !this.rows.length || this.selected.size === this.rows.length;
this.clearSelection.disabled = !this.selected.size;
}
this.context.onSelection?.(this.selectedRows());
}
@@ -131,10 +205,9 @@ export class DataTable {
this.body.replaceChildren();
const row = el('tr');
if (this.selection) {
this.allCheck = el('input', {type: 'checkbox', 'aria-label': '选择当前表格全部条目'});
this.allCheck = el('input', {type: 'checkbox', 'aria-label': '选择本页全部条目'});
this.allCheck.addEventListener('change', () => {
this.selected.clear();
if (this.allCheck.checked) this.rows.forEach(item => this.selected.add(String(item.id)));
this.nodes.forEach((_, id) => this.allCheck.checked ? this.selected.add(id) : this.selected.delete(id));
this.syncSelection();
});
row.append(el('th', {scope: 'col', class: 'selection-cell'}, this.allCheck));
@@ -147,6 +220,7 @@ export class DataTable {
if (column.width) th.style.minWidth = `${Number(column.width)}px`;
button.addEventListener('click', () => {
this.sort = {key: column.key, direction: this.sort?.key === column.key && this.sort.direction === 1 ? -1 : 1};
this.page = 1;
this.update(this.columns, this.rows);
});
row.append(th);
@@ -154,30 +228,54 @@ export class DataTable {
this.head.append(row);
}
setRows(rows) {
this.rows = rows;
this.rowById = new Map(rows.map((row, index) => [rowId(row, index), row]));
for (const id of this.selected) if (!this.rowById.has(id)) this.selected.delete(id);
}
update(columns = [], rows = []) {
if (this.destroyed) return;
this.columns = columns;
this.setRows(rows);
const focusedId = this.body.contains(document.activeElement) ? document.activeElement.closest('tr[data-row-id]')?.dataset.rowId : undefined;
const keepFocus = focusedId !== undefined && this.rowById.has(focusedId);
const signature = JSON.stringify(columns);
if (this.signature !== signature) {
if (this.host.contains(document.activeElement) && this.signature) return;
this.columns = columns;
if (this.signature !== signature && !keepFocus) {
this.signature = signature;
this.renderedColumns = columns;
this.buildHead(columns);
}
this.rows = rows;
const active = new Set(rows.map(row => String(row.id)));
for (const [id, node] of this.nodes) {
if (!active.has(id) && !node.tr.contains(document.activeElement)) { node.tr.remove(); this.nodes.delete(id); this.selected.delete(id); }
}
const sorted = [...rows];
if (this.sort && !columns.some(column => column.key === this.sort.key)) this.sort = null;
const sorted = rows.map((row, index) => ({row, id: rowId(row, index), index}));
if (this.sort) {
const {key, direction} = this.sort;
const column = columns.find(column => column.key === this.sort.key);
sorted.forEach(item => { item.value = this.sortValue(column, item.row); });
sorted.sort((a, b) => {
const aValue = a[key], bValue = b[key];
if (typeof aValue === 'number' && typeof bValue === 'number') return (aValue - bValue) * direction;
return textValue(aValue).localeCompare(textValue(bValue), 'zh-CN', {numeric: true}) * direction;
const difference = typeof a.value === 'number' && typeof b.value === 'number'
? a.value - b.value : collator.compare(textValue(a.value), textValue(b.value));
return difference * this.sort.direction || a.index - b.index;
});
}
sorted.forEach((row, index) => {
const id = String(row.id ?? index);
this.pageCount = Math.max(1, Math.ceil(rows.length / this.pageSize));
this.page = Math.min(this.page, this.pageCount);
let visible = sorted.slice((this.page - 1) * this.pageSize, this.page * this.pageSize);
const currentIds = [...this.body.children].map(tr => tr.dataset.rowId);
const orderChanged = visible.length !== currentIds.length || visible.some((item, index) => item.id !== currentIds[index]);
this.pendingRender = keepFocus && (orderChanged || signature !== this.signature);
if (this.pendingRender) {
// Hold the current arrangement until focus leaves. Deleted rows still leave
// immediately, and the retained editors always stay within the page limit.
const retained = currentIds.filter(id => this.rowById.has(id)).slice(0, this.pageSize);
const retainedIds = new Set(retained);
visible = [...retained.map(id => ({id, row: this.rowById.get(id)})),
...visible.filter(item => !retainedIds.has(item.id)).slice(0, this.pageSize - retained.length)];
}
const visibleIds = new Set(visible.map(item => item.id));
for (const [id, node] of this.nodes) {
if (!visibleIds.has(id)) { node.tr.remove(); this.nodes.delete(id); }
}
visible.forEach(({row, id}, index) => {
let node = this.nodes.get(id);
if (!node) {
const tr = el('tr', {'data-row-id': id, 'aria-selected': 'false', tabindex: -1});
@@ -187,7 +285,7 @@ export class DataTable {
tr.append(el('td', {class: 'selection-cell'}, check));
}
tr.addEventListener('click', event => {
if (event.target.closest('input,select,button,a,label')) return;
if (!this.selection || event.target.closest('input,select,textarea,button,a,label')) return;
if (!event.ctrlKey && !event.metaKey && !event.shiftKey) this.selected.clear();
this.selected.add(id);
this.syncSelection();
@@ -199,7 +297,8 @@ export class DataTable {
this.nodes.set(id, node);
}
node.row = row;
columns.forEach(column => {
if (node.check) node.check.setAttribute('aria-label', `选择 ${row.name || row.label || id}`);
this.renderedColumns.forEach(column => {
let cell = node.cells.get(column.key);
if (!cell) {
const td = el('td', {'data-column': column.key});
@@ -210,14 +309,18 @@ export class DataTable {
const spec = editableSpec(column, row);
if (spec) {
const controlSignature = JSON.stringify(spec);
if (!cell.control || cell.controlSignature !== controlSignature && !cell.td.contains(document.activeElement)) {
cell.control = createCellControl(spec, row, this.context, column.key);
if (!cell.control || cell.controlSignature !== controlSignature && !cell.td.contains(document.activeElement) && !cell.control.isDrafting?.()) {
cell.control = createCellControl(spec, () => node.row, this.context, column.key);
cell.controlSignature = controlSignature;
cell.td.replaceChildren(cell.control.root);
cell.td.className = 'cell-edit';
}
if (cell.controlSignature !== controlSignature) this.pendingRender = true;
cell.control?.sync();
} else {
if (cell.td.contains(document.activeElement)) { this.pendingRender = true; return; }
cell.control = null;
cell.controlSignature = null;
const value = row[column.key];
const text = typeof value==='number'?number(value):textValue(value);
if (cell.td.textContent !== text) cell.td.textContent = text;
@@ -231,7 +334,15 @@ export class DataTable {
});
this.empty.hidden = Boolean(rows.length);
this.table.hidden = !columns.length;
this.count.textContent = `共 ${rows.length} 项`;
const first = rows.length ? (this.page - 1) * this.pageSize + 1 : 0;
const last = rows.length ? Math.min(rows.length, first + visible.length - 1) : 0;
const countText = `共 ${rows.length} 项,显示 ${first}–${last} 项${this.pendingRender ? ';编辑完成后更新排列' : ''}`;
if (this.count.textContent !== countText) this.count.textContent = countText;
this.firstPage.disabled = this.previousPage.disabled = this.page === 1;
this.nextPage.disabled = this.lastPage.disabled = this.page === this.pageCount;
this.pageInput.max = String(this.pageCount);
if (document.activeElement !== this.pageInput) this.pageInput.value = String(this.page);
this.pageTotal.textContent = `页 / 共 ${this.pageCount} 页`;
for (const th of this.head.querySelectorAll('[data-column]')) {
const activeSort = this.sort?.key === th.dataset.column;
th.setAttribute('aria-sort', activeSort ? this.sort.direction === 1 ? 'ascending' : 'descending' : 'none');
@@ -239,6 +350,22 @@ export class DataTable {
}
this.syncSelection();
}
sortValue(column, row) {
const edit = columnEdit(column, row);
const value = edit ? this.context.get(editPath(edit.path, row), ['target', 'priority_target', 'target_priority'].includes(edit.type) ? undefined : edit.value ?? row[column.key]) : row[column.key];
if (['target', 'priority_target', 'target_priority'].includes(edit?.type)) return Number(value !== undefined && value !== null && value !== false && value !== 0);
const type = edit?.type || column.type;
if (['boolean', 'bool', 'checkbox'].includes(type)) return Number(Boolean(value));
if (['integer', 'int', 'number', 'float', 'priority'].includes(type) && value !== '' && value != null && Number.isFinite(Number(value))) return Number(value);
return value;
}
destroy() {
this.destroyed = true;
this.table.removeEventListener('focusout', this.onFocusOut);
this.nodes.clear();
}
}
export class GroupedTables {
@@ -257,7 +384,7 @@ export class GroupedTables {
if (!grouped.has(key)) grouped.set(key, []);
grouped.get(key).push(row);
});
for (const [key, group] of this.groups) if (!grouped.has(key)) { group.root.remove(); this.groups.delete(key); }
for (const [key, group] of this.groups) if (!grouped.has(key)) { group.table?.destroy(); group.root.remove(); this.groups.delete(key); }
grouped.forEach((items, key) => {
let group = this.groups.get(key);
if (!group) {
@@ -275,6 +402,7 @@ export class GroupedTables {
group.summary.replaceChildren(document.createTextNode(labels[key] || key), el('small', {text: `${items.length} 项`}));
group.columns=columns;group.items=items;
if(group.root.open)this.renderGroup(group);
else if(group.table) { group.table.setRows(items); group.table.syncSelection(); }
});
if (!grouped.size) {
if (!this.empty) { this.empty = el('div', {class: 'empty-state', text: '当前筛选下没有条目。'}); this.host.append(this.empty); }
@@ -289,4 +417,5 @@ export class GroupedTables {
expand(open) { this.groups.forEach(group => { group.root.open = open; }); }
selectedRows() { return [...this.groups.values()].flatMap(group => group.table?.selectedRows() || []); }
destroy() { this.groups.forEach(group => group.table?.destroy()); this.groups.clear(); }
}