ui: simplify helper copy and center page loading feedback

This commit is contained in:
AttilaNet
2026-11-11 21:08:48 +08:00
parent d1e7f3c717
commit e23e7586c4
25 changed files with 747 additions and 141 deletions
+45 -31
View File
@@ -27,10 +27,10 @@ function strategyRequested(summary) { return typeof summary?.strategy_requested=
function strategyDetails(account) {
if(!account)return '';
const summary=account.summary,requested=strategyRequested(summary);
if(!requested)return summary.strategy_requested===false?'策略已停止(用户暂停);暂停会保留到再次“开启”,账号仍会按设定时长自动重登。':'策略已停止,可在顶部“开启”继续执行已勾选功能。';
if(summary.strategy_state==='blocked')return `策略等待处理:${summary.strategy_message || '请检查执行结果,确认后再继续。'}`;
if(summary.running && gameAvailable(account))return '角色状态自动刷新,正在自动执行已配置且已勾选的功能;可在顶部“停止”。';
const parts=['已请求自动执行已勾选功能,等待恢复;可在顶部“停止”暂停执行。'];
if(!requested)return summary.strategy_requested===false?'策略已停止(用户暂停)':'策略已停止';
if(summary.strategy_state==='blocked')return `策略等待处理:${summary.strategy_message || '等待确认执行结果'}`;
if(summary.running && gameAvailable(account))return '策略运行中';
const parts=['等待自动恢复'];
if(summary.strategy_message)parts.push(summary.strategy_message);
const value=summary.strategy_retry_at;
const retryAt=typeof value==='number'?(value<1e12?value*1000:value):Date.parse(value);
@@ -96,8 +96,8 @@ function renderPageConnection(page) {
}
const stale=!gameAvailable(page.account),message=connectionDetails(page.account);
page.connectionStatus.hidden=!stale;page.connectionStatus.textContent=message;
if(stale){page.loading.dataset.loading='false';page.loading.textContent=page.data?'已载入缓存':'缓存中暂无数据';clearTimeout(page.loadTimer);}
else if(page.loading.textContent.includes('缓存')){page.loading.textContent=page.data?'已载入':'正在读取…';page.loading.dataset.loading=String(!page.data);}
if(stale || page.root.hidden){clearTimeout(page.loadTimer);page.pending=false;}
page.setLoading(!stale && page.errorBox.hidden && (page.fetching || page.pending));
$$('button[data-operation]',page.actionsHost).filter(button=>gameRefreshOperations.has(button.dataset.operation)).forEach(button=>button.disabled=stale);
}
@@ -292,7 +292,7 @@ async function perform(account,operation,payload={},options={}) {
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==='forget_login')account.lastFailure='';
const message=loginOperations.has(operation)?account.summary.running && strategyRequested(account.summary)?'已读取角色,已自动开启策略,执行已配置且已勾选的功能;可在顶部“停止”。':`已读取角色。${strategyDetails(account)}`:result?.message;
const message=loginOperations.has(operation)?account.summary.running && strategyRequested(account.summary)?'已读取角色,策略运行中':`已读取角色。${strategyDetails(account)}`:result?.message;
if(message && operation!=='refresh')notice(message);
setStatus(operation==='refresh'?'状态已刷新':message || `${operationLabels[operation] || '操作'}已完成`);
return result;
@@ -310,15 +310,17 @@ function getPage(account,key) {
async function loadPage(page,force=false) {
if(!force && !gameAvailable(page.account) && (page.key!=='login'||state.webStatusError||page.account.transportErrors.has('status'))){clearTimeout(page.loadTimer);renderPageConnection(page);return;}
if(page.fetching){if(force)page.reload=true;return;}
page.fetching=true;const generation=page.generation || 0;
clearTimeout(page.loadTimer);
page.fetching=true;page.clearError();renderPageConnection(page);
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(generation!==(page.generation||0)){page.pending=false;return;}
page.pending=Boolean(response.loading);page.render(response.data);page.lastLoad=Date.now();
transportError(page.account,`view:${page.key}`,'页面数据',null);renderPageConnection(page);
if(response.loading && gameAvailable(page.account)){clearTimeout(page.loadTimer);page.loadTimer=setTimeout(()=>loadPage(page),650);}
}catch(failure){if(generation===(page.generation||0)){page.showError(failure.message);transportError(page.account,`view:${page.key}`,'页面数据',failure);}}
finally{page.fetching=false;if(page.reload){page.reload=false;loadPage(page);}}
if(page.pending && gameAvailable(page.account) && !page.root.hidden && page.root.isConnected)page.loadTimer=setTimeout(()=>loadPage(page),650);
}catch(failure){if(generation===(page.generation||0)){page.pending=false;clearTimeout(page.loadTimer);page.showError(failure.message);transportError(page.account,`view:${page.key}`,'页面数据',failure);}}
finally{page.fetching=false;renderPageConnection(page);if(page.reload){page.reload=false;loadPage(page);}}
}
function selectPage(key) {
@@ -326,7 +328,10 @@ function selectPage(key) {
saveLogScroll(account);
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;}));
state.accounts.forEach(other=>other.pages.forEach(page=>{
page.root.hidden=other.id!==account.id||page.key!==key;
if(page.root.hidden){clearTimeout(page.loadTimer);page.pending=false;page.setLoading(false);}
}));
const page=getPage(account,key);page.root.hidden=false;
renderLogs();
$$('.page-tab').forEach(tab=>{const selected=tab.dataset.page===key;tab.setAttribute('aria-selected',String(selected));tab.tabIndex=selected?0:-1;});
@@ -339,6 +344,7 @@ async function selectAccount(id) {
if(previous?.edits.size)flushConfig(previous).catch(error);
state.active=id;const account=current();if(!account)return;
$('#page-host').querySelector('.initial-state')?.remove();
$('#page-host').querySelector(':scope > .loading-state')?.remove();
renderAccountTabs();renderSummary();renderLogs(true);applyLogLayout(account);selectPage(account.page);
if(!account.config)try{await refreshConfig(account);}catch(failure){error(failure);}
fetchLogs(account);
@@ -346,7 +352,7 @@ async function selectAccount(id) {
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()})});
const result=await dialog(demo?'新增离线演示账号':'新增账号',el('label',{class:'field'},el('span',{class:'field-label',text:'账号名称'}),label),{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?'离线演示账号已创建':'账号已创建,请在登录页登录。');
}
@@ -409,7 +415,7 @@ async function exportYields(account=current()) {
async function command(name,account=current()) {
try {
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.4'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`}),el('p',{class:'info-note',text:'与桌面助手共用核心策略。配置在服务端自动保存;在线时默认自动执行已勾选功能,连接恢复后继续执行。顶部“停止”仅暂停执行,暂停在重新登录和服务重启后仍保留,直到再次“开启”。已保存的账号按设定时长自动重登,退出登录不取消;只有清除登录记录或删除账号才取消。'})),{info:true});
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.5'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true});
if(name==='updates')return await showUpdates();
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
if(!account)throw new Error('请先新增或选择账号。');
@@ -429,7 +435,7 @@ async function command(name,account=current()) {
}
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;
await api.remove(account.id);account.jobs.forEach(record=>record.reject(new Error('账号已移除')));account.pages.forEach(page=>{clearTimeout(page.loadTimer);page.setLoading(false);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'){
@@ -449,10 +455,16 @@ async function command(name,account=current()) {
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 loading=el('div',{class:'loading-state',role:'status','aria-label':'正在读取版本与更新状态',hidden:true},el('span',{class:'loading-spinner','aria-hidden':'true'}));
const region=el('div',{class:'loading-region','aria-busy':'false'},values,loading);
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;
let status,timer,loadingTimer,closed=false,busy=false;
const active=()=>!closed && content.isConnected && $('#action-dialog').open;
const setLoading=value=>{
clearTimeout(loadingTimer);loading.hidden=true;region.setAttribute('aria-busy',String(value));
if(value)loadingTimer=setTimeout(()=>{if(active())loading.hidden=false;},150);
};
const bounded=async callback=>{
const controller=new AbortController(),abort=()=>controller.abort();
lifetime.signal.addEventListener('abort',abort,{once:true});
@@ -478,31 +490,31 @@ async function showUpdates() {
async function poll(){
if(!active())return;
if(busy){schedule();return;}
busy=true;
busy=true;setLoading(true);
try{render(await bounded(signal=>api.updates({signal})));}
catch(failure){await disconnected(failure);}
finally{busy=false;schedule();}
finally{busy=false;setLoading(false);schedule();}
}
check.addEventListener('click',async()=>{
if(busy)return;busy=true;clearTimeout(timer);check.disabled=true;check.textContent='正在检查…';
if(busy)return;busy=true;setLoading(true);clearTimeout(timer);check.disabled=true;
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();}
finally{busy=false;setLoading(false);check.disabled=false;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;
busy=true;setLoading(true);clearTimeout(timer);apply.disabled=true;
try{render(await bounded(signal=>api.applyUpdate(version,{signal})));}
catch(failure){await disconnected(failure);}
finally{busy=false;schedule();}
finally{busy=false;setLoading(false);schedule();}
});
content.append(values,message,el('div',{class:'page-toolbar'},check,apply),el('p',{class:'info-note',text:'仅检查 GitHub 正式版本。窗口打开时每 3 秒读取宿主机状态;提交请求后由受控更新器处理,服务恢复且健康检查通过后才显示完成。'}));
content.append(region,message,el('div',{class:'page-toolbar'},check,apply));
const open=dialog('版本与更新',content,{info:true});
poll();
try{await open;}
finally{closed=true;clearTimeout(timer);lifetime.abort();}
finally{closed=true;clearTimeout(timer);setLoading(false);lifetime.abort();}
}
function setLogVisible(visible) {
@@ -563,18 +575,20 @@ async function fetchLogs(account) {
}
async function showDebugEntry(account,entry) {
const pre=el('pre',{class:'debug-json',text:'正在读取所选条目的脱敏详情…'});const open=dialog('请求 / 响应详情(已脱敏)',pre,{info:true});
const pre=el('pre',{class:'debug-json',hidden:true}),loading=el('div',{class:'loading-state',role:'status','aria-label':'正在读取所选条目的脱敏详情'},el('span',{class:'loading-spinner','aria-hidden':'true'}));
const content=el('div',{'aria-busy':'true'},loading,pre),open=dialog('请求 / 响应详情(已脱敏)',content,{info:true});
try{
let path;
try{path=apiPath(entry.detail_url || entry.debug_url);}catch{/* Use the account's own endpoint for untrusted URLs. */}
const detail=await (path?request(path):api.debugEntry(account.id,entry.id));
pre.textContent=JSON.stringify(detail.details ?? detail,null,2);
}catch(failure){pre.textContent=failure.message;}
finally{loading.hidden=true;pre.hidden=false;content.setAttribute('aria-busy','false');}
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')}))));
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();applyLogLayout();setStatus('等待新增账号');
}
@@ -584,7 +598,7 @@ async function syncAccounts() {
catch(failure){if(failure.status!==401){state.webStatusError=`Web 状态读取失败:${failure.message || String(failure)} 正在重试。`;renderAccountTabs();renderSummary();}throw failure;}
const 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);}
for(const [id,account]of state.accounts)if(!ids.has(id)){account.pages.forEach(page=>{clearTimeout(page.loadTimer);page.setLoading(false);page.root.remove();});state.accounts.delete(id);}
summaries.forEach(summary=>{
const account=state.accounts.get(summary.id);if(account){acceptSummary(account,summary);account.transportErrors.delete('status');if(account.config&&account.revision!==summary.revision&&!account.edits.size&&!account.savePromise)refreshConfig(account).catch(error);}
else state.accounts.set(summary.id,makeAccount(summary));
@@ -612,7 +626,7 @@ function hideWorkbench() {
$$('dialog[open]').forEach(root=>root.close());
$$('.context-menu').forEach(root=>root.remove());
$$('input[type="password"]').forEach(input=>input.value='');
state.accounts.forEach(account=>{clearTimeout(account.saveTimer);account.pages.forEach(page=>clearTimeout(page.loadTimer));});
state.accounts.forEach(account=>{clearTimeout(account.saveTimer);account.pages.forEach(page=>{clearTimeout(page.loadTimer);page.pending=false;page.setLoading(false);});});
}
function requireAuth() {
@@ -626,7 +640,7 @@ async function bootstrap() {
$('#app').hidden=false;
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
if(state.redirecting)return;
$('#app-version').textContent=meta.version || '2.0.4';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
$('#app-version').textContent=meta.version || '2.0.5';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接');
}catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
}