Add Web 2 workspace and controlled deployment updates
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
export class ApiError extends Error {
|
||||
constructor(message, status, detail) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.detail = detail;
|
||||
}
|
||||
}
|
||||
|
||||
function errorMessage(data, status) {
|
||||
if (typeof data?.detail === 'string') return data.detail;
|
||||
if (typeof data?.error === 'string') return data.error;
|
||||
if (typeof data?.message === 'string') return data.message;
|
||||
if (Array.isArray(data?.detail)) return data.detail.map(item => `${(item.loc || []).slice(1).join('.')}: ${item.msg}`).join(';');
|
||||
return `请求未完成(HTTP ${status})`;
|
||||
}
|
||||
|
||||
export async function request(path, {method = 'GET', body, signal, blob = false} = {}) {
|
||||
const headers = {Accept: blob ? '*/*' : 'application/json'};
|
||||
if (body !== undefined && !(body instanceof FormData)) headers['Content-Type'] = 'application/json';
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(path, {method, credentials: 'same-origin', cache: 'no-store', headers, signal,
|
||||
body: body === undefined ? undefined : body instanceof FormData ? body : JSON.stringify(body)});
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') throw error;
|
||||
throw new ApiError('无法连接 Web 服务,请检查服务是否仍在运行。', 0);
|
||||
}
|
||||
if (response.status === 401 && !path.startsWith('/api/auth/')) window.dispatchEvent(new CustomEvent('auth-required'));
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
throw new ApiError(errorMessage(data, response.status), response.status, data);
|
||||
}
|
||||
if (blob) return response.blob();
|
||||
if (response.status === 204) return null;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export const accountURL = id => `/api/accounts/${encodeURIComponent(id)}`;
|
||||
export const api = {
|
||||
auth: () => request('/api/auth/status'),
|
||||
login: password => request('/api/auth/login', {method: 'POST', body: {password}}),
|
||||
logout: () => request('/api/auth/logout', {method: 'POST', body: {}}),
|
||||
meta: () => request('/api/meta'),
|
||||
schema: () => request('/api/schema'),
|
||||
accounts: () => request('/api/accounts'),
|
||||
create: (label, demo) => request('/api/accounts', {method: 'POST', body: {label, demo}}),
|
||||
remove: id => request(accountURL(id), {method: 'DELETE'}),
|
||||
status: id => request(`${accountURL(id)}/status`),
|
||||
config: id => request(`${accountURL(id)}/config`),
|
||||
save: (id, config, revision) => request(`${accountURL(id)}/config`, {method: 'PUT', body: {config, revision}}),
|
||||
view: (id, page, query = {}) => request(`${accountURL(id)}/views/${encodeURIComponent(page)}?query=${encodeURIComponent(JSON.stringify(query))}`),
|
||||
action: (id, operation, payload = {}) => request(`${accountURL(id)}/actions/${encodeURIComponent(operation)}`, {method: 'POST', body: payload}),
|
||||
job: (id, job) => request(`${accountURL(id)}/jobs/${encodeURIComponent(job)}`),
|
||||
logs: (id, after, debug) => request(`${accountURL(id)}/logs?after=${encodeURIComponent(after)}&debug=${debug}`),
|
||||
debugEntry: (id, entry) => request(`${accountURL(id)}/debug/${encodeURIComponent(entry)}`),
|
||||
exportConfig: id => request(`${accountURL(id)}/config/export`),
|
||||
importConfig: (id, config) => request(`${accountURL(id)}/config/import`, {method: 'POST', body: config}),
|
||||
health: options => request('/api/health', options),
|
||||
updates: options => request('/api/system/updates', options),
|
||||
checkUpdates: options => request('/api/system/updates/check', {...options, method: 'POST', body: {}}),
|
||||
applyUpdate: (version, options) => request('/api/system/updates/apply', {...options, method: 'POST', body: version ? {version} : {}}),
|
||||
};
|
||||
@@ -0,0 +1,511 @@
|
||||
import {api, request} from './api.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};
|
||||
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) { 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'){await api.logout();state.ready=false;location.reload();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){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 detail;if(entry.detail_url&&new URL(entry.detail_url,location.href).origin===location.origin)detail=await request(entry.detail_url);else detail=await 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(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;}
|
||||
}
|
||||
|
||||
async function requireAuth() {
|
||||
state.ready=false;const root=$('#auth-dialog');if(!root.open)root.showModal();$('#admin-password').focus();
|
||||
}
|
||||
|
||||
async function bootstrap() {
|
||||
try{
|
||||
const auth=await api.auth();if(auth.required&&!auth.authenticated){requireAuth();return;}
|
||||
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
|
||||
$('#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();state.ready=true;setStatus('工作台已连接');
|
||||
}catch(failure){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]);});
|
||||
$('#auth-form').addEventListener('submit',async event=>{event.preventDefault();const input=$('#admin-password');const password=input.value;input.value='';const button=$('button',event.currentTarget);button.disabled=true;try{await api.login(password);$('#auth-dialog').close();$('#auth-error').hidden=true;await bootstrap();}catch(failure){$('#auth-error').textContent=failure.message;$('#auth-error').hidden=false;input.focus();}finally{button.disabled=false;}});
|
||||
$('#auth-dialog').addEventListener('cancel',event=>event.preventDefault());window.addEventListener('auth-required',requireAuth);
|
||||
window.addEventListener('beforeunload',event=>{if([...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();
|
||||
@@ -0,0 +1,116 @@
|
||||
// Every supplied string is rendered as text, including names, errors and logs.
|
||||
export function el(tag, attributes = {}, ...children) {
|
||||
const node = document.createElement(tag);
|
||||
for (const [key, value] of Object.entries(attributes)) {
|
||||
if (value === undefined || value === null || value === false) continue;
|
||||
if (key === 'class') node.className = value;
|
||||
else if (key === 'text') node.textContent = String(value);
|
||||
else if (key.startsWith('on') && typeof value === 'function') node.addEventListener(key.slice(2).toLowerCase(), value);
|
||||
else if (['checked', 'disabled', 'hidden', 'value', 'multiple', 'required', 'open'].includes(key)) node[key] = value;
|
||||
else node.setAttribute(key, value === true ? '' : String(value));
|
||||
}
|
||||
for (const child of children.flat(Infinity)) {
|
||||
if (child !== null && child !== undefined && child !== false) node.append(child instanceof Node ? child : document.createTextNode(String(child)));
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
export const $ = (selector, root = document) => root.querySelector(selector);
|
||||
export const $$ = (selector, root = document) => [...root.querySelectorAll(selector)];
|
||||
export const clone = value => structuredClone(value);
|
||||
export const pathKey = path => JSON.stringify(path);
|
||||
const blockedKeys = new Set(['__proto__', 'prototype', 'constructor']);
|
||||
|
||||
export function getPath(object, path, fallback) {
|
||||
let value = object;
|
||||
for (const key of path || []) {
|
||||
if (blockedKeys.has(String(key)) || value == null || !Object.hasOwn(value, key)) return fallback;
|
||||
value = value[key];
|
||||
}
|
||||
return value === undefined ? fallback : value;
|
||||
}
|
||||
|
||||
export function setPath(object, path, value) {
|
||||
if (!Array.isArray(path) || !path.length || path.some(key => blockedKeys.has(String(key)))) throw new Error('配置字段路径无效');
|
||||
let current = object;
|
||||
path.slice(0, -1).forEach((key, index) => {
|
||||
if (!current[key] || typeof current[key] !== 'object') current[key] = typeof path[index + 1] === 'number' ? [] : {};
|
||||
current = current[key];
|
||||
});
|
||||
if (value === undefined) delete current[path.at(-1)];
|
||||
else current[path.at(-1)] = clone(value);
|
||||
}
|
||||
|
||||
export function textValue(value) {
|
||||
if (value === null || value === undefined || value === '') return '—';
|
||||
if (typeof value === 'boolean') return value ? '是' : '否';
|
||||
if (Array.isArray(value)) return value.map(textValue).join(' / ');
|
||||
if (typeof value === 'object') return Object.entries(value).map(([key, item]) => `${key}: ${textValue(item)}`).join(';');
|
||||
return String(value);
|
||||
}
|
||||
|
||||
export function number(value) {
|
||||
if (value === null || value === undefined) return '—';
|
||||
const numeric=Number(value);
|
||||
if(!Number.isFinite(numeric))return textValue(value);
|
||||
return numeric.toLocaleString('zh-CN',Number.isInteger(numeric)?{}:{maximumSignificantDigits:6});
|
||||
}
|
||||
|
||||
export function chinaTime(value, {date=false} = {}) {
|
||||
if(value===null || value===undefined || value==='')return '';
|
||||
const parsed=typeof value==='number'?new Date(value<1e12?value*1000:value):new Date(value);
|
||||
if(!Number.isFinite(parsed.getTime()))return String(value);
|
||||
return new Intl.DateTimeFormat('zh-CN',{timeZone:'Asia/Shanghai',hour12:false,hour:'2-digit',minute:'2-digit',second:'2-digit',
|
||||
...(date?{year:'numeric',month:'2-digit',day:'2-digit'}:{})}).format(parsed);
|
||||
}
|
||||
|
||||
export function optionsList(options) {
|
||||
if (!options) return [];
|
||||
if (!Array.isArray(options)) return Object.entries(options).map(([value, label]) => ({value, label}));
|
||||
return options.map(option => Array.isArray(option) ? {value: option[0], label: option[1]} : typeof option === 'object' ? {value: option.value ?? option.id ?? option.key, label: option.label ?? option.name ?? String(option.value ?? option.id), ...option} : {value: option, label: String(option)});
|
||||
}
|
||||
|
||||
export function download(blob, filename) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = el('a', {href: url, download: filename});
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
export function csvBlob(columns, rows) {
|
||||
// Spreadsheet text must not become a formula when a nickname starts with '='.
|
||||
const escape = value => {
|
||||
let text = value == null ? '' : textValue(value);
|
||||
if (/^[\s]*[=+@\-]/u.test(text) && !/^-?\d+(\.\d+)?$/u.test(text)) text = "'" + text;
|
||||
return '"' + text.replaceAll('"', '""') + '"';
|
||||
};
|
||||
const lines = [columns.map(column => escape(column.label)).join(','), ...rows.map(row => columns.map(column => escape(row[column.key])).join(','))];
|
||||
return new Blob(['\ufeff', lines.join('\r\n')], {type: 'text/csv;charset=utf-8'});
|
||||
}
|
||||
|
||||
export function empty(message) {
|
||||
return el('div', {class: 'empty-state'}, el('p', {text: message}));
|
||||
}
|
||||
|
||||
export function detailsList(value, labels = {}) {
|
||||
const list = el('dl', {class: 'detail-list'});
|
||||
for (const [key, item] of Object.entries(value || {})) {
|
||||
list.append(el('dt', {text: labels[key] || key}), el('dd', {text: textValue(item)}));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
export function tabKeys(container, selector) {
|
||||
container.addEventListener('keydown', event => {
|
||||
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
|
||||
const tabs = $$(selector, container).filter(tab => !tab.disabled);
|
||||
const index = tabs.indexOf(document.activeElement);
|
||||
if (index < 0) return;
|
||||
const next = event.key === 'Home' ? 0 : event.key === 'End' ? tabs.length - 1 : (index + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length;
|
||||
event.preventDefault();
|
||||
tabs[next]?.focus();
|
||||
tabs[next]?.click();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import {el, $, optionsList, pathKey} from './dom.js';
|
||||
|
||||
function readNumber(input, integer = true) {
|
||||
if (input.value.trim() === '' || !input.checkValidity()) return undefined;
|
||||
const value = Number(input.value);
|
||||
return Number.isFinite(value) && (!integer || Number.isInteger(value)) ? value : undefined;
|
||||
}
|
||||
|
||||
// A control is created once, then synchronized without replacing its input node.
|
||||
export function control(field, {get, set, onError = () => {}}) {
|
||||
const type = field.type || 'text';
|
||||
const path = field.path || [];
|
||||
const label = field.label || path.at(-1) || '设置';
|
||||
let root, sync;
|
||||
const commit = value => {
|
||||
try { set(path, value, field); } catch (error) { onError(error); }
|
||||
};
|
||||
const value = () => get(path, field.value);
|
||||
if (type === 'add_rule') {
|
||||
const select = el('select', {'aria-label': label}, el('option', {value: '', text: '选择魔物蛋(含无库存)'}), ...optionsList(field.options).map(option => el('option', {value: option.value, text: `${option.label} [${option.value}]`})));
|
||||
const add = el('button', {type: 'button', text: '添加无库存蛋规则'});
|
||||
add.addEventListener('click', () => {
|
||||
if (!select.value) { select.focus(); return; }
|
||||
const defaults=field.defaults_by_id?.[select.value] || field.defaults || {};
|
||||
set([...path, select.value], get([...path, select.value], defaults), field);
|
||||
});
|
||||
root = el('div', {class: 'inline-editor'}, select, add);
|
||||
sync = () => {};
|
||||
} 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()); };
|
||||
} else if (['select', 'enum'].includes(type)) {
|
||||
root = el('select', {'aria-label': label});
|
||||
let optionsSignature;
|
||||
const fill = () => {
|
||||
const options = optionsList(typeof field.options === 'function' ? field.options() : field.options);
|
||||
const signature = JSON.stringify(options);
|
||||
if (signature !== optionsSignature && document.activeElement !== root) {
|
||||
root.replaceChildren(...options.map(option => el('option', {value: String(option.value), text: option.label, disabled: option.disabled})));
|
||||
optionsSignature = signature;
|
||||
}
|
||||
return options;
|
||||
};
|
||||
root.addEventListener('change', () => {
|
||||
const selected = fill().find(option => String(option.value) === root.value);
|
||||
if (selected) commit(selected.value);
|
||||
});
|
||||
sync = () => {
|
||||
fill();
|
||||
if (document.activeElement !== root) root.value = String(value() ?? '');
|
||||
};
|
||||
} else if (['multiselect', 'multi_select'].includes(type)) {
|
||||
root = el('div', {class: 'multi-select', role: 'group', 'aria-label': label});
|
||||
const items = optionsList(field.options).map(option => {
|
||||
const check = el('input', {type: 'checkbox', 'aria-label': option.label});
|
||||
check.addEventListener('change', () => commit(items.filter(item => item.check.checked).map(item => item.option.value)));
|
||||
root.append(el('label', {}, check, option.label));
|
||||
return {check, option};
|
||||
});
|
||||
sync = () => items.forEach(({check, option}) => { check.checked = (value() || []).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'});
|
||||
const add = el('button', {type: 'button', class: 'small', text: '添加编号 / 数量'});
|
||||
root.append(lines, add);
|
||||
let signature;
|
||||
const save = () => {
|
||||
const result = {};
|
||||
for (const line of [...lines.children]) {
|
||||
const id = $('input[data-part=id]', line), count = $('input[data-part=count]', line);
|
||||
if (!id.value.trim() && count.value === '') continue;
|
||||
const number = readNumber(count);
|
||||
if (!/^[1-9]\d*$/.test(id.value.trim()) || number === undefined || result[id.value.trim()] !== undefined) {
|
||||
id.setCustomValidity('请输入不重复的正整数编号和有效数量');
|
||||
return;
|
||||
}
|
||||
id.setCustomValidity('');
|
||||
result[id.value.trim()] = number;
|
||||
}
|
||||
signature = JSON.stringify(result);
|
||||
commit(result);
|
||||
};
|
||||
const addLine = (id = '', count = '') => {
|
||||
const idInput = el('input', {type: 'text', inputmode: 'numeric', value: id, placeholder: '编号', 'aria-label': `${label}物品编号`, 'data-part': 'id', class: 'count-id'});
|
||||
const countInput = el('input', {type: 'number', min: 0, max: 1000000000, step: 1, value: count, placeholder: '数量', 'aria-label': `${label}数量`, 'data-part': 'count'});
|
||||
const line = el('div', {class: 'inline-editor'}, idInput, countInput);
|
||||
line.append(el('button', {type: 'button', class: 'small', text: '移除', onClick: () => { line.remove(); save(); }}));
|
||||
idInput.addEventListener('input', () => { idInput.setCustomValidity(''); save(); });
|
||||
countInput.addEventListener('input', save);
|
||||
lines.append(line);
|
||||
return idInput;
|
||||
};
|
||||
add.addEventListener('click', () => addLine().focus());
|
||||
sync = () => {
|
||||
if (root.contains(document.activeElement)) return;
|
||||
const next = value() || {};
|
||||
if (JSON.stringify(next) === signature) return;
|
||||
lines.replaceChildren();
|
||||
Object.entries(next).forEach(([id, count]) => addLine(id, count));
|
||||
signature = JSON.stringify(next);
|
||||
};
|
||||
} else {
|
||||
const numeric = ['integer', 'int', 'number', 'float', 'priority'].includes(type);
|
||||
root = el('input', {type: numeric ? 'number' : 'text', 'aria-label': label, min: field.min ?? (numeric ? 0 : undefined), max: field.max,
|
||||
step: field.step ?? (['number', 'float'].includes(type) ? 'any' : numeric ? 1 : undefined), placeholder: field.placeholder});
|
||||
root.addEventListener('input', () => {
|
||||
if (numeric) {
|
||||
const next = readNumber(root, !['number', 'float'].includes(type));
|
||||
if (next !== undefined) commit(next);
|
||||
} else if (['id_list', 'ids'].includes(type)) {
|
||||
const parts = root.value.split(/[,,;;\s]+/).filter(Boolean);
|
||||
if (parts.some(part => !/^[1-9]\d*$/.test(part))) { root.setCustomValidity('编号须为正整数,多个编号用逗号分隔'); return; }
|
||||
root.setCustomValidity('');
|
||||
commit([...new Set(parts.map(Number))]);
|
||||
} else commit(root.value);
|
||||
});
|
||||
sync = () => {
|
||||
if (document.activeElement === root) return;
|
||||
const next = value();
|
||||
root.value = ['id_list', 'ids'].includes(type) ? (next || []).join(', ') : next ?? '';
|
||||
};
|
||||
}
|
||||
root.dataset.configPath = pathKey(path);
|
||||
root.title = field.help || field.description || label;
|
||||
root.disabled = Boolean(field.disabled || field.readonly);
|
||||
sync();
|
||||
return {root, sync, field};
|
||||
}
|
||||
|
||||
export class PolicyForm {
|
||||
constructor(host, context) {
|
||||
this.host = host;
|
||||
this.context = context;
|
||||
this.controls = [];
|
||||
this.signature = '';
|
||||
}
|
||||
|
||||
update(fields = []) {
|
||||
if (!Array.isArray(fields)) fields = fields.fields || [];
|
||||
const signature = JSON.stringify(fields.map(({value, ...field}) => field));
|
||||
if (signature !== this.signature && !this.host.contains(document.activeElement)) {
|
||||
this.host.replaceChildren();
|
||||
this.controls = [];
|
||||
const groups = new Map();
|
||||
fields.forEach(field => {
|
||||
if (!Array.isArray(field.path) || field.hidden) return;
|
||||
const group = field.group || '';
|
||||
if (!groups.has(group)) {
|
||||
const grid = el('div', {class: 'form-grid'});
|
||||
const section = group ? el('fieldset', {class: 'form-section'}, el('legend', {text: group}), grid) : grid;
|
||||
this.host.append(section);
|
||||
groups.set(group, grid);
|
||||
}
|
||||
const entry = control(field, this.context);
|
||||
entry.root.classList.add('field-input');
|
||||
const boolean = ['boolean', 'bool', 'checkbox'].includes(field.type);
|
||||
const wide = ['id_counts', 'counts', 'reserves', 'multiselect'].includes(field.type);
|
||||
const row = el('label', {class: `field${boolean ? ' checkbox-field' : ''}${wide ? ' field-wide' : ''}`, title: field.help || field.description || ''});
|
||||
if (entry.root.tagName === 'DIV') {
|
||||
const fieldRow = el('div', {class: `field${wide ? ' field-wide' : ''}`}, el('span', {class: 'field-label', text: field.label}), entry.root);
|
||||
groups.get(group).append(fieldRow);
|
||||
entry.row = fieldRow;
|
||||
} else {
|
||||
row.append(el('span', {class: 'field-label', text: field.label}), entry.root);
|
||||
groups.get(group).append(row);
|
||||
entry.row = row;
|
||||
}
|
||||
if (field.help || field.description) groups.get(group).append(el('span', {class: 'field-help', text: field.help || field.description}));
|
||||
this.controls.push(entry);
|
||||
});
|
||||
this.signature = signature;
|
||||
}
|
||||
this.host.hidden = !fields.length;
|
||||
this.controls.forEach(entry => {
|
||||
const latest = fields.find(field => pathKey(field.path) === 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)));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Keep native number behavior only for the number field the user is editing.
|
||||
document.addEventListener('wheel', event => {
|
||||
const input = event.target.closest?.('input[type=number]');
|
||||
if (input && document.activeElement !== input) event.preventDefault();
|
||||
}, {passive: false});
|
||||
@@ -0,0 +1,50 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<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="牧羊人之心牧场助手">
|
||||
<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>
|
||||
<dialog id="auth-dialog" aria-labelledby="auth-title"><form id="auth-form"><h1 id="auth-title">登录管理工作台</h1><p>请输入此 Web 工作台的管理密码。</p><label class="field">管理密码<input id="admin-password" type="password" autocomplete="current-password" required></label><p id="auth-error" class="error-text" role="alert" hidden></p><div class="dialog-footer"><button type="submit" class="primary">登录</button></div></form></dialog>
|
||||
<noscript>此工作台需要启用 JavaScript 才能连接本地服务。</noscript>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,357 @@
|
||||
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.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: '记住的账号密码和登录会话由服务端加密保存。浏览器不会保存游戏凭据。退出或恢复会话后,策略保持关闭。'}));
|
||||
host.append(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.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;
|
||||
}
|
||||
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
: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}
|
||||
@@ -0,0 +1,292 @@
|
||||
import {el, $, optionsList, pathKey, textValue, number} from './dom.js';
|
||||
import {control} from './forms.js';
|
||||
|
||||
export function editPath(template, row) {
|
||||
return (template || []).map(part => {
|
||||
if (typeof part !== 'string') return part;
|
||||
if (['*', '{id}', '$id', ':id'].includes(part)) return String(row.id);
|
||||
const match = part.match(/^\{(?:row\.)?([^}]+)\}$|^\$row\.(.+)$/);
|
||||
if (match) return String(row[match[1] || match[2]] ?? row.id);
|
||||
return part;
|
||||
});
|
||||
}
|
||||
|
||||
function editableSpec(column, row) {
|
||||
const edit = column.edit || row.edits?.[column.key] ? {...column.edit, ...row.edits?.[column.key]} : null;
|
||||
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);
|
||||
const target = ['target', 'priority_target', 'target_priority'].includes(spec.type);
|
||||
if (target) {
|
||||
const checkbox = el('input', {type: 'checkbox', 'aria-label': spec.label});
|
||||
const root = el('div', {class: 'inline-editor'}, checkbox);
|
||||
root.dataset.configPath = pathKey(spec.path);
|
||||
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;
|
||||
checkbox.disabled = Boolean(spec.disabled);
|
||||
};
|
||||
sync();
|
||||
return {root, sync, field: spec};
|
||||
}
|
||||
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 || []);
|
||||
let drafting=false;
|
||||
const hint=el('span',{class:'member-draft-note',hidden:true});
|
||||
const selects = Array.from({length: spec.count || 3}, (_, index) => {
|
||||
const select = el('select', {'aria-label': `${spec.label}${index === 0 ? '队长' : `队员${index}`}`, disabled: spec.disabled},
|
||||
el('option', {value: '', text: index === 0 ? '自动选择队长' : '自动选择队员'}),
|
||||
...options.map(option => el('option', {value: option.value, text: option.label, disabled: option.disabled})));
|
||||
select.addEventListener('change', () => {
|
||||
selects.forEach(item=>item.setCustomValidity(''));
|
||||
const slots=selects.map(item=>item.value), selected=slots.filter(Boolean).map(Number);
|
||||
if(!select.value){drafting=false;selects.forEach(item=>item.value='');hint.hidden=true;set(spec.path,[],spec);return;}
|
||||
drafting=true;
|
||||
const invalid=message=>{hint.textContent=message;hint.hidden=false;select.setCustomValidity(message);};
|
||||
if (new Set(selected).size !== selected.length) {invalid('探险队员不可重复');return;}
|
||||
if(selected.length!==3){invalid(`已选择 ${selected.length}/3 只;选满队长和两名队员后保存`);return;}
|
||||
const leader=options.find(option=>Number(option.value)===selected[0]);
|
||||
if(leader&&selected.slice(1).some(id=>(options.find(option=>Number(option.value)===id)?.level || 0)>leader.level)){invalid('队员等级不可高于队长');return;}
|
||||
drafting=false;hint.hidden=true;set(spec.path, selected, spec);
|
||||
});
|
||||
root.append(select);
|
||||
return select;
|
||||
});
|
||||
const auto = el('button', {type: 'button', class: 'small', text: '自动选三只', disabled: spec.disabled,
|
||||
title: '清除手动指定,由核心选择未被战斗队和培养目标占用的空闲魔物', onClick: () => {drafting=false;selects.forEach(item=>{item.value='';item.setCustomValidity('');});hint.hidden=true;set(spec.path, [], spec);}});
|
||||
root.append(auto,hint);
|
||||
const sync = () => {
|
||||
if(drafting)return;
|
||||
const selected = get(spec.path, []) || [];
|
||||
selects.forEach((select, index) => { if (document.activeElement !== select) select.value = String(selected[index] ?? ''); });
|
||||
};
|
||||
sync();
|
||||
return {root, sync, field: spec};
|
||||
}
|
||||
return control(spec, {get, set, onError: context.onError});
|
||||
}
|
||||
|
||||
export class DataTable {
|
||||
constructor(host, context, {selection = true, emptyMessage = '当前筛选下没有条目。'} = {}) {
|
||||
this.host = host;
|
||||
this.context = context;
|
||||
this.selection = selection;
|
||||
this.emptyMessage = emptyMessage;
|
||||
this.rows = [];
|
||||
this.nodes = new Map();
|
||||
this.selected = new Set();
|
||||
this.sort = null;
|
||||
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);
|
||||
host.append(this.scroller, this.footer);
|
||||
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)) {
|
||||
this.selected.clear();
|
||||
this.selected.add(id);
|
||||
this.syncSelection();
|
||||
}
|
||||
context.onContext?.(event, this.selectedRows(), this.rows.find(row => String(row.id) === id));
|
||||
});
|
||||
}
|
||||
|
||||
selectedRows() { return this.rows.filter(row => this.selected.has(String(row.id))); }
|
||||
|
||||
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} 项` : '';
|
||||
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;
|
||||
}
|
||||
this.context.onSelection?.(this.selectedRows());
|
||||
}
|
||||
|
||||
buildHead(columns) {
|
||||
this.head.replaceChildren();
|
||||
this.nodes.clear();
|
||||
this.body.replaceChildren();
|
||||
const row = el('tr');
|
||||
if (this.selection) {
|
||||
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.syncSelection();
|
||||
});
|
||||
row.append(el('th', {scope: 'col', class: 'selection-cell'}, this.allCheck));
|
||||
}
|
||||
columns.forEach(column => {
|
||||
const mark = el('span', {class: 'sort-mark', 'aria-hidden': 'true'});
|
||||
const label = column.key === 'keep_count' ? '牧场保留' : column.label;
|
||||
const button = el('button', {type: 'button', title: `按${label}排序`}, label, mark);
|
||||
const th = el('th', {scope: 'col', 'data-column': column.key}, button);
|
||||
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.update(this.columns, this.rows);
|
||||
});
|
||||
row.append(th);
|
||||
});
|
||||
this.head.append(row);
|
||||
}
|
||||
|
||||
update(columns = [], rows = []) {
|
||||
const signature = JSON.stringify(columns);
|
||||
if (this.signature !== signature) {
|
||||
if (this.host.contains(document.activeElement) && this.signature) return;
|
||||
this.columns = columns;
|
||||
this.signature = signature;
|
||||
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) {
|
||||
const {key, direction} = this.sort;
|
||||
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;
|
||||
});
|
||||
}
|
||||
sorted.forEach((row, index) => {
|
||||
const id = String(row.id ?? index);
|
||||
let node = this.nodes.get(id);
|
||||
if (!node) {
|
||||
const tr = el('tr', {'data-row-id': id, 'aria-selected': 'false', tabindex: -1});
|
||||
const check = this.selection ? el('input', {type: 'checkbox', 'aria-label': `选择 ${row.name || row.label || id}`}) : null;
|
||||
if (check) {
|
||||
check.addEventListener('change', () => { check.checked ? this.selected.add(id) : this.selected.delete(id); this.syncSelection(); });
|
||||
tr.append(el('td', {class: 'selection-cell'}, check));
|
||||
}
|
||||
tr.addEventListener('click', event => {
|
||||
if (event.target.closest('input,select,button,a,label')) return;
|
||||
if (!event.ctrlKey && !event.metaKey && !event.shiftKey) this.selected.clear();
|
||||
this.selected.add(id);
|
||||
this.syncSelection();
|
||||
});
|
||||
tr.addEventListener('dblclick', event => {
|
||||
if (!event.target.closest('input,select,button,a,label')) this.context.onDetail?.(node.row);
|
||||
});
|
||||
node = {tr, check, cells: new Map(), row};
|
||||
this.nodes.set(id, node);
|
||||
}
|
||||
node.row = row;
|
||||
columns.forEach(column => {
|
||||
let cell = node.cells.get(column.key);
|
||||
if (!cell) {
|
||||
const td = el('td', {'data-column': column.key});
|
||||
cell = {td};
|
||||
node.cells.set(column.key, cell);
|
||||
node.tr.append(td);
|
||||
}
|
||||
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);
|
||||
cell.controlSignature = controlSignature;
|
||||
cell.td.replaceChildren(cell.control.root);
|
||||
cell.td.className = 'cell-edit';
|
||||
}
|
||||
cell.control?.sync();
|
||||
} else {
|
||||
const value = row[column.key];
|
||||
const text = typeof value==='number'?number(value):textValue(value);
|
||||
if (cell.td.textContent !== text) cell.td.textContent = text;
|
||||
cell.td.title = row.tooltips?.[column.key] || text;
|
||||
cell.td.className = `${typeof value === 'number' || ['number', 'integer'].includes(column.type) ? 'number ' : ''}${column.type === 'wrap' ? 'cell-wrap' : 'cell-ellipsis'}`;
|
||||
}
|
||||
});
|
||||
// Inserting a node unnecessarily can blur a focused native number input.
|
||||
const existing = this.body.children[index];
|
||||
if (existing !== node.tr && !node.tr.contains(document.activeElement)) this.body.insertBefore(node.tr, existing || null);
|
||||
});
|
||||
this.empty.hidden = Boolean(rows.length);
|
||||
this.table.hidden = !columns.length;
|
||||
this.count.textContent = `共 ${rows.length} 项`;
|
||||
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');
|
||||
$('.sort-mark', th).textContent = activeSort ? this.sort.direction === 1 ? '▲' : '▼' : '';
|
||||
}
|
||||
this.syncSelection();
|
||||
}
|
||||
}
|
||||
|
||||
export class GroupedTables {
|
||||
constructor(host, context, {collapsed = true} = {}) {
|
||||
this.host = host;
|
||||
this.context = context;
|
||||
this.collapsed = collapsed;
|
||||
this.groups = new Map();
|
||||
this.host.classList.add('grouped-tables');
|
||||
}
|
||||
|
||||
update(columns, rows, groupBy, labels = {}, metadata = {}) {
|
||||
const grouped = new Map();
|
||||
rows.forEach(row => {
|
||||
const key = String(typeof groupBy === 'function' ? groupBy(row) : row[groupBy] ?? '其他');
|
||||
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); }
|
||||
grouped.forEach((items, key) => {
|
||||
let group = this.groups.get(key);
|
||||
if (!group) {
|
||||
const summary = el('summary');
|
||||
const container = el('div', {class: 'group-table'});
|
||||
const root = el('details', {class: 'table-group', open: metadata[key]?.collapsed === false || !this.collapsed}, summary, container);
|
||||
container.style.display = 'flex';
|
||||
container.style.flexDirection = 'column';
|
||||
group = {root, summary, container, table:null};
|
||||
const item=group;
|
||||
root.addEventListener('toggle',()=>{if(root.open)this.renderGroup(item);});
|
||||
this.groups.set(key, group);
|
||||
this.host.append(root);
|
||||
}
|
||||
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);
|
||||
});
|
||||
if (!grouped.size) {
|
||||
if (!this.empty) { this.empty = el('div', {class: 'empty-state', text: '当前筛选下没有条目。'}); this.host.append(this.empty); }
|
||||
}
|
||||
if (this.empty) this.empty.hidden = Boolean(grouped.size);
|
||||
}
|
||||
|
||||
renderGroup(group) {
|
||||
if(!group.table)group.table=new DataTable(group.container,this.context);
|
||||
group.table.update(group.columns || [],group.items || []);
|
||||
}
|
||||
|
||||
expand(open) { this.groups.forEach(group => { group.root.open = open; }); }
|
||||
selectedRows() { return [...this.groups.values()].flatMap(group => group.table?.selectedRows() || []); }
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import {el, $, $$} from './dom.js';
|
||||
|
||||
let noticeTimer;
|
||||
export function notice(message, error = false) {
|
||||
const node = $('#notice');
|
||||
node.textContent = message;
|
||||
node.classList.toggle('error', error);
|
||||
node.hidden = false;
|
||||
clearTimeout(noticeTimer);
|
||||
noticeTimer = setTimeout(() => { node.hidden = true; }, error ? 10000 : 4500);
|
||||
}
|
||||
|
||||
let closeCurrent;
|
||||
export function dialog(title, content, {confirm = '确认', cancel = '取消', read = () => true, danger = false, info = false} = {}) {
|
||||
closeCurrent?.();
|
||||
const root = $('#action-dialog');
|
||||
const form = $('#dialog-form');
|
||||
const confirmButton = $('#dialog-confirm');
|
||||
$('#dialog-title').textContent = title;
|
||||
$('#dialog-content').replaceChildren(content);
|
||||
$('#dialog-error').hidden = true;
|
||||
confirmButton.textContent = confirm;
|
||||
confirmButton.hidden = info;
|
||||
confirmButton.disabled = false;
|
||||
confirmButton.className = danger ? 'danger' : 'primary';
|
||||
$('#dialog-cancel').textContent = info ? '关闭' : cancel;
|
||||
const previous = document.activeElement;
|
||||
root.showModal();
|
||||
return new Promise(resolve => {
|
||||
const abort = new AbortController();
|
||||
const done = value => {
|
||||
abort.abort();
|
||||
closeCurrent = null;
|
||||
root.close();
|
||||
$('#dialog-content').replaceChildren();
|
||||
previous?.isConnected && previous.focus();
|
||||
resolve(value);
|
||||
};
|
||||
closeCurrent = () => done(null);
|
||||
root.addEventListener('cancel', event => { event.preventDefault(); done(null); }, {signal: abort.signal});
|
||||
$('#dialog-cancel').addEventListener('click', () => done(null), {signal: abort.signal});
|
||||
$('.dialog-close', root).addEventListener('click', () => done(null), {signal: abort.signal});
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
if (!form.reportValidity()) return;
|
||||
confirmButton.disabled = true;
|
||||
try { const value = await read(); if (value !== undefined) done(value); }
|
||||
catch (error) { $('#dialog-error').textContent = error.message; $('#dialog-error').hidden = false; }
|
||||
finally { confirmButton.disabled = false; }
|
||||
}, {signal: abort.signal});
|
||||
const focus = $('input:not([type=checkbox]),select,textarea', content);
|
||||
(focus || (danger ? $('#dialog-cancel') : confirmButton.hidden ? $('#dialog-cancel') : confirmButton)).focus();
|
||||
});
|
||||
}
|
||||
|
||||
export async function confirm(title, message, options = {}) {
|
||||
return Boolean(await dialog(title, el('p', {text: message}), options));
|
||||
}
|
||||
|
||||
export function contextMenu(event, items) {
|
||||
document.querySelector('.context-menu')?.remove();
|
||||
const menu = el('div', {class: 'context-menu', role: 'menu', 'aria-label': '条目操作'});
|
||||
const abort = new AbortController();
|
||||
const close = () => { menu.remove(); abort.abort(); };
|
||||
items.forEach(item => menu.append(el('button', {type: 'button', role: 'menuitem', disabled: item.disabled, text: item.label,
|
||||
onClick: () => { close(); Promise.resolve(item.run()).catch(error => notice(error.message, true)); }})));
|
||||
document.body.append(menu);
|
||||
const rect = menu.getBoundingClientRect();
|
||||
menu.style.left = `${Math.max(4, Math.min(event.clientX, innerWidth - rect.width - 5))}px`;
|
||||
menu.style.top = `${Math.max(4, Math.min(event.clientY, innerHeight - rect.height - 5))}px`;
|
||||
document.addEventListener('pointerdown', action => { if (!menu.contains(action.target)) close(); }, {capture: true, signal: abort.signal});
|
||||
document.addEventListener('keydown', action => {
|
||||
if (action.key === 'Escape') close();
|
||||
if (['ArrowDown', 'ArrowUp'].includes(action.key)) {
|
||||
const buttons = $$('button:not(:disabled)', menu), index = buttons.indexOf(document.activeElement);
|
||||
buttons[(index + (action.key === 'ArrowDown' ? 1 : -1) + buttons.length) % buttons.length]?.focus();
|
||||
action.preventDefault();
|
||||
}
|
||||
}, {signal: abort.signal});
|
||||
document.addEventListener('scroll', close, {capture: true, once: true, signal: abort.signal});
|
||||
$('button:not(:disabled)', menu)?.focus();
|
||||
}
|
||||
|
||||
export function filePicker(accept) {
|
||||
return new Promise(resolve => {
|
||||
const input = el('input', {type: 'file', accept});
|
||||
input.addEventListener('change', () => resolve(input.files[0] || null), {once: true});
|
||||
input.addEventListener('cancel', () => resolve(null), {once: true});
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
export async function fileBase64(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.addEventListener('load', () => resolve(String(reader.result).split(',', 2)[1]));
|
||||
reader.addEventListener('error', () => reject(new Error('无法读取所选文件,请重新选择。')));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user