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

This commit is contained in:
AttilaNet
2026-11-11 09:35:54 +08:00
parent 99aff423d8
commit ff6a828f58
46 changed files with 4549 additions and 748 deletions
+32
View File
@@ -0,0 +1,32 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="ranch-web-base-path" content="">
<meta name="color-scheme" content="light">
<meta name="theme-color" content="#172435">
<link rel="icon" href="data:,">
<title>牧羊人之心 · 自动化控制台</title>
</head>
<body>
<div id="app" hidden></div>
<div id="notice" class="notice" role="status" hidden></div>
<dialog id="action-dialog" aria-labelledby="dialog-title">
<form id="dialog-form">
<header class="dialog-header">
<h1 id="dialog-title"></h1>
<button type="button" class="dialog-close" aria-label="关闭对话框">×</button>
</header>
<div id="dialog-content" class="dialog-content"></div>
<p id="dialog-error" class="error-text" role="alert" hidden></p>
<footer class="dialog-footer">
<button type="button" id="dialog-cancel">取消</button>
<button type="submit" id="dialog-confirm" class="primary">确认</button>
</footer>
</form>
</dialog>
<noscript>请启用 JavaScript 以使用牧场管理控制台。</noscript>
<script type="module" src="/src/main.js"></script>
</body>
</html>
+14
View File
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"allowJs": true,
"checkJs": false,
"noEmit": true,
"skipLibCheck": true,
"types": ["vite/client"]
},
"include": ["src/**/*.js", "src/**/*.vue"]
}
+1190
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "ranch-console",
"version": "2.0.0-dev.1",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1",
"build": "vite build && node scripts/publish-console.mjs",
"preview": "vite preview --host 127.0.0.1",
"check": "vue-tsc --noEmit -p jsconfig.json",
"test": "node --test tests/*.test.mjs"
},
"dependencies": {
"vue": "^3.5.45"
},
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.10",
"typescript": "^6.0.3",
"vite": "^8.3.7",
"vue-tsc": "^3.3.14"
}
}
+11
View File
@@ -0,0 +1,11 @@
import { readFile, writeFile } from 'node:fs/promises';
const output = new URL('../../ranch_web/static/', import.meta.url);
const built = (await readFile(new URL('console/index.html', output), 'utf8')).replace(/\r\n?/g, '\n');
await writeFile(new URL('console/index.html', output), built, 'utf8');
const html = built.replaceAll(/(["'])\.\/assets\//g, '$1/static/console/assets/');
if (!html.includes('name="ranch-web-base-path"')) {
throw new Error('The runtime base-path metadata is missing from the console entry.');
}
await writeFile(new URL('index.html', output), html, 'utf8');
console.log('Published console entry to ranch_web/static/index.html');
+212
View File
@@ -0,0 +1,212 @@
<script setup>
import { computed, nextTick, onMounted, onBeforeUnmount, ref, watch, watchEffect } from 'vue';
import { createConsoleController } from './controller.js';
import { navigation, pages } from './navigation.js';
import { accountName, connection, number } from './format.js';
import ConsoleIcon from './components/ConsoleIcon.vue';
import AccountsTable from './components/AccountsTable.vue';
import ActivityPanel from './components/ActivityPanel.vue';
const controller = createConsoleController();
const { state } = controller;
const pageHost = ref(null), sidebar = ref(null), drawerButton = ref(null);
const narrow = ref(matchMedia('(max-width: 900px)').matches), drawerOpen = ref(false);
const accountSearch = ref(''), routeError = ref('');
const current = computed(() => state.accounts.find(account => account.id === state.activeId));
const page = computed(() => pages[state.page] || pages.overview);
const player = computed(() => current.value?.connected || current.value?.demo ? current.value.player || {} : {});
const globalScope = computed(() => ['overview', 'accounts'].includes(state.page));
const filteredAccounts = computed(() => state.accounts.filter(account =>
`${accountName(account)} ${account.player?.name || ''}`.toLocaleLowerCase().includes(accountSearch.value.toLocaleLowerCase())));
const counts = computed(() => ({ total: state.accounts.length,
connected: state.accounts.filter(a => a.connected).length,
running: state.accounts.filter(a => a.running).length,
attention: state.accounts.filter(a => a.error || a.saveError).length }));
const canStart = computed(() => Boolean(current.value && (current.value.connected || current.value.demo)));
let routingReady = false, applying = 0, routeGeneration = 0;
const media = matchMedia('(max-width: 900px)');
function routeHash(key, id = state.activeId) {
return pages[key]?.global || !id
? `#/${key}${id ? `?account=${encodeURIComponent(id)}` : ''}`
: `#/accounts/${encodeURIComponent(id)}/${key}`;
}
async function applyRoute() {
if (!state.ready) return;
const generation = ++routeGeneration;
applying++;
try {
let path, query;
try {
const url = new URL((location.hash.slice(1) || '/overview'), location.origin);
path = url.pathname.split('/').filter(Boolean).map(decodeURIComponent);
query = url.searchParams;
} catch { path = ['overview']; query = new URLSearchParams(); }
const accountRoute = path[0] === 'accounts' && path.length > 1;
const key = accountRoute ? path[2] : path[0] || 'overview';
const requestedId = accountRoute ? path[1] : query.get('account');
routeError.value = '';
if (!pages[key] || accountRoute && !requestedId) {
routeError.value = '页面不存在,请从左侧导航选择功能。';
await controller.navigate('overview');
return;
}
if (requestedId && !state.accounts.some(a => String(a.id) === requestedId)) {
routeError.value = '此账号已移除或不存在,请重新选择账号。';
await controller.navigate('accounts');
return;
}
if (requestedId && String(state.activeId) !== requestedId) {
const account = state.accounts.find(a => String(a.id) === requestedId);
await controller.selectAccount(account.id);
}
if (generation !== routeGeneration) return;
await controller.navigate(key);
if (generation === routeGeneration) document.title = `${pages[key].label} · 牧羊人之心控制台`;
} finally { applying--; }
}
function go(key, id = state.activeId) {
const hash = routeHash(key, id);
closeDrawer();
window.scrollTo({top: 0, behavior: 'instant'});
if (location.hash === hash) void applyRoute();
else location.hash = hash;
}
function syncHash() {
if (!routingReady || applying || !state.ready || routeError.value) return;
const hash = routeHash(state.page);
if (location.hash !== hash) history.replaceState(null, '', `${location.pathname}${location.search}${hash}`);
}
async function startConnected() {
const eligible = state.accounts.filter(account => account.connected || account.demo).map(account => account.id);
await Promise.allSettled(eligible.map(id => controller.command('start', id)));
}
async function runCommand(name, id) {
await controller.command(name, id);
syncHash();
}
function selectAccount(event) { go(state.page, event.target.value); }
function openAccount(id) {
const account = state.accounts.find(a => a.id === id);
go(account?.connected || account?.demo ? 'incubator' : 'login', id);
}
function closeDrawer() {
const wasOpen = drawerOpen.value;
drawerOpen.value = false;
if (wasOpen && narrow.value) nextTick(() => drawerButton.value?.focus());
}
async function toggleDrawer() {
if (drawerOpen.value) { closeDrawer(); return; }
drawerOpen.value = true;
await nextTick();
const selected = sidebar.value?.querySelector('a[aria-current=page]');
(selected || sidebar.value?.querySelector('button'))?.focus();
selected?.scrollIntoView({block: 'nearest'});
}
function drawerKeys(event) {
if (event.key === 'Escape') { closeDrawer(); return; }
if (event.key !== 'Tab' || !narrow.value || !drawerOpen.value) return;
const controls = [...sidebar.value.querySelectorAll('a[href], button:not(:disabled), select:not(:disabled)')];
const first = controls[0], last = controls.at(-1);
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
}
function mediaChange(event) { narrow.value = event.matches; if (!event.matches) drawerOpen.value = false; }
function escapeDrawer(event) {
if (event.key === 'Escape' && drawerOpen.value) {
event.preventDefault();
closeDrawer();
}
}
watch(() => [state.activeId, state.page], syncHash);
watch(() => narrow.value && drawerOpen.value, open => {
document.body.style.overflow = open ? 'hidden' : '';
});
watchEffect(() => {
const root = document.getElementById('app');
if (root) root.hidden = !state.ready && !state.error;
});
onMounted(async () => {
media.addEventListener('change', mediaChange);
window.addEventListener('hashchange', applyRoute);
window.addEventListener('keydown', escapeDrawer);
await controller.init(pageHost.value);
await applyRoute();
routingReady = true;
if (!location.hash) syncHash();
});
onBeforeUnmount(() => {
media.removeEventListener('change', mediaChange);
window.removeEventListener('hashchange', applyRoute);
window.removeEventListener('keydown', escapeDrawer);
document.body.style.overflow = '';
controller.dispose();
});
</script>
<template>
<div v-show="state.ready" class="console-shell" :class="{ 'drawer-open': drawerOpen }">
<a class="skip-link" href="#main-content">跳转到内容</a>
<button v-if="drawerOpen && narrow" class="drawer-scrim" aria-label="关闭导航" tabindex="-1" @click="closeDrawer"></button>
<aside id="sidebar" ref="sidebar" class="sidebar" :inert="narrow && !drawerOpen ? true : undefined" :aria-hidden="narrow && !drawerOpen ? 'true' : undefined" @keydown="drawerKeys">
<a href="#/overview" class="sidebar-brand" @click.prevent="go('overview')"><span class="brand-mark"><ConsoleIcon name="brand" /></span><span><strong>牧羊人之心</strong><small>自动化控制台</small></span></a>
<button v-if="narrow" class="sidebar-close" aria-label="关闭导航" @click="closeDrawer">关闭导航<ConsoleIcon name="close" /></button>
<nav aria-label="主导航">
<section v-for="group in navigation" :key="group.label" class="nav-group"><h2>{{ group.label }}</h2>
<a v-for="item in group.items" :key="item.key" :href="routeHash(item.key)" class="nav-link" :class="{ selected: state.page === item.key }" :data-page="item.key" :aria-current="state.page === item.key ? 'page' : undefined" @click.prevent="go(item.key)"><ConsoleIcon :name="item.icon" /><span>{{ item.label }}</span></a>
</section>
</nav>
<footer class="sidebar-footer"><span class="status-dot"></span><span>单人工作空间</span><span>{{ state.meta?.version || '2.0.0.dev1' }}</span></footer>
</aside>
<div class="console-main" :inert="narrow && drawerOpen ? true : undefined">
<header id="topbar" class="topbar">
<div class="context-bar"><button ref="drawerButton" class="mobile-sidebar-toggle icon-button" aria-label="打开导航" :aria-expanded="drawerOpen" aria-controls="sidebar" @click="toggleDrawer"><ConsoleIcon name="menu" /></button>
<span class="workspace-name">账号工作区</span>
<span class="context-divider" aria-hidden="true"></span>
<label class="account-picker"><span class="sr-only">当前游戏账号</span><ConsoleIcon name="accounts" /><select id="account-select" :value="state.activeId || ''" aria-label="当前游戏账号" :disabled="!state.accounts.length" @change="selectAccount"><option v-if="!state.accounts.length" value="">尚未添加账号</option><option v-for="account in state.accounts" :key="account.id" :value="account.id">{{ accountName(account) }}{{ account.player?.name && account.player.name !== accountName(account) ? ` / ${account.player.name}` : '' }}</option></select></label>
</div>
<div class="user-actions"><button v-if="current" id="save-status" class="text-button desktop-only" :class="{ 'danger-text': state.saveError }" title="当前账号策略保存状态" @click="controller.retrySave()">{{ state.saveStatus }}</button><button class="icon-button" aria-label="系统设置" title="系统设置" @click="go('system')"><ConsoleIcon name="system" /></button><button class="text-button" data-command="admin-logout" @click="runCommand('admin-logout')"><ConsoleIcon name="logout" /><span>退出管理</span></button></div>
</header>
<main id="main-content" class="content-area" tabindex="-1">
<nav class="breadcrumb" aria-label="当前位置"><a href="#/overview" @click.prevent="go('overview')">工作空间</a><span aria-hidden="true">/</span><template v-if="!globalScope"><span>牧羊人之心</span><span aria-hidden="true">/</span><span v-if="current">{{ accountName(current) }}</span><span v-if="current" aria-hidden="true">/</span></template><strong aria-current="page">{{ page.label }}</strong></nav>
<div class="page-heading"><div><h1>{{ page.label }}</h1><p class="page-description">{{ page.description }}</p></div><div class="button-row"><button id="refresh" @click="controller.refresh()"><ConsoleIcon name="refresh" />{{ globalScope ? '刷新状态' : '刷新 / 预览策略' }}</button><button v-if="globalScope" class="primary" data-command="add-account" @click="runCommand('add-account')"><ConsoleIcon name="plus" />添加账号</button></div></div>
<div v-if="routeError" class="page-error" role="alert">{{ routeError }}</div>
<div v-if="state.error" class="connection-error" role="status"><span>{{ state.error }}</span><button class="text-button" @click="state.error = null">关闭提示</button></div>
<section v-if="current && !globalScope" class="account-resource-bar" aria-label="当前账号状态">
<div class="resource-identity"><span :class="['status-pill', connection(current).tone]">{{ connection(current).label }}</span><strong id="player-name">{{ player.name || accountName(current) }}</strong><span>Lv. {{ number(player.level) }}</span></div>
<div class="resource-item"><span>经验</span><strong>{{ player.exp == null ? '—' : `${number(player.exp)} / ${number(player.next_exp)}` }}</strong></div><div class="resource-item"><span>金币</span><strong>{{ number(player.money) }}</strong></div><div class="resource-item"><span>氪金</span><strong>{{ number(player.ke) }}</strong></div><div class="resource-item"><span>体力</span><strong>{{ number(player.ti) }}</strong></div>
<div class="context-actions"><label class="inline-label">刷新<select id="refresh-interval" :value="state.interval" aria-label="随机刷新间隔" @change="controller.setInterval(Number($event.target.value))"><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="current.running || current.starting ? 'stop-button' : 'start-button'" :aria-pressed="Boolean(current.running || current.starting)" :disabled="!current.running && !current.starting && !canStart" @click="runCommand(current.running || current.starting ? 'stop' : 'start', current.id)"><ConsoleIcon :name="current.running || current.starting ? 'stop' : 'play'" />{{ current.running || current.starting ? '停止' : '开启' }}</button></div>
</section>
<div v-if="current && !globalScope" class="workspace-meta"><span>{{ current.starting ? '正在启动 · 可随时停止' : current.running ? '策略运行中 · 执行各页面已启用的功能' : '策略已停止 · 可继续查看数据与调整规则' }}</span><span>{{ state.saveStatus }}</span></div>
<section v-if="state.page === 'overview'" class="global-view">
<div class="metric-grid"><article class="metric-card"><span>已添加账号</span><strong>{{ counts.total }}</strong><small>牧羊人之心</small></article><article class="metric-card"><span>已连接游戏</span><strong>{{ counts.connected }}</strong><small>成功读取角色的账号</small></article><article class="metric-card"><span>策略运行中</span><strong>{{ counts.running }}</strong><small>各账号独立执行</small></article><article class="metric-card" :class="{ 'metric-attention': counts.attention }"><span>需要关注</span><strong>{{ counts.attention }}</strong><small>连接或配置保存异常</small></article></div>
<section class="panel"><div class="panel-heading"><div><h2>账号运行概况</h2><p>查看状态,进入账号工作区管理资源与策略。</p></div><button class="text-button" @click="go('accounts')">管理全部账号<ConsoleIcon name="arrow" /></button></div><AccountsTable :accounts="state.accounts" :active-id="state.activeId" @open="openAccount" @command="runCommand" /></section>
<section v-if="counts.attention" class="panel attention-panel"><div class="panel-heading"><h2>待处理事项</h2></div><ul class="attention-list"><li v-for="account in state.accounts.filter(a => a.error || a.saveError)" :key="account.id"><strong>{{ accountName(account) }}</strong><span>{{ account.error || account.saveError }}</span><button @click="openAccount(account.id)">查看账号</button></li></ul></section>
<div v-else class="overview-note"><ConsoleIcon name="connection" /><p>状态来自账号当前快照。浏览器页面关闭后,服务端策略继续运行;重新启动服务后需要手动开启。</p></div>
</section>
<section v-if="state.page === 'accounts'" class="global-view panel"><div class="panel-heading"><div><h2>游戏账号</h2><p>连接、策略和运行记录按账号独立保存。</p></div><div class="button-row"><button data-command="start-all" :disabled="!state.accounts.some(a => a.connected || a.demo)" title="开启已连接及离线演示账号的策略" @click="startConnected">批量开启</button><button data-command="stop-all" :disabled="!state.accounts.length" @click="runCommand('stop-all')">停止全部</button><button data-command="add-demo" @click="runCommand('add-demo')">新增离线演示</button><button class="primary" @click="runCommand('add-account')">添加账号</button></div></div><div class="filter-bar"><label class="search-field"><span class="sr-only">搜索账号</span><input v-model="accountSearch" type="search" aria-label="搜索账号" placeholder="搜索账号或角色名称"></label><span class="muted">{{ filteredAccounts.length }} 个账号</span></div><AccountsTable :accounts="filteredAccounts" :active-id="state.activeId" manageable @open="openAccount" @command="runCommand" /></section>
<section v-if="state.page === 'system'" class="global-view info-grid">
<article class="panel system-card"><div class="panel-heading"><div><h2>当前账号配置</h2><p>{{ current ? accountName(current) : '请先选择一个游戏账号' }}</p></div><ConsoleIcon name="system" /></div><p>策略修改后自动保存。导入只应用到当前账号,运行开关保持关闭。</p><div class="button-row"><button data-command="export-config" :disabled="!current" @click="runCommand('export-config')"><ConsoleIcon name="download" />导出策略</button><button data-command="import-config" :disabled="!current" @click="runCommand('import-config')">导入策略</button><button data-command="save" :disabled="!current" @click="controller.retrySave()">重试保存</button></div></article>
<article class="panel system-card"><div class="panel-heading"><div><h2>版本与更新</h2><p>牧羊人之心控制台 {{ state.meta?.version || '2.0.0.dev1' }}</p></div><ConsoleIcon name="refresh" /></div><p>游戏资料版本 {{ state.meta?.gameVersion || '1.9.68' }}。更新状态由宿主机执行器提供。</p><div class="button-row"><button data-command="updates" @click="runCommand('updates')">检查版本更新</button><button data-command="about" @click="runCommand('about')">关于</button></div></article>
<article class="panel system-card"><div class="panel-heading"><div><h2>账号与连接</h2><p>游戏连接与管理控制台分别退出。</p></div><ConsoleIcon name="connection" /></div><div class="button-row"><button :disabled="!current" @click="go('login')">管理游戏连接</button><button data-command="logout" :disabled="!current" @click="runCommand('logout')">退出游戏登录</button><button data-command="forget-login" class="danger-text" :disabled="!current" @click="runCommand('forget-login')">退出并清除登录记录</button></div></article>
<article class="panel system-card"><div class="panel-heading"><h2>平台状态</h2></div><dl class="system-facts"><dt>管理模式</dt><dd>单人工作空间</dd><dt>游戏</dt><dd>牧羊人之心</dd><dt>服务连接</dt><dd role="status">{{ state.status }}</dd></dl><p class="muted">各账号独立保存连接、策略与运行记录。</p></article>
</section>
<section v-if="!page.global && !current" class="panel empty-block"><ConsoleIcon name="accounts" /><h2>先添加一个游戏账号</h2><p>连接角色后,即可在这里查看数据并配置策略。</p><button class="primary" @click="go('accounts')">前往账号管理</button></section>
<div id="page-host" ref="pageHost" class="page-host" :hidden="page.global || !current"></div>
<section v-if="state.jobs.length && !globalScope" class="pending-jobs" aria-label="后台任务"><span v-for="job in state.jobs.filter(j => j.accountId === state.activeId)" :key="job.id"><span class="status-dot"></span>{{ job.accountLabel }} · {{ job.operation }} · {{ job.status === 'queued' ? '排队中' : '处理中' }}</span></section>
<div v-if="current && state.page !== 'activity'" class="log-dock"><button id="log-toggle" class="text-button" :aria-expanded="state.logVisible" aria-controls="log-panel" @click="runCommand('toggle-log')"><ConsoleIcon name="activity" />{{ state.logVisible ? '收起当前账号日志' : '展开当前账号日志' }}</button><button id="debug-toggle" class="text-button" @click="controller.setLogDebug(!state.logDebug)">调试日志</button></div>
<ActivityPanel v-if="state.page === 'activity' || current && state.logVisible" :logs="state.logs" :account-id="state.activeId" :account-label="current ? accountName(current) : ''" :debug="state.logDebug" @debug="controller.setLogDebug" @inspect="controller.inspectLog" />
<footer class="console-status"><span id="status-text" role="status">{{ state.status }}</span><span>牧羊人之心 · {{ state.meta?.version || '2.0.0.dev1' }}</span></footer>
</main>
</div>
</div>
<section v-if="!state.ready && state.error" class="startup-error" role="alert"><h1>暂时无法连接控制台</h1><p>{{ state.error }}</p><button @click="controller.init(pageHost)">重新连接</button></section>
</template>
+35
View File
@@ -0,0 +1,35 @@
<script setup>
import ConsoleIcon from './ConsoleIcon.vue';
import { accountName, connection, number } from '../format.js';
defineProps({
accounts: { type: Array, default: () => [] },
activeId: { type: [String, Number], default: null },
manageable: Boolean,
busy: { type: Boolean, default: false },
});
defineEmits(['open', 'command']);
</script>
<template>
<div v-if="!accounts.length" class="empty-block">
<div class="empty-icon"><ConsoleIcon name="accounts" /></div>
<h3>还没有游戏账号</h3>
<p>添加账号后,连接游戏并配置自动化策略。</p>
<button class="primary" @click="$emit('command', 'add-account')"><ConsoleIcon name="plus" />添加账号</button>
</div>
<div v-else class="account-table-scroll" role="region" aria-label="游戏账号列表" tabindex="0">
<table class="account-table">
<thead><tr><th scope="col">游戏账号</th><th scope="col">连接状态</th><th scope="col">游戏角色</th><th scope="col">策略状态</th><th scope="col" class="row-actions-heading">操作</th></tr></thead>
<tbody>
<tr v-for="account in accounts" :key="account.id" :data-account="account.id" :class="{ 'current-account-row': account.id === activeId }">
<td><div class="account-name-cell"><span class="account-avatar">{{ accountName(account).slice(0, 1) }}</span><span><button class="text-button account-name" @click="$emit('open', account.id)">{{ accountName(account) }}</button><span v-if="account.id === activeId" class="current-label">当前账号</span></span></div></td>
<td><span :class="['status-pill', connection(account).tone]" :title="account.error || ''"><span class="status-dot"></span>{{ connection(account).label }}</span></td>
<td><span class="account-player">{{ account.player?.name || '尚未读取角色' }}</span><span v-if="(account.connected || account.demo) && account.player?.level != null" class="table-secondary">Lv. {{ number(account.player.level) }}</span></td>
<td><span :class="['status-pill', account.running ? 'success' : 'neutral']"><ConsoleIcon :name="account.running ? 'play' : 'stop'" />{{ account.starting ? '启动中' : account.running ? '运行中' : '已停止' }}</span><span v-if="account.busy" class="table-secondary">后台任务处理中</span></td>
<td><div class="row-actions"><button class="small" :aria-label="`管理${accountName(account)}`" @click="$emit('open', account.id)">管理<ConsoleIcon name="arrow" /></button><button :class="['small', account.running || account.starting ? 'stop-outline' : 'start-outline']" :disabled="!account.running && !account.starting && (busy || (!account.connected && !account.demo))" :aria-label="`${account.running || account.starting ? '停止' : '开启'}${accountName(account)}策略`" @click="$emit('command', account.running || account.starting ? 'stop' : 'start', account.id)">{{ account.running || account.starting ? '停止' : '开启' }}</button><button v-if="manageable" class="small danger-text" :disabled="busy" :aria-label="`移除${accountName(account)}`" @click="$emit('command', 'remove-account', account.id)">移除</button></div></td>
</tr>
</tbody>
</table>
</div>
</template>
+53
View File
@@ -0,0 +1,53 @@
<script setup>
import { computed, nextTick, ref, watch } from 'vue';
import ConsoleIcon from './ConsoleIcon.vue';
import { downloadText, logMessage, time } from '../format.js';
const props = defineProps({
logs: { type: Array, default: () => [] },
accountId: { type: [String, Number], default: null },
accountLabel: { type: String, default: '' },
debug: Boolean,
});
defineEmits(['debug', 'inspect']);
const search = ref('');
const level = ref('all');
const follow = ref(true);
const logHost = ref(null);
const hiddenEntries = ref(new Set());
const keyOf = entry => entry.id ?? `${entry.time ?? entry.timestamp ?? entry.at ?? ''}:${logMessage(entry)}`;
const toneOf = entry => {
const value = String(entry.level || entry.kind || 'info').toLowerCase();
return ['error', 'warning', 'debug'].includes(value) ? value : value === 'warn' ? 'warning' : 'info';
};
const levelNames = { info: '信息', warning: '警告', error: '错误', debug: '调试' };
const visibleLogs = computed(() => props.logs.filter(entry => !hiddenEntries.value.has(keyOf(entry))
&& (level.value === 'all' || toneOf(entry) === level.value)
&& logMessage(entry).toLocaleLowerCase().includes(search.value.toLocaleLowerCase())).slice(-600));
const inspectable = entry => Boolean(entry.details_available || entry.detail_url || entry.debug_url);
watch(() => props.accountId, () => { hiddenEntries.value = new Set(); search.value = ''; level.value = 'all'; });
watch(() => [visibleLogs.value.length, keyOf(visibleLogs.value.at(-1) || {})], async () => {
if (!follow.value) return;
await nextTick();
if (logHost.value) logHost.value.scrollTop = logHost.value.scrollHeight;
});
function download() {
const text = visibleLogs.value.map(entry => `${time(entry.time ?? entry.timestamp ?? entry.at)} [${levelNames[toneOf(entry)]}] ${logMessage(entry)}`).join('\n');
downloadText(text, `牧场日志-${props.accountLabel || '账号'}.txt`);
}
function onScroll() {
if (!logHost.value) return;
const host = logHost.value;
follow.value = host.scrollHeight - host.scrollTop - host.clientHeight < 48;
}
</script>
<template>
<section id="log-panel" class="panel activity-panel" aria-label="当前账号运行日志">
<div class="panel-heading"><div><h2>{{ debug ? '调试日志(已脱敏)' : '运行日志' }}</h2><p>{{ accountLabel || '请先选择账号' }}<span v-if="accountId"> · 最近 {{ visibleLogs.length }} 条</span></p></div><div class="button-row"><button id="download-log" class="small" :disabled="!visibleLogs.length" @click="download"><ConsoleIcon name="download" />下载日志</button><button id="clear-log" class="small" :disabled="!visibleLogs.length" @click="hiddenEntries = new Set(logs.map(keyOf))">清空显示</button></div></div>
<div class="activity-filters"><label class="search-field"><span class="sr-only">搜索日志</span><input v-model="search" type="search" placeholder="搜索日志内容" aria-label="搜索日志"></label><label class="inline-label">级别<select v-model="level" aria-label="日志级别"><option value="all">全部级别</option><option v-for="(name, key) in levelNames" :key="key" :value="key">{{ name }}</option></select></label><span class="flex-spacer"></span><label class="checkbox-label"><input id="debug-log" type="checkbox" :checked="debug" :disabled="!accountId" @change="$emit('debug', $event.target.checked)">调试 / 脱敏</label><label class="checkbox-label"><input id="log-follow" v-model="follow" type="checkbox">自动跟随</label></div>
<div v-if="!accountId" class="empty-block"><ConsoleIcon name="activity" /><h3>选择账号以查看运行记录</h3><p>日志按账号独立展示。</p></div>
<div v-else-if="!visibleLogs.length" class="empty-block"><ConsoleIcon name="activity" /><h3>{{ search || level !== 'all' ? '没有匹配的日志' : '暂无运行日志' }}</h3><p>{{ search || level !== 'all' ? '调整搜索内容或日志级别。' : '连接游戏或执行操作后,运行记录会显示在这里。' }}</p></div>
<ol v-else id="log-lines" ref="logHost" class="activity-lines" role="log" aria-live="off" aria-label="日志内容" tabindex="0" @scroll="onScroll"><li v-for="entry in visibleLogs" :key="keyOf(entry)" :class="['activity-line', toneOf(entry)]"><time class="log-time" :title="String(entry.time ?? entry.timestamp ?? entry.at ?? '')">{{ time(entry.time ?? entry.timestamp ?? entry.at) }}</time><span class="log-level">{{ levelNames[toneOf(entry)] }}</span><button v-if="inspectable(entry)" class="log-message inspectable" title="查看脱敏请求 / 响应详情" @click="$emit('inspect', entry)">{{ logMessage(entry) }}<ConsoleIcon name="arrow" /></button><span v-else class="log-message">{{ logMessage(entry) }}</span></li></ol>
</section>
</template>
+46
View File
@@ -0,0 +1,46 @@
<script setup>
import { computed } from 'vue';
const props = defineProps({ name: { type: String, default: 'overview' } });
const paths = {
brand: ['M12 21v-9', 'M12 16C5 16 3 11 3 5c6 0 9 3 9 9', 'M12 12c0-6 3-9 9-9 0 6-3 9-9 9'],
overview: ['M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z'],
accounts: ['M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2', 'M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8', 'M17 4a4 4 0 0 1 0 7M22 21v-2a4 4 0 0 0-3-3.87'],
connection: ['M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2', 'M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2'],
incubator: ['M5 3h14v18H5zM5 9h14M9 6h1M14 14c0-4-4-4-4 0a2 2 0 0 0 4 0zM9 18h6'],
bag: ['M4 7h16l1 14H3L4 7zM8 7V6a4 4 0 0 1 8 0v1'],
ranch: ['M3 21V9l9-6 9 6v12M9 21v-7h6v7M3 10h18'],
daily: ['M4 5h16v16H4zM16 3v4M8 3v4M4 11h16M8 15l2 2 5-3'],
hatching: ['M20 14c0 5-3.6 7-8 7s-8-2-8-7S8 2 12 2s8 7 8 12zM8 12l3 3 5-5'],
gifts: ['M3 8h18v4H3zM5 12v9h14v-9M12 8v13M12 8H8a3 3 0 1 1 3-3l1 3zM12 8h4a3 3 0 1 0-3-3l-1 3z'],
commissions: ['M9 5H5v16h14V5h-4M9 3h6v4H9zM8 12h8M8 16h5'],
exploration: ['M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0zM16 8l-3 5-5 3 3-5 5-3z'],
mainline: ['M6 3v18M6 4h13l-3 4 3 4H6'],
maps: ['M9 3 3 6v15l6-3 6 3 6-3V3l-6 3-6-3zM9 3v15M15 6v15'],
plans: ['M9 5h12M9 12h12M9 19h12M3 5l1 1 2-2M3 12l1 1 2-2M3 19l1 1 2-2'],
battles: ['M14 4l6-1-1 6-9 9-4-4 8-10zM4 14l6 6M4 20l3-3M4 4l7 7M14 14l6 6M17 17l3-3'],
statistics: ['M4 3v18h18M8 16v-5M13 16V7M18 16v-8'],
activity: ['M4 3h12l4 4v14H4zM15 3v5h5M8 12h8M8 16h6'],
yields: ['M21 9c0 3.3-4 6-9 6s-9-2.7-9-6 4-6 9-6 9 2.7 9 6zM3 9v6c0 3.3 4 6 9 6s9-2.7 9-6V9M8 8h8M12 6v6'],
system: ['M9 3h6l1 3 3 1 2 5-2 5-3 1-1 3H9l-1-3-3-1-2-5 2-5 3-1 1-3zM15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z'],
menu: ['M3 6h18M3 12h18M3 18h18'],
close: ['M6 6l12 12M6 18 18 6'],
chevron: ['M9 5l7 7-7 7'],
plus: ['M12 5v14M5 12h14'],
play: ['M7 4l14 8-14 8V4z'],
stop: ['M5 5h14v14H5z'],
refresh: ['M20 7v5h-5M4 17v-5h5M6 6a8 8 0 0 1 13 2M18 18a8 8 0 0 1-13-2'],
arrow: ['M5 12h14M13 6l6 6-6 6'],
check: ['M4 12l5 5L20 6'],
info: ['M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0zM12 11v6M12 7h.01'],
download: ['M12 3v12M7 10l5 5 5-5M4 16v5h16v-5'],
upload: ['M12 16V4M7 9l5-5 5 5M4 16v5h16v-5'],
logout: ['M10 4H4v16h6M9 12h12M17 8l4 4-4 4'],
};
const selected = computed(() => paths[props.name] || paths.overview);
</script>
<template>
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">
<path v-for="(path, index) in selected" :key="index" :d="path" />
</svg>
</template>
+904
View File
@@ -0,0 +1,904 @@
import {shallowReactive} from 'vue';
import {api, request} from '../../ranch_web/static/api.js';
import {apiPath, webPath} from '../../ranch_web/static/paths.js';
import {el, $, $$, clone, getPath, setPath, pathKey, download, csvBlob, optionsList, detailsList} from '../../ranch_web/static/dom.js';
import {PageView, PAGES} from '../../ranch_web/static/pages.js';
import {notice, dialog, confirm, filePicker, fileBase64} from '../../ranch_web/static/ui.js';
const GLOBAL_PAGES = new Set(['overview', 'accounts', 'activity', 'system']);
const PAGE_KEYS = new Set(PAGES.map(([key]) => key));
const TERMINAL = new Set(['succeeded', 'failed', 'cancelled']);
const JOB_LABELS = {queued:'排队中', running:'执行中', succeeded:'已完成', failed:'失败', cancelled:'已取消'};
const OPERATION_LABELS = {login:'登录', enter_server:'进入区服', restore_session:'恢复会话', refresh:'刷新 / 预览', start:'开启策略', stop:'停止策略', set_config:'保存配置', import_config:'导入策略', import_yields:'导入收益', claim_daily:'领取每日奖励', quote_expansion:'读取扩建费用', expand:'扩建', sell:'派遣', feed:'喂养', lock:'锁定', unlock:'解锁'};
/**
* The shell owns routes, navigation, account chrome and log rendering. Only the
* supplied host and ui.js dialogs are manipulated here. Account configuration,
* snapshots and PageViews deliberately stay outside Vue's reactive graph.
*/
export function createConsoleController() {
const state = shallowReactive({
ready:false, accounts:[], activeId:null, page:'overview', meta:null, schema:null,
status:'正在连接', saveStatus:'', saveError:null, logs:[], logDebug:false,
jobs:[], error:null, interval:30, currentConfig:null, logVisible:true,
accessMode:null,
});
const accounts = new Map();
let host = null;
let disposed = false;
let redirecting = false;
let sequence = 0;
let pollTimer;
let accountsPromise = null;
let initPromise = null;
let lastAccountsLoad = 0;
const lifecycle = new AbortController();
const updateCleanups = new Set();
const current = () => accounts.get(state.activeId);
const alive = account => !disposed && !redirecting && accounts.get(account.id) === account && !account.removing;
const visible = page => alive(page.account) && state.activeId === page.account.id && state.page === page.key && !document.hidden;
const currentPage = () => current()?.pages.get(state.page);
function setStatus(message) { if (!disposed && !redirecting) state.status = message; }
function reportError(failure) {
if (disposed || redirecting || failure?.name === 'AbortError') return;
const message = failure?.message || String(failure);
state.error = message;
setStatus(message);
notice(message, true);
}
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, configPromise:null, statusPromise:null,
saveError:null, saveTimer:null, removing:false, executionGeneration:0, startingGeneration:null,
logs:{entries:[], next:0, debug:false, promise:null, generation:0, lastLoad:0},
};
}
function publish() {
if (disposed || redirecting) return;
state.accounts = [...accounts.values()].map(account => Object.freeze({
...account.summary, starting:account.startingGeneration !== null, configReady:Boolean(account.config), dirty:Boolean(account.edits.size),
saving:Boolean(account.savePromise), saveError:account.saveError,
}));
state.jobs = [...accounts.values()].flatMap(account => [...account.jobs.values()].map(record => ({
...record.job, accountId:account.id, accountLabel:account.summary.label || account.summary.player?.name || '账号',
})));
const account = current();
state.saveError = account?.saveError || null;
state.saveStatus = !account ? '' : account.saveError ? '保存失败 · 点击重试' : account.savePromise ? '保存中…' : account.edits.size ? '修改待保存…' : account.config ? '策略已自动保存' : '配置载入中…';
state.interval = account?.config?.interval ?? 30;
state.currentConfig = account ? Object.freeze({
ready:Boolean(account.config), revision:account.revision, interval:state.interval,
dirty:Boolean(account.edits.size), saving:Boolean(account.savePromise), saveError:account.saveError,
log_visible:account.config?.log_visible ?? true,
log_sizes:Object.freeze([...(account.config?.log_sizes || [])]),
}) : null;
state.logs = account ? account.logs.entries : [];
state.logDebug = account?.logs.debug ?? false;
state.logVisible = account?.config?.log_visible ?? true;
}
function invalidatePages(account) {
account.pages.forEach(page => { page.configDirty = true; });
const page = currentPage();
if (page?.account === account && visible(page) && page.data) {
page.render(page.data, page.dataLoading);
page.configDirty = false;
}
}
function getPage(account, key) {
if (!PAGE_KEYS.has(key)) return null;
if (!account.pages.has(key)) {
const page = new PageView(account, key, {
edit:editConfig, perform, load:loadPage, action:pageAction,
command:(name, owner) => command(name, owner?.id ?? account.id),
schema:pageKey => state.schema?.pages?.find(item => item.key === pageKey)?.form || [],
});
account.pages.set(key, page);
host.append(page.root);
}
return account.pages.get(key);
}
function hidePages() {
accounts.forEach(account => account.pages.forEach(page => {
page.root.hidden = true;
clearTimeout(page.loadTimer);
clearTimeout(page.queryTimer);
}));
}
async function navigate(key) {
if (disposed || redirecting) return;
if (!GLOBAL_PAGES.has(key) && !PAGE_KEYS.has(key)) throw new Error('未知页面。');
if (state.page !== key) currentPage()?.login?.clearPassword();
state.page = key;
hidePages();
if (!GLOBAL_PAGES.has(key) && current() && host) {
const account = current();
account.page = key;
const page = getPage(account, key);
page.root.hidden = false;
if (page.data && (page.configDirty || page.needsRender) && visible(page)) {
page.render(page.data, page.dataLoading);
page.configDirty = false;
page.needsRender = false;
}
await loadPage(page, true);
}
void fetchLogs(current());
}
async function selectAccount(id) {
if (disposed || redirecting) return;
if (id != null && !accounts.has(id)) throw new Error('账号不存在或已移除。');
const previous = current();
previous?.pages.get('login')?.login?.clearPassword();
if (previous?.edits.size && previous.id !== id) void flushConfig(previous).catch(reportError);
state.activeId = id ?? null;
hidePages();
publish();
const account = current();
if (!account) return;
const load = account.config && account.revision === account.summary.revision ? Promise.resolve() : refreshConfig(account);
await Promise.all([load, navigate(state.page)]);
if (alive(account) && current() === account) publish();
}
async function refresh() {
const account = current();
try {
if (GLOBAL_PAGES.has(state.page)) return await syncAccounts(true);
if (account) return await perform(account, 'refresh', {page:state.page});
} catch (failure) { reportError(failure); }
}
function setInterval(value) {
try {
const numeric = Number(value);
if (![30, 60, 120, 300].includes(numeric)) throw new Error('刷新间隔须为 30、60、120 或 300 秒。');
if (current()) editConfig(current(), ['interval'], numeric);
} catch (failure) { reportError(failure); }
}
async function retrySave() { return command('save', state.activeId); }
async function setLogDebug(value) { return changeLogDebug(current(), Boolean(value)); }
async function inspectLog(entry) { return showDebugEntry(current(), entry); }
async function init(pageHostElement) {
if (disposed) throw new Error('控制器已销毁。');
if (!pageHostElement?.append) throw new TypeError('init 需要页面容器元素。');
if (host && host !== pageHostElement) throw new Error('控制器已绑定其他页面容器。');
host = pageHostElement;
if (initPromise) return initPromise;
if (state.ready) return;
initPromise = bootstrap().finally(() => { initPromise = null; });
return initPromise;
}
function dispose() {
if (disposed) return;
disposed = true;
state.ready = false;
clearTimeout(pollTimer);
lifecycle.abort();
updateCleanups.forEach(cleanup => cleanup());
accounts.forEach(account => releaseAccount(account, '控制器已关闭'));
accounts.clear();
}
function applyEdit(config, edit) {
if (!edit.ifMissing || getPath(config, edit.path) === undefined) setPath(config, edit.path, edit.value);
}
function acceptConfig(account, response) {
if (!alive(account) || !response?.config) return;
account.config = clone(response.config);
account.revision = response.revision;
account.edits.forEach(edit => applyEdit(account.config, edit));
invalidatePages(account);
publish();
}
function readConfig(account) {
if (account.configPromise) return account.configPromise;
account.configPromise = api.config(account.id).finally(() => { account.configPromise = null; });
return account.configPromise;
}
async function refreshConfig(account) {
if (!alive(account)) return;
if (account.savePromise) await account.savePromise.catch(() => {});
if (!alive(account)) return;
const response = await readConfig(account);
if (!account.savePromise) acceptConfig(account, response);
}
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:++sequence, ifMissing});
}
function editConfig(account, path, value, field = {}, row) {
if (!alive(account)) throw new Error('账号不存在或已移除。');
if (!account.config) throw new Error('配置尚未载入,请稍后再试。');
if (row?.rule_path && row.rule_defaults) {
Object.entries(row.rule_defaults).forEach(([key, fallback]) => writeEdit(account, [...row.rule_path, key], fallback, {ifMissing:true}));
}
writeEdit(account, path, value);
// Match the desktop's linked rule switches, including defaults-only writes.
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(() => { void flushConfig(account).catch(reportError); }, 500);
invalidatePages(account);
publish();
}
function validatePage(account, message) {
const page = account.pages.get(account.page);
const invalid = page?.root.querySelector(':invalid');
if (invalid) {
if (visible(page)) invalid.reportValidity();
throw new Error(message);
}
}
async function flushConfig(account = current()) {
if (!account || !alive(account)) return;
clearTimeout(account.saveTimer);
if (account.savePromise) return account.savePromise;
if (!account.edits.size) return;
validatePage(account, '请先补全当前输入,再保存或开启策略。');
account.saveError = null;
const saving = (async () => {
// A preceding config read must finish before the first write snapshots it.
if (account.configPromise) await account.configPromise;
while (alive(account) && account.edits.size) {
validatePage(account, '请先补全当前输入,再保存或开启策略。');
const sent = [...account.edits.values()].map(clone);
let response = await api.save(account.id, clone(account.config), account.revision);
if (!alive(account)) return;
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 readConfig(account);
}
if (!response?.config) response = await readConfig(account);
if (!alive(account)) return;
sent.forEach(edit => {
if (account.edits.get(pathKey(edit.path))?.seq === edit.seq) account.edits.delete(pathKey(edit.path));
});
acceptConfig(account, response);
}
})();
account.savePromise = saving.catch(async failure => {
if (!alive(account)) throw failure;
if (failure.status === 409) {
account.saveError = '配置已被另一浏览器更新。已保留你修改的字段,请点击保存状态重试。';
try { acceptConfig(account, await readConfig(account)); }
catch { /* Keep both edits and the conflict explanation for explicit retry. */ }
} else account.saveError = failure.message || String(failure);
throw new Error(account.saveError);
}).finally(() => {
account.savePromise = null;
publish();
});
publish();
await account.savePromise;
if (alive(account)) {
invalidatePages(account);
const page = currentPage();
if (page?.account === account) void 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 || JOB_LABELS[job.status]));
if (!alive(account)) return Promise.reject(new Error('账号不存在或已移除。'));
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; });
// Lifecycle cancellation can reject before its caller reaches await.
void promise.catch(() => {});
const record = {job, promise, resolve, reject, polling:false, timer:null};
account.jobs.set(job.id, record);
publish();
void pollJob(account, record);
return promise;
}
async function pollJob(account, record) {
if (!alive(account) || record.polling || !account.jobs.has(record.job.id)) return;
record.polling = true;
try {
const job = await api.job(account.id, record.job.id);
if (!alive(account) || !account.jobs.has(record.job.id)) return;
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 || JOB_LABELS[job.status] || '任务已取消'));
}
} catch (failure) {
if ([400, 401, 403, 404].includes(failure.status)) {
account.jobs.delete(record.job.id);
record.reject(failure);
}
} finally {
record.polling = false;
publish();
if (alive(account) && account.jobs.has(record.job.id)) record.timer = setTimeout(() => { void pollJob(account, record); }, document.hidden ? 3000 : 1000);
}
}
function refreshStatus(account) {
if (!alive(account)) return Promise.resolve();
if (account.statusPromise) return account.statusPromise;
account.statusPromise = api.status(account.id).then(summary => {
if (alive(account)) { account.summary = summary; publish(); }
}).finally(() => { account.statusPromise = null; });
return account.statusPromise;
}
async function perform(account, operation, payload = {}, options = {}) {
if (!account || !alive(account)) throw new Error('请先新增或选择一个账号。');
// Capture intent synchronously: Stop invalidates only this account's unsent
// starts, and an older completion cannot clear a newer starting indicator.
const generation = operation === 'start' ? ++account.executionGeneration : null;
if (operation === 'start') {
account.startingGeneration = generation;
publish();
} else if (operation === 'stop') {
account.executionGeneration++;
account.startingGeneration = null;
publish();
}
const superseded = () => generation !== null && generation !== account.executionGeneration;
const finishStart = () => {
if (generation !== null && account.startingGeneration === generation) {
account.startingGeneration = null;
publish();
}
};
try {
if (operation === 'start') {
// Account-table actions may target an account never selected in the shell.
if (!account.config) await refreshConfig(account);
if (superseded()) return;
if (!alive(account)) throw new Error('账号不存在或已移除。');
validatePage(account, '请先完成当前输入,再开启策略。');
}
// Stop always reaches this account's worker immediately, even during a save.
if (operation !== 'stop') await flushConfig(account);
if (superseded()) return;
if (!alive(account)) throw new Error('账号不存在或已移除。');
const job = await api.action(account.id, operation, payload);
// Once sent, the request's real server result/job must still be tracked.
if (!alive(account)) return;
setStatus(`${OPERATION_LABELS[operation] || '操作'}:${JOB_LABELS[job?.status] || '已提交'}`);
const result = await trackJob(account, job);
if (!alive(account)) return result;
if (result?.config) acceptConfig(account, result);
if (['enter_server', 'restore_session', 'logout', 'forget_login', 'import_config', 'import_yields'].includes(operation)) await refreshConfig(account);
await refreshStatus(account);
finishStart();
const page = options.page || account.pages.get(account.page);
if (page && visible(page)) await loadPage(page, true);
if (operation === 'login' && result && page?.key === 'login' && visible(page)) page.login?.update(result);
if (!alive(account)) return result;
if (operation === 'enter_server' || operation === 'restore_session') notice('已读取角色。策略保持关闭,请配置功能后开启。');
else if (result?.message) notice(result.message);
setStatus(result?.message || `${OPERATION_LABELS[operation] || '操作'}已完成`);
return result;
} finally { finishStart(); }
}
async function loadPage(page, force = false) {
if (!page || !visible(page)) return;
if (page.fetching) {
if (force) page.reload = true;
return page.fetchPromise;
}
clearTimeout(page.loadTimer);
page.fetching = true;
page.fetchPromise = (async () => {
do {
page.reload = false;
const generation = page.generation || 0;
try {
const response = await readView(page.account, page.key, clone(page.query));
if (!visible(page) || generation !== (page.generation || 0)) continue;
page.clearError();
page.dataLoading = Boolean(response.loading);
page.render(response.data, page.dataLoading);
page.configDirty = false;
page.needsRender = false;
if (response.loading) page.loadTimer = setTimeout(() => { void loadPage(page); }, 650);
} catch (failure) {
if (visible(page)) page.showError(failure.message || String(failure));
} finally { page.lastLoad = Date.now(); }
} while (page.reload && visible(page));
})().finally(() => { page.fetching = false; page.fetchPromise = null; });
return page.fetchPromise;
}
function releaseAccount(account, message = '账号已移除') {
account.removing = true;
clearTimeout(account.saveTimer);
account.logs.generation++;
account.jobs.forEach(record => {
clearTimeout(record.timer);
record.reject(new Error(message));
});
account.jobs.clear();
account.pages.forEach(page => {
clearTimeout(page.loadTimer);
clearTimeout(page.queryTimer);
page.generation = (page.generation || 0) + 1;
page.login?.clearPassword();
page.destroy?.();
page.root.remove();
});
account.pages.clear();
}
async function syncAccounts(force = false) {
if (disposed || redirecting) return;
if (accountsPromise) return accountsPromise;
if (!force && Date.now() - lastAccountsLoad < (document.hidden ? 15000 : 3000)) return;
accountsPromise = (async () => {
const response = await api.accounts();
if (disposed || redirecting) return;
const summaries = Array.isArray(response) ? response : response.accounts || [];
const ids = new Set(summaries.map(summary => summary.id));
for (const [id, account] of accounts) if (!ids.has(id)) { releaseAccount(account); accounts.delete(id); }
summaries.forEach(summary => {
const account = accounts.get(summary.id);
if (account && !account.removing) account.summary = summary;
else if (!account) accounts.set(summary.id, makeAccount(summary));
});
publish();
if ((state.activeId != null && !accounts.has(state.activeId)) || (state.activeId == null && accounts.size)) {
// Slow config/page reads cannot hold up polling all public summaries.
void selectAccount(accounts.keys().next().value ?? null).catch(reportError);
}
const active = current();
if (active?.config && active.revision !== active.summary.revision && !active.edits.size && !active.savePromise) void refreshConfig(active).catch(reportError);
if (!accounts.size) setStatus('等待新增账号');
})().finally(() => { accountsPromise = null; lastAccountsLoad = Date.now(); });
return accountsPromise;
}
async function tick() {
if (!state.ready || disposed || redirecting) return;
// Jobs have independent timers and never wait behind an account/view read.
void syncAccounts().catch(reportError);
if (document.hidden) return;
const page = currentPage();
if (page && Date.now() - (page.lastLoad || 0) >= 5000) void loadPage(page);
void fetchLogs(current());
}
function schedulePoll() {
clearTimeout(pollTimer);
if (disposed || redirecting || !state.ready) return;
pollTimer = setTimeout(() => {
void tick();
schedulePoll();
}, document.hidden ? 5000 : 1000);
}
function requireAuth() {
if (redirecting || disposed) return;
redirecting = true;
state.ready = false;
clearTimeout(pollTimer);
accounts.forEach(account => {
clearTimeout(account.saveTimer);
account.pages.forEach(page => { clearTimeout(page.loadTimer); clearTimeout(page.queryTimer); page.root.hidden = true; page.login?.clearPassword(); });
account.jobs.forEach(record => { clearTimeout(record.timer); record.reject(new Error('请重新登录管理工作台。')); });
account.jobs.clear();
});
updateCleanups.forEach(cleanup => cleanup());
$$('dialog[open]').forEach(root => root.close());
$$('.context-menu').forEach(root => root.remove());
const noticeNode = $('#notice');
if (noticeNode) noticeNode.hidden = true;
location.replace(webPath('/login'));
}
async function bootstrap() {
try {
state.error = null;
setStatus('正在连接');
const auth = await api.auth();
if (disposed || redirecting) return;
if (auth.required && !auth.authenticated) { requireAuth(); return; }
const [meta, schema] = await Promise.all([api.meta(), api.schema()]);
if (disposed || redirecting) return;
state.meta = meta;
state.schema = schema;
state.accessMode = auth.access_mode;
await syncAccounts(true);
if (disposed || redirecting) return;
state.ready = true;
setStatus('控制台已连接');
schedulePoll();
} catch (failure) {
if (failure.status === 401) requireAuth();
else reportError(failure);
}
}
window.addEventListener('auth-required', requireAuth, {signal:lifecycle.signal});
window.addEventListener('beforeunload', event => {
if (!redirecting && [...accounts.values()].some(account => account.edits.size || account.savePromise)) {
event.preventDefault();
event.returnValue = '';
}
}, {signal:lifecycle.signal});
window.addEventListener('pagehide', () => {
state.ready = false;
clearTimeout(pollTimer);
accounts.forEach(account => {
clearTimeout(account.saveTimer);
account.pages.forEach(page => { clearTimeout(page.loadTimer); clearTimeout(page.queryTimer); page.login?.clearPassword(); });
account.jobs.forEach(record => clearTimeout(record.timer));
});
updateCleanups.forEach(cleanup => cleanup());
}, {signal:lifecycle.signal});
window.addEventListener('pageshow', event => {
if (!event.persisted || disposed) return;
redirecting = false;
accounts.forEach(account => account.jobs.forEach(record => { void pollJob(account, record); }));
void init(host);
}, {signal:lifecycle.signal});
document.addEventListener('visibilitychange', () => {
if (document.hidden || !state.ready || disposed || redirecting) return;
const page = currentPage();
if (page?.data && page.configDirty) invalidatePages(page.account);
void tick();
schedulePoll();
}, {signal:lifecycle.signal});
async function pageAction(page,action,currency) {
const account=page.account,operation=action.operation;
if(operation==='configure_bag'||operation==='configure_ranch'){await navigate(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 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 || disposed || redirecting) return;
const summary = await api.create(result.label, demo);
if (disposed || redirecting) return;
accounts.set(summary.id, makeAccount(summary));
state.page = 'login';
await selectAccount(summary.id);
notice(demo ? '离线演示账号已创建' : '账号已创建,请在登录页登录。');
return summary;
}
function readView(account, key, query = {}) {
account.viewRequests ||= new Map();
const signature = JSON.stringify(query);
const pending = account.viewRequests.get(key);
if (pending) {
if (pending.signature === signature) return pending.promise;
return pending.promise.catch(() => {}).then(() => readView(account, key, query));
}
const promise = api.view(account.id, key, query).finally(() => {
if (account.viewRequests.get(key)?.promise === promise) account.viewRequests.delete(key);
});
account.viewRequests.set(key, {promise, signature});
return promise;
}
async function exportYields(account = current()) {
if (!account || !alive(account)) throw new Error('请先选择账号。');
// An explicit export can read a snapshot without mounting a hidden PageView.
const page = account.pages.get('yields');
const query = clone(page?.query || {});
const deadline = Date.now() + 30000;
let response;
do {
response = await readView(account, 'yields', query);
if (!alive(account)) return;
if (response.data?.columns?.length) break;
await new Promise(resolve => setTimeout(resolve, 650));
} while (alive(account) && Date.now() < deadline);
if (!response?.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, response.data.rows || []), '牧场收益资料.csv');
}
async function command(name, optionalAccountId) {
// Resolve once before dialogs, file pickers or config saves can yield.
const account = accounts.get(optionalAccountId === undefined ? state.activeId : optionalAccountId);
try {
if (disposed || redirecting) return;
if (name === 'add-account' || name === 'add-demo') return await addAccount(name === 'add-demo');
if (name === 'about') return await 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') {
state.ready = false;
clearTimeout(pollTimer);
hidePages();
accounts.forEach(item => item.pages.get('login')?.login?.clearPassword());
try { await api.logout(); } finally { requireAuth(); }
return;
}
if (name === 'start-all' || name === 'stop-all') {
const results = await Promise.allSettled([...accounts.values()].filter(alive).map(item => perform(item, name === 'start-all' ? 'start' : 'stop')));
const failures = results.filter(result => result.status === 'rejected');
if (failures.length) throw new Error(failures.map(result => result.reason?.message || String(result.reason)).join(';'));
return results.map(result => result.value);
}
if (!account || !alive(account)) throw new Error('请先新增或选择账号。');
if (name === 'debug') return await changeLogDebug(account, !account.logs.debug);
if (name === 'save') { await flushConfig(account); notice('策略已保存。'); return; }
if (name === 'start' || name === 'stop' || name === 'logout') return await perform(account, name);
if (name === 'toggle-strategy') return await perform(account, account.summary.running || account.startingGeneration !== null ? 'stop' : 'start');
if (name === 'refresh') return await perform(account, 'refresh', {page:account.page});
if (name === 'forget-login') {
if (await confirm('退出并清除登录记录', '将退出当前角色,删除当前账号保存的登录会话和账号密码。培养策略和其他账号不受影响。', {confirm:'清除登录记录', danger:true})) return await perform(account, 'forget_login');
return;
}
if (name === 'remove-account') {
if (!await confirm('移除当前账号', `移除“${account.summary.label || '当前账号'}”及其保存的会话和策略?此操作无法撤销。`, {confirm:'移除账号', danger:true})) return;
if (!alive(account)) return;
account.removing = true;
clearTimeout(account.saveTimer);
try { await api.remove(account.id); }
catch (failure) {
account.removing = false;
account.jobs.forEach(record => { void pollJob(account, record); });
publish();
throw failure;
}
if (disposed || redirecting) return;
releaseAccount(account);
accounts.delete(account.id);
if (state.activeId === account.id) {
state.page = 'login';
await selectAccount(accounts.keys().next().value ?? null);
}
publish();
if (!accounts.size) setStatus('等待新增账号');
return;
}
if (name === 'export-config') {
await flushConfig(account);
if (!alive(account)) return;
const result = await trackJob(account, await api.exportConfig(account.id));
if (alive(account)) download(new Blob([JSON.stringify(result, null, 2)], {type:'application/json'}), '牧场策略.json');
return result;
}
if (name === 'import-config') {
const file = await filePicker('.json');
if (!file || !alive(account)) 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);
if (!alive(account)) return;
const result = await trackJob(account, await api.importConfig(account.id, config));
await refreshConfig(account);
await refreshStatus(account);
if (!alive(account)) return;
notice('策略已导入,运行保持关闭。');
const page = account.pages.get(account.page);
if (page && visible(page)) await loadPage(page, true);
return result;
}
if (name === 'import-yields') return await importYields(account);
if (name === 'export-yields') return await exportYields(account);
if (['toggle-log', 'show-log', 'hide-log'].includes(name)) {
editConfig(account, ['log_visible'], name === 'show-log' || name === 'toggle-log' && !(account.config?.log_visible ?? true));
return;
}
if (name === 'clear-log') { account.logs.entries = []; publish(); return; }
if (name === 'download-log') {
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');
return;
}
throw new Error('未知操作。');
} catch (failure) { reportError(failure); }
}
function logsNeeded(account) {
return account && alive(account) && current() === account && !document.hidden && ((account.config?.log_visible ?? true) || state.page === 'activity');
}
async function fetchLogs(account, force = false) {
if (!logsNeeded(account)) return;
const log = account.logs;
if (log.promise) {
if (force) { await log.promise; if (logsNeeded(account)) return fetchLogs(account, true); }
return log.promise;
}
if (!force && Date.now() - log.lastLoad < 3000) return;
const generation = log.generation;
log.promise = (async () => {
try {
const response = await api.logs(account.id, log.next, log.debug);
if (!logsNeeded(account) || generation !== log.generation) return;
const seen = new Set(log.entries.map(entry => entry.id).filter(id => id != null));
const fresh = (response.entries || []).filter(entry => {
if (entry.id == null) return true;
if (seen.has(entry.id)) return false;
seen.add(entry.id);
return true;
});
log.entries = [...log.entries, ...fresh].slice(-500);
log.next = response.next ?? log.next;
publish();
} catch (failure) {
if (current() === account && failure.status !== 401) setStatus(failure.message);
} finally { log.lastLoad = Date.now(); }
})().finally(() => { log.promise = null; });
return log.promise;
}
async function changeLogDebug(account, value) {
if (!account || !alive(account)) return;
if (account.logs.debug !== value) {
account.logs.debug = value;
account.logs.entries = [];
account.logs.next = 0;
account.logs.lastLoad = 0;
account.logs.generation++;
}
if (account.config && account.config.log_visible === false) editConfig(account, ['log_visible'], true);
publish();
await fetchLogs(account, true);
}
async function showDebugEntry(account, entry) {
if (!account || !alive(account) || !entry) return;
const pre = el('pre', {class:'debug-json', text:'正在读取所选条目的脱敏详情…'});
const open = dialog('请求 / 响应详情(已脱敏)', pre, {info:true});
try {
let path;
try { path = apiPath(entry.detail_url || entry.debug_url); } catch { /* Fall back to the captured account's endpoint. */ }
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 || String(failure); }
await open;
}
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 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 cleanup=()=>{closed=true;clearTimeout(timer);lifetime.abort();};
updateCleanups.add(cleanup);
const active=()=>!disposed && !redirecting && !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{cleanup();updateCleanups.delete(cleanup);}
}
return {state, init, navigate, selectAccount, command, refresh, setInterval, retrySave, setLogDebug, inspectLog, dispose};
}
+38
View File
@@ -0,0 +1,38 @@
export function number(value) {
if (value == null || value === '') return '—';
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric.toLocaleString('zh-CN', { maximumFractionDigits: 2 }) : String(value);
}
export function accountName(account) {
return account?.label || account?.player?.name || '未命名账号';
}
export function connection(account) {
if (account?.error) return { label: '连接异常', tone: 'danger' };
if (account?.demo) return { label: '离线演示', tone: 'warning' };
if (account?.connected) return { label: '已连接', tone: 'success' };
return { label: '未连接', tone: 'neutral' };
}
export function time(value) {
if (value == null || 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' }).format(parsed);
}
export function logMessage(entry) {
return String(entry.message || entry.operation || '');
}
export function downloadText(content, filename) {
const url = URL.createObjectURL(new Blob(['\ufeff', content], { type: 'text/plain;charset=utf-8' }));
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.append(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
+15
View File
@@ -0,0 +1,15 @@
import { createApp } from 'vue';
import App from './App.vue';
import './styles/tokens.css';
import './styles/console.css';
import './styles/pages.css';
// Scrolling a dense form must never silently change a numeric setting.
document.addEventListener('wheel', (event) => {
if (event.target instanceof HTMLInputElement && event.target.type === 'number'
&& event.target !== document.activeElement) {
event.preventDefault();
}
}, { passive: false, capture: true });
createApp(App).mount('#app');
+33
View File
@@ -0,0 +1,33 @@
export const navigation = [
{ label: '工作空间', items: [
{ key: 'overview', label: '总览', icon: 'overview', description: '查看全部账号的连接状态与策略运行情况。', global: true },
{ key: 'accounts', label: '账号管理', icon: 'accounts', description: '集中管理游戏账号与连接,进入账号配置策略。', global: true },
] },
{ label: '游戏资源', items: [
{ key: 'login', label: '连接管理', icon: 'connection', description: '登录游戏、选择区服,或恢复已保存的会话。' },
{ key: 'incubator', label: '培育室', icon: 'incubator', description: '查看孵化进度,管理培育室与孵化操作。' },
{ key: 'bag', label: '背包', icon: 'bag', description: '管理魔物蛋、物品与装备,配置物品使用规则。' },
{ key: 'ranch', label: '牧场', icon: 'ranch', description: '查看魔物与培养目标,管理喂养和派遣。' },
{ key: 'daily', label: '每日事务', icon: 'daily', description: '查看每日任务与可领取奖励。' },
] },
{ label: '自动化策略', items: [
{ key: 'hatching', label: '自动孵蛋', icon: 'hatching', description: '配置孵蛋、牧场与喂养策略,修改后自动保存。' },
{ key: 'gifts', label: '自动赠礼', icon: 'gifts', description: '配置赠礼物品、目标与执行条件。' },
{ key: 'commissions', label: '自动委托', icon: 'commissions', description: '管理委托任务与自动执行规则。' },
{ key: 'exploration', label: '自动探险', icon: 'exploration', description: '配置探险队伍、目标与优先级。' },
{ key: 'mainline', label: '自动主线', icon: 'mainline', description: '查看主线任务与推进条件,配置推进策略。' },
{ key: 'maps', label: '自动扫荡', icon: 'maps', description: '筛选关卡、查看掉落,配置扫荡规则。' },
] },
{ label: '运行观测', items: [
{ key: 'plans', label: '执行计划', icon: 'plans', description: '预览当前策略与待执行任务。' },
{ key: 'battles', label: '战斗记录', icon: 'battles', description: '查看战斗结果与关卡执行记录。' },
{ key: 'statistics', label: '数据分析', icon: 'statistics', description: '按关卡查看掉落统计与实测收益。' },
{ key: 'activity', label: '运行日志', icon: 'activity', description: '查看当前账号的运行记录与任务状态。', global: true },
] },
{ label: '资料与系统', items: [
{ key: 'yields', label: '收益资料', icon: 'yields', description: '查阅孵化收益,导入或下载自定义收益资料。' },
{ key: 'system', label: '系统设置', icon: 'system', description: '管理账号配置,查看版本更新与系统信息。', global: true },
] },
];
export const pages = Object.fromEntries(navigation.flatMap(group => group.items.map(item => [item.key, { ...item, group: group.label }])));
+204
View File
@@ -0,0 +1,204 @@
/* Application frame: web navigation and document scrolling. */
.console-shell { min-width: 0; min-height: 100dvh; }
.skip-link { position: fixed; top: 10px; left: 240px; z-index: 100; padding: 8px 14px; border-radius: 5px; background: var(--accent); color: #fff; transform: translateY(-160%); }
.skip-link:focus { transform: translateY(0); }
.sidebar { position: fixed; inset: 0 auto 0 0; z-index: 50; display: flex; flex-direction: column; width: var(--sidebar-width); height: 100dvh; overflow: hidden; overscroll-behavior: contain; background: var(--sidebar); color: var(--sidebar-text); scrollbar-width: auto; scrollbar-color: #43516a transparent; }
.sidebar-brand { display: flex; align-items: center; flex: 0 0 auto; gap: 11px; min-height: 84px; padding: 18px 20px; color: #fff; text-decoration: none; border-bottom: 1px solid rgb(255 255 255 / 8%); }
.brand-mark { display: grid; place-items: center; flex: 0 0 34px; width: 34px; height: 36px; border-radius: 7px; background: #2563eb; color: #fff; }
.brand-mark .icon { width: 23px; height: 23px; }
.sidebar-brand strong { display: block; font-size: 17px; font-weight: 650; letter-spacing: .2px; }
.sidebar-brand small { display: block; margin-top: 2px; color: #b3bfd2; font-size: 11px; }
.sidebar > nav { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 9px 12px 20px; scrollbar-width: auto; }
.nav-group { margin: 14px 0 0; }
.nav-group h2 { margin: 0 12px 6px; color: #99a9bf; font-size: 12px; font-weight: 500; }
.nav-link { display: flex; align-items: center; gap: 11px; width: 100%; min-height: 38px; margin: 2px 0; padding: 8px 12px; border: 0; border-radius: 5px; color: var(--sidebar-text); background: transparent; text-decoration: none; line-height: 1.5; text-align: left; }
.nav-link span { min-width: 0; overflow-wrap: anywhere; }
.nav-link .icon { width: 17px; height: 17px; flex-basis: 17px; opacity: .9; }
.nav-link:hover { color: #fff; background: rgb(255 255 255 / 7%); }
.nav-link.selected, .nav-link.active, .nav-link[aria-current="page"] { color: #fff; background: #2563eb; font-weight: 550; }
.sidebar :focus-visible { outline-color: #9ec4ff; outline-offset: 2px; }
.sidebar-footer { display: flex; flex-wrap: wrap; align-items: center; gap: 7px; flex: 0 0 auto; margin-top: auto; padding: 16px 20px; border-top: 1px solid rgb(255 255 255 / 10%); color: #aab9cf; font-size: 11px; }
.sidebar-footer > :last-child { margin-left: auto; }
.sidebar-footer .status-dot { background: #77c897; }
.console-main { display: flex; flex-direction: column; min-width: 0; min-height: 100dvh; margin-left: var(--sidebar-width); }
.topbar { position: sticky; top: 0; z-index: 20; display: flex; align-items: center; justify-content: space-between; gap: 16px; min-width: 0; min-height: var(--topbar-height); padding: 10px 24px; background: var(--surface); border-bottom: 1px solid var(--border); }
.context-bar { display: flex; align-items: center; flex: 1 1 auto; gap: 16px; min-width: 0; }
.context-divider { height: 22px; width: 1px; background: var(--border); flex: 0 0 1px; }
.workspace-name { flex: 0 0 auto; white-space: nowrap; font-weight: 600; }
.account-picker { display: flex; align-items: center; gap: 8px; min-width: 0; }
.account-picker { flex: 0 1 260px; }
.account-picker > .icon { color: var(--muted); }
.account-picker select { width: 100%; min-width: 0; }
.user-actions { display: flex; align-items: center; justify-content: flex-end; flex: 0 0 auto; gap: 10px; }
.user-actions > .text-button { color: var(--muted); font-size: 13px; }
.user-actions > .danger-text { color: var(--danger); }
.content-area { flex: 1 1 auto; width: 100%; min-width: 0; padding: 20px 24px 0; }
.content-area > * { min-width: 0; max-width: 100%; }
.breadcrumb { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 16px; color: var(--muted); font-size: 12px; overflow-wrap: anywhere; }
.breadcrumb a { color: var(--muted); text-decoration: none; }
.breadcrumb a:hover { color: var(--accent); text-decoration: underline; }
.breadcrumb strong { color: var(--text); font-weight: 500; }
.page-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; margin-bottom: 20px; }
.page-heading > div { min-width: 0; }
.page-description { margin-top: 5px; color: var(--muted); font-size: 13px; line-height: 1.7; }
.button-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; }
.page-heading > .button-row { flex: 0 0 auto; padding-top: 2px; }
.global-view { display: flex; flex-direction: column; gap: 20px; min-width: 0; }
.global-view.panel { gap: 0; }
.metric-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; }
.metric-card { display: flex; flex-direction: column; align-items: flex-start; min-width: 0; padding: 18px 20px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); box-shadow: var(--shadow); }
.metric-card > span { color: var(--muted); font-size: 13px; }
.metric-card > strong, .metric-value { margin: 7px 0 6px; font-size: 30px; line-height: 1.2; font-weight: 650; font-variant-numeric: tabular-nums; letter-spacing: -.6px; }
.metric-card > small { color: var(--muted); font-size: 12px; overflow-wrap: anywhere; }
.metric-attention > strong { color: var(--warning); }
.panel { min-width: 0; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); box-shadow: var(--shadow); }
.panel-heading { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; min-width: 0; padding: 17px 20px; border-bottom: 1px solid var(--border); }
.panel-heading > div { min-width: 0; }
.panel-heading p { margin-top: 3px; color: var(--muted); font-size: 12px; }
.panel-heading > .icon { color: var(--muted); }
.panel > .filter-bar { padding: 12px 20px; border-bottom: 1px solid var(--border); }
.overview-grid, .info-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: stretch; gap: 20px; }
.overview-note { display: flex; align-items: flex-start; gap: 10px; padding: 0 2px; color: var(--muted); font-size: 12px; line-height: 1.8; }
.overview-note > .icon { margin-top: 2px; color: #697c98; }
.attention-list { list-style: none; margin: 0; padding: 0 20px; }
.attention-list li { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding: 12px 0; border-bottom: 1px solid var(--border); }
.attention-list li:last-child { border-bottom: 0; }
.attention-list li > span { flex: 1 1 180px; color: var(--danger); overflow-wrap: anywhere; }
.account-resource-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 16px 24px; padding: 16px 20px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); }
.resource-identity { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; padding-right: 20px; border-right: 1px solid var(--border); }
.resource-identity strong { max-width: 220px; overflow-wrap: anywhere; }
.resource-identity > span:last-child { color: var(--muted); font-size: 12px; }
.resource-item { display: flex; flex-direction: column; min-width: 48px; font-variant-numeric: tabular-nums; }
.resource-item > span { color: var(--muted); font-size: 12px; }
.resource-item strong { font-size: 14px; font-weight: 600; overflow-wrap: anywhere; }
.context-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-left: auto; min-width: 0; }
.inline-label, .checkbox-label { display: inline-flex; align-items: center; gap: 7px; min-width: 0; color: var(--muted); font-size: 13px; }
.inline-label select { color: var(--text); }
.workspace-meta { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 6px 18px; margin: 10px 0 18px; color: var(--muted); font-size: 12px; }
.status-pill { display: inline-flex; align-items: center; gap: 6px; min-height: 25px; max-width: 100%; padding: 2px 8px; border-radius: 4px; background: #edf1f6; color: #526079; font-size: 12px; line-height: 1.5; white-space: nowrap; vertical-align: middle; }
.status-pill.success { color: #17613c; background: var(--green-tint); }
.status-pill.warning { color: #80510b; background: var(--warning-tint); }
.status-pill.danger { color: #a32634; background: var(--danger-tint); }
.status-pill.neutral { color: #526079; background: #edf1f6; }
.status-pill .icon { width: 13px; height: 13px; flex-basis: 13px; }
.status-dot { display: inline-block; width: 6px; height: 6px; flex: 0 0 6px; border-radius: 50%; background: currentColor; }
.empty-block { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; min-height: 216px; padding: 32px 20px; text-align: center; }
.empty-block p { max-width: 60ch; color: var(--muted); font-size: 13px; }
.empty-block > .icon, .empty-icon { color: #8293ad; }
.empty-block > .icon { width: 30px; height: 30px; flex-basis: 30px; }
.empty-icon { display: grid; place-items: center; width: 48px; height: 48px; margin-bottom: 3px; border-radius: 50%; background: #f0f4fa; }
.empty-icon .icon { width: 24px; height: 24px; }
.empty-block button { margin-top: 4px; }
.account-table-scroll { width: 100%; min-width: 0; max-width: 100%; overflow: auto; border-radius: 0 0 var(--radius) var(--radius); scrollbar-width: auto; }
.account-table { width: 100%; min-width: 760px; border-collapse: collapse; text-align: left; font-size: 13px; }
.account-table th { padding: 11px 20px; background: var(--surface-subtle); color: var(--muted); font-size: 12px; font-weight: 500; white-space: nowrap; border-bottom: 1px solid var(--border); }
.account-table td { padding: 15px 20px; border-bottom: 1px solid #edf0f5; vertical-align: middle; }
.account-table tr:last-child td { border-bottom: 0; }
.account-table tbody tr:hover { background: #f8faff; }
.account-table .current-account-row { background: #fbfcff; }
.account-name-cell { display: flex; align-items: center; gap: 10px; min-width: 140px; }
.account-avatar { display: grid; place-items: center; width: 34px; height: 34px; flex: 0 0 34px; border: 1px solid #dce7fb; border-radius: 7px; background: #edf3ff; color: #315fa8; font-size: 14px; font-weight: 600; }
button.account-name { justify-content: flex-start; min-height: auto; max-width: 210px; padding: 0; font-weight: 600; overflow-wrap: anywhere; text-align: left; }
.current-label, .table-secondary { display: block; margin-top: 3px; color: var(--muted); font-size: 11px; }
.current-label { color: var(--accent); }
.account-player { display: block; max-width: 200px; overflow-wrap: anywhere; }
.row-actions { display: flex; justify-content: flex-end; align-items: center; gap: 6px; white-space: nowrap; }
.row-actions-heading { text-align: right; }
.row-actions .icon { width: 14px; height: 14px; flex-basis: 14px; }
.system-card { display: flex; flex-direction: column; min-width: 0; padding-bottom: 20px; }
.system-card > p, .system-card > .button-row, .system-card > dl { margin: 16px 20px 0; }
.system-card > p { color: var(--muted); font-size: 13px; }
.system-card > .button-row { margin-top: auto; padding-top: 18px; }
.system-facts { display: grid; grid-template-columns: 86px minmax(0, 1fr); gap: 10px 16px; font-size: 13px; }
.system-facts dt { color: var(--muted); }
.system-facts dd { margin: 0; overflow-wrap: anywhere; }
.log-dock { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px; margin: 18px 0 10px; }
.log-dock > button { font-size: 12px; }
.activity-panel { margin-top: 12px; }
.activity-filters { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 16px; padding: 12px 20px; border-bottom: 1px solid var(--border); }
.search-field { display: block; min-width: 0; }
.search-field input { width: 240px; max-width: 100%; }
.activity-lines { max-height: 380px; min-height: 160px; margin: 0; padding: 6px 0; overflow: auto; list-style: none; border-radius: 0 0 var(--radius) var(--radius); background: #fcfdff; }
.activity-line { display: grid; grid-template-columns: 72px 38px minmax(0, 1fr); align-items: baseline; gap: 10px; padding: 6px 20px; border-bottom: 1px solid #f0f3f7; font-size: 12px; line-height: 1.7; }
.activity-line:last-child { border-bottom: 0; }
.log-time { color: #68768c; font-variant-numeric: tabular-nums; }
.log-level { color: #526079; font-size: 11px; }
.log-message { min-width: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
button.log-message { justify-content: flex-start; min-height: 0; padding: 0 3px; border: 0; background: transparent; font: inherit; color: var(--accent); text-align: left; }
button.log-message .icon { width: 13px; height: 13px; flex-basis: 13px; }
.activity-line.error .log-level, .activity-line.error .log-message { color: var(--danger); }
.activity-line.warning .log-level, .activity-line.warning .log-message { color: #855509; }
.activity-line.debug .log-message { color: var(--muted); }
.pending-jobs { display: flex; flex-wrap: wrap; gap: 8px 18px; padding: 10px 0; color: var(--muted); font-size: 12px; }
.pending-jobs > span { display: inline-flex; align-items: center; gap: 6px; overflow-wrap: anywhere; }
.console-status { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; margin-top: 28px; padding: 16px 0; border-top: 1px solid var(--border); color: var(--muted); font-size: 11px; }
.connection-error { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; margin-bottom: 16px; padding: 10px 14px; border: 1px solid #ebc48d; border-radius: 6px; background: var(--warning-tint); color: #80510b; font-size: 13px; }
.connection-error > span { flex: 1 1 200px; overflow-wrap: anywhere; }
.startup-error, .console-loading { width: min(560px, calc(100% - 32px)); margin: 12vh auto; padding: 28px; border: 1px solid var(--border); border-radius: var(--radius); background: #fff; }
.startup-error p, .console-loading p { margin: 12px 0 20px; color: var(--muted); }
.mobile-sidebar-toggle, .drawer-scrim, .sidebar-close { display: none; }
@media (max-width: 1180px) and (min-width: 901px) {
.topbar { padding-inline: 20px; gap: 10px; }
.context-bar { gap: 10px; }
.account-picker { flex-basis: 190px; }
.user-actions { gap: 5px; }
.user-actions #save-status { display: none; }
.resource-identity { flex-basis: 100%; border: 0; padding: 0; }
}
@media (max-width: 900px) {
.console-main { margin-left: 0; }
.sidebar { transform: translateX(-100%); visibility: hidden; transition: transform 180ms ease, visibility 180ms ease; }
.console-shell.drawer-open .sidebar { transform: translateX(0); visibility: visible; }
.drawer-scrim { display: block; position: fixed; inset: 0; z-index: 40; width: 100%; max-width: none; height: 100dvh; min-height: 0; padding: 0; border: 0; border-radius: 0; background: rgb(15 26 43 / 48%); }
.drawer-scrim:hover:not(:disabled) { background: rgb(15 26 43 / 48%); border: 0; }
.mobile-sidebar-toggle { display: inline-flex; }
.sidebar-close { display: flex; justify-content: space-between; min-height: 40px; margin: 10px 12px 0; padding-inline: 12px; border-color: #485771; background: #1e2e47; color: #e2e9f4; }
.sidebar-close:hover:not(:disabled) { background: #2b3e5b; border-color: #7385a1; }
.desktop-only { display: none !important; }
.topbar { padding-inline: 16px; gap: 12px; }
.context-bar { gap: 10px; }
.content-area { padding-inline: 20px; }
.skip-link { left: 16px; }
.resource-identity { border: 0; padding: 0; }
}
@media (max-width: 600px) {
:root { --control-height: 38px; }
.topbar { flex-wrap: wrap; gap: 8px; padding: 10px 14px; }
.context-bar { flex: 1 1 100%; gap: 8px; }
.account-picker { flex: 1 1 120px; gap: 5px; }
.account-picker > .icon, .context-divider { display: none; }
.account-picker select { font-size: 12px; }
.user-actions { justify-content: flex-end; width: 100%; gap: 8px; }
.user-actions .icon-button { width: 34px; }
.user-actions > .text-button { font-size: 12px; }
.content-area { padding: 16px 14px 0; }
.breadcrumb { gap: 5px; margin-bottom: 12px; font-size: 11px; }
.page-heading { flex-direction: column; gap: 12px; margin-bottom: 16px; }
h1 { font-size: 22px; }
.page-heading > .button-row { flex: 0 1 auto; padding: 0; }
.metric-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
.metric-card { padding: 14px; }
.metric-card > strong { font-size: 27px; }
.metric-card > small { font-size: 11px; }
.global-view { gap: 14px; }
.panel-heading { padding: 14px; gap: 10px; }
.panel-heading > .button-row { width: 100%; }
.panel > .filter-bar { padding: 12px 14px; }
.overview-grid, .info-grid { grid-template-columns: minmax(0, 1fr); gap: 14px; }
.account-resource-bar { gap: 14px 18px; padding: 14px; }
.resource-identity { flex-basis: 100%; }
.resource-identity strong { max-width: 180px; }
.context-actions { flex-basis: 100%; justify-content: space-between; margin-left: 0; gap: 8px; padding-top: 12px; border-top: 1px solid var(--border); }
.context-actions .inline-label { flex-wrap: wrap; }
.empty-block { padding: 28px 16px; }
.system-card > p, .system-card > .button-row, .system-card > dl { margin-inline: 14px; }
.activity-filters { padding: 12px 14px; gap: 10px 12px; }
.activity-filters .search-field { width: 100%; }
.activity-filters .search-field input { width: 100%; }
.activity-filters .flex-spacer { display: none; }
.activity-line { grid-template-columns: 62px 30px minmax(0, 1fr); gap: 6px; padding-inline: 12px; font-size: 11px; }
.console-status { margin-top: 20px; }
.sidebar-close, .mobile-sidebar-toggle, .dialog-close { min-height: 40px; }
}
@media (max-width: 600px) { .activity-line { font-size: 12px; } }
+119
View File
@@ -0,0 +1,119 @@
/* Account views share data contracts, but use the web console's visual system. */
.page-host, .page-panel, .page-content { width: 100%; min-width: 0; max-width: 100%; }
.page-panel { display: flex; flex-direction: column; gap: 16px; padding: 18px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); box-shadow: var(--shadow); }
.page-header { display: flex; align-items: center; min-height: 14px; }
.page-header h2 { display: none; }
.page-loading { margin-left: auto; color: var(--muted); font-size: 12px; }
.page-loading[data-loading=true]::before { content: ''; display: inline-block; width: 6px; height: 6px; margin-right: 7px; border-radius: 50%; background: var(--accent); }
.page-summary { margin: 0; color: var(--muted); line-height: 1.7; white-space: pre-wrap; overflow-wrap: anywhere; }
.page-summary:empty, .page-toolbar:empty, .policy-form:empty { display: none; }
.page-error { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; padding: 12px 16px; border: 1px solid #ecc3c7; border-radius: 7px; background: #fff5f5; color: #a42a37; white-space: pre-wrap; overflow-wrap: anywhere; }
.page-toolbar, .filter-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 14px; min-width: 0; }
.filter-bar { padding: 12px 0; border-block: 1px solid var(--border); }
.filter-bar label { display: flex; align-items: center; gap: 8px; min-width: 0; max-width: 100%; }
.filter-bar label > span { flex: 0 0 auto; white-space: nowrap; }
.filter-bar label:has(input[type=search]) { flex: 1 1 300px; max-width: 600px; }
.filter-bar input[type=search] { flex: 1 1 auto; min-width: 0; width: 280px; max-width: 100%; }
.filter-bar select { max-width: min(100%, 360px); }
.subtabs { display: flex; gap: 4px; max-width: 100%; overflow-x: auto; border-bottom: 1px solid var(--border); }
.subtab { flex: 0 0 auto; padding: 9px 14px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; color: var(--muted); }
.subtab[aria-selected=true] { border-bottom-color: var(--accent); background: var(--tint); color: var(--accent); font-weight: 600; }
.page-content { display: flex; flex-direction: column; gap: 14px; }
.policy-form { display: flex; flex-direction: column; gap: 16px; min-width: 0; }
.form-section { margin: 0; min-width: 0; padding: 16px; border: 1px solid var(--border); border-radius: 8px; }
.form-section legend { padding: 0 8px; font-size: 14px; font-weight: 600; color: var(--text); }
.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); gap: 18px 24px; min-width: 0; }
.field { display: flex; flex-direction: column; align-items: stretch; gap: 7px; min-width: 0; max-width: 100%; }
.field-label { min-width: 0; color: var(--text); line-height: 1.6; overflow-wrap: anywhere; }
.field-input { min-width: 0; max-width: 100%; }
.field.checkbox-field { flex-direction: row; align-items: center; justify-content: flex-start; }
.field.checkbox-field .field-label { flex: 1; }
.field-wide, .field-help { grid-column: 1 / -1; }
.field-help, .inline-note, .info-note { color: var(--muted); font-size: 12px; line-height: 1.8; overflow-wrap: anywhere; }
.info-note { margin: 0; padding: 8px 12px; border-radius: 6px; background: var(--surface-subtle); }
.field[data-dirty=true] .field-label::after { content: ' ·'; color: var(--warning); }
.field.invalid input { border-color: var(--danger); }
.inline-editor, .multi-select, .member-selects { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; }
.multi-select label { display: inline-flex; align-items: center; gap: 6px; }
.member-selects select { width: 190px; max-width: 100%; }
.member-draft-note { flex-basis: 100%; font-size: 12px; color: var(--warning); }
.counts-lines { display: flex; flex-direction: column; gap: 8px; margin-bottom: 8px; }
.counts-editor { min-width: 0; }
.count-id { width: 110px; }
.login-layout { display: flex; flex-direction: column; gap: 20px; max-width: 800px; padding: 4px 0; }
.login-layout > form { padding: 20px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface-subtle); }
.login-layout input[type=text], .login-layout input[type=password] { width: 100%; }
.login-options, .login-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 14px; }
.login-options label { display: flex; align-items: center; gap: 6px; }
.server-row { display: flex; flex-wrap: wrap; gap: 10px; min-width: 0; }
.server-row select { flex: 1 1 220px; min-width: 0; }
.session-block { padding-top: 20px; border-top: 1px solid var(--border); }
.initial-state, .empty-state { padding: 32px 20px; color: var(--muted); line-height: 1.8; text-align: center; }
.empty-state button { margin-top: 14px; }
.table-scroll { position: relative; width: 100%; max-width: 100%; min-width: 0; max-height: 65vh; min-height: 80px; overflow: auto; border: 1px solid var(--border); border-radius: 7px; background: var(--surface); scrollbar-width: auto; }
.data-table { width: 100%; border-collapse: separate; border-spacing: 0; text-align: left; font-size: 13px; white-space: nowrap; font-variant-numeric: tabular-nums; }
.data-table th { position: sticky; top: 0; z-index: 2; padding: 10px 12px; border-bottom: 1px solid var(--border-strong); background: #f3f6fb; color: #41516c; font-weight: 600; text-align: center; }
.data-table th button { display: flex; align-items: center; justify-content: center; width: 100%; gap: 6px; min-height: 26px; padding: 0; border: 0; border-radius: 0; background: transparent; font: inherit; }
.data-table th .sort-mark { color: var(--accent); font-size: 10px; }
.data-table td { height: 44px; max-width: 280px; padding: 7px 12px; overflow: hidden; border-bottom: 1px solid #e9edf3; text-align: center; text-overflow: ellipsis; }
.data-table th:first-child, .data-table th:nth-child(2), .data-table td:first-child, .data-table td:nth-child(2) { text-align: left; }
.data-table th:first-child button, .data-table th:nth-child(2) button { justify-content: flex-start; }
.data-table tr:last-child td { border-bottom: 0; }
.data-table tr:nth-child(even) td { background: #fafbfd; }
.data-table tr:hover td { background: #f2f6fd; }
.data-table tr[aria-selected=true] td { background: #eaf2ff; }
.data-table .selection-cell { position: sticky; left: 0; z-index: 1; width: 40px; min-width: 40px; padding: 8px; text-align: center !important; background: var(--surface); }
.data-table th.selection-cell { z-index: 3; background: #f3f6fb; }
.data-table td.cell-edit { padding: 5px 8px; }
.data-table .cell-edit input[type=number] { width: 90px; min-width: 64px; min-height: 32px; text-align: center; }
.data-table .cell-edit select { max-width: 260px; min-height: 32px; }
.data-table .cell-edit input[type=text] { width: 150px; }
.data-table .cell-edit .inline-editor { justify-content: center; }
.data-table .cell-wrap { min-width: 190px; white-space: normal; overflow-wrap: anywhere; line-height: 1.7; }
.data-table .cell-ellipsis { max-width: 280px; }
.table-footer, .table-pagination { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 16px; padding: 12px 0 0; color: var(--muted); font-size: 12px; }
.table-page-size, .table-page-controls, .table-page-current, .table-selection-controls { display: flex; flex-wrap: wrap; align-items: center; gap: 7px; }
.table-page-controls { margin-left: auto; }
.table-page-current input { width: 58px; text-align: center; }
.table-selection-summary { color: var(--accent); }
.table-footer button { font-size: 12px; }
.grouped-tables { display: flex; flex-direction: column; gap: 10px; width: 100%; min-width: 0; }
.table-group { min-width: 0; border: 1px solid var(--border); border-radius: 7px; background: var(--surface); overflow: hidden; }
.table-group > summary { padding: 12px 16px; cursor: pointer; font-weight: 600; background: #f6f8fb; }
.table-group > summary small { margin-left: 12px; color: var(--muted); font-weight: 400; }
.group-table { min-width: 0; padding: 12px; }
.statistics-layout { display: flex; align-items: stretch; gap: 18px; min-width: 0; }
.statistics-picker { flex: 0 0 245px; min-width: 0; max-height: 70vh; overflow: auto; border: 1px solid var(--border); border-radius: 7px; }
.statistics-picker button { display: block; width: 100%; border: 0; border-radius: 0; text-align: left; overflow: hidden; text-overflow: ellipsis; }
.statistics-picker button[aria-selected=true] { color: var(--accent); background: var(--tint); }
.statistics-main { flex: 1 1 auto; display: flex; flex-direction: column; gap: 16px; min-width: 0; }
.statistics-table-host { min-width: 0; max-width: 100%; }
.statistics-city > summary, .statistics-stage > summary { padding: 10px; font-size: 13px; line-height: 1.6; cursor: pointer; overflow-wrap: anywhere; }
.statistics-city > summary { font-weight: 600; background: #f6f8fb; }
.statistics-stage { margin-left: 10px; }
.statistics-levels { padding: 0 0 8px 12px; }
.chart-scroll { min-width: 0; min-height: 130px; max-height: 400px; overflow: auto; padding: 12px; border: 1px solid var(--border); border-radius: 7px; }
.drop-chart { display: block; width: 100%; min-width: 420px; height: auto; }
.chart-label { fill: var(--text); font-size: 12px; }
.chart-axis, .chart-value { fill: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; }
.chart-bar { fill: var(--accent); }
.chart-grid { stroke: #e2e8f0; stroke-width: 1; }
.detail-list { display: grid; grid-template-columns: minmax(90px, auto) minmax(0, 1fr); gap: 10px 20px; }
.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: 18px; }
.debug-json { margin: 0; font: 12px/1.8 Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; }
@media (max-width: 1100px) { .statistics-picker { flex-basis: 200px; } }
@media (max-width: 760px) {
.page-panel { padding: 14px; gap: 14px; }
.form-section { padding: 12px; }
.form-grid { grid-template-columns: minmax(0, 1fr); gap: 16px; }
.filter-bar label { flex-wrap: wrap; }
.filter-bar label:has(input[type=search]), .filter-bar input[type=search] { width: 100%; }
.table-page-controls { margin-left: 0; }
.statistics-layout { flex-direction: column; }
.statistics-picker { flex: 0 0 auto; width: 100%; max-height: 230px; }
.login-layout > form { padding: 14px; }
.detail-list { grid-template-columns: minmax(0, 1fr); gap: 4px; }
.detail-list dd { margin-bottom: 10px; }
}
+87
View File
@@ -0,0 +1,87 @@
:root {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
font-size: 14px;
color: #17243b;
background: #f4f6fa;
color-scheme: light;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
--canvas: #f4f6fa;
--surface: #fff;
--surface-subtle: #f8fafc;
--text: #17243b;
--muted: #526079;
--border: #dbe2ec;
--border-strong: #bdc9d9;
--accent: #2563eb;
--accent-hover: #1d4ed8;
--tint: #edf3ff;
--green: #187447;
--green-tint: #edf8f1;
--danger: #bf3540;
--danger-tint: #fff1f2;
--warning: #94630e;
--warning-tint: #fff8e7;
--sidebar: #162235;
--sidebar-text: #bac6d8;
--sidebar-width: 224px;
--topbar-height: 64px;
--control-height: 34px;
--radius: 8px;
--radius-sm: 5px;
--shadow: 0 1px 3px rgb(26 42 65 / 4%);
--shadow-overlay: 0 12px 36px rgb(16 32 56 / 18%);
}
*, *::before, *::after { box-sizing: border-box; }
html { min-width: 0; scroll-padding-top: 80px; }
body { margin: 0; min-width: 0; font-size: 14px; line-height: 1.6; }
#app { min-width: 0; min-height: 100dvh; }
[hidden] { display: none !important; }
h1, h2, h3, h4, p { margin: 0; }
h1 { font-size: 24px; line-height: 1.4; font-weight: 650; letter-spacing: -.4px; }
h2 { font-size: 16px; line-height: 1.5; font-weight: 600; }
h3, h4 { font-size: 14px; line-height: 1.5; font-weight: 600; }
p { overflow-wrap: anywhere; }
a { color: var(--accent); text-underline-offset: 3px; }
button, input, select, textarea { font: inherit; color: inherit; }
button, select, textarea, input:not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="hidden"]) { min-height: var(--control-height); max-width: 100%; border: 1px solid var(--border-strong); border-radius: var(--radius-sm); background: var(--surface); }
button { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 5px 12px; line-height: 1.5; font-weight: 500; text-align: center; cursor: pointer; vertical-align: middle; transition: background-color 120ms ease, border-color 120ms ease, color 120ms ease; }
button:hover:not(:disabled) { border-color: #9bacc4; background: #f2f5fa; }
button:active:not(:disabled) { background: #e8edf5; }
button:disabled, input:disabled, select:disabled, textarea:disabled { opacity: .55; cursor: not-allowed; }
input:not([type="checkbox"]):not([type="radio"]):not([type="range"]), select { padding: 5px 9px; min-width: 0; }
input[type="number"] { width: 112px; font-variant-numeric: tabular-nums; }
input[type="checkbox"], input[type="radio"] { width: 16px; height: 16px; min-height: 0; flex: 0 0 16px; margin: 0; accent-color: var(--accent); vertical-align: middle; cursor: pointer; }
input::placeholder, textarea::placeholder { color: #68768c; opacity: 1; }
textarea { padding: 8px 10px; min-width: 0; min-height: 88px; resize: vertical; }
input, textarea { caret-color: var(--accent); }
select { overflow: hidden; text-overflow: ellipsis; }
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible, summary:focus-visible, [tabindex]:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; scroll-margin-block: 12px; }
::selection { background: #dbe8ff; color: #153b7e; }
button.primary, a.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
button.primary:hover:not(:disabled), a.primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
button.danger { color: #a32634; border-color: #e5b3b8; background: #fff; }
button.danger:hover:not(:disabled) { color: #932330; border-color: #cc7680; background: var(--danger-tint); }
.danger-text { color: #ae2d39; }
button.start-button, button.run-button { background: var(--green); border-color: var(--green); color: #fff; }
button.start-button:hover:not(:disabled), button.run-button:hover:not(:disabled) { background: #135d39; border-color: #135d39; }
button.stop-button, button.run-button.running { background: var(--danger); border-color: var(--danger); color: #fff; }
button.stop-button:hover:not(:disabled), button.run-button.running:hover:not(:disabled) { background: #a72b36; border-color: #a72b36; }
button.start-outline { color: var(--green); border-color: #a9cfb9; }
button.start-outline:hover:not(:disabled) { background: var(--green-tint); border-color: var(--green); }
button.stop-outline { color: var(--danger); border-color: #e5b3b8; }
button.stop-outline:hover:not(:disabled) { background: var(--danger-tint); border-color: var(--danger); }
button.text-button { border-color: transparent; background: transparent; color: var(--accent); padding-inline: 5px; }
button.text-button:hover:not(:disabled) { background: var(--tint); border-color: transparent; }
button.text-button.danger-text { color: var(--danger); }
button.small, button.compact, .small, .compact { min-height: 34px; padding: 4px 9px; font-size: 13px; }
.icon { display: inline-block; width: 18px; height: 18px; flex: 0 0 18px; vertical-align: middle; }
.icon-button { width: 34px; height: 34px; padding: 6px; flex: 0 0 34px; }
.muted { color: var(--muted); }
.error-text { color: var(--danger); white-space: pre-wrap; overflow-wrap: anywhere; }
.spacer, .flex-spacer { flex: 1 1 auto; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; }
}
+329
View File
@@ -0,0 +1,329 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import {createContext, runInContext} from 'node:vm';
import {shallowReactive, isReactive} from 'vue';
// Exercise orchestration with fake APIs and time. No server or game is contacted.
const source = await readFile(new URL('../src/controller.js', import.meta.url), 'utf8');
const dom = await readFile(new URL('../../ranch_web/static/dom.js', import.meta.url), 'utf8');
const paths = await readFile(new URL('../../ranch_web/static/paths.js', import.meta.url), 'utf8');
const keys = ['login','incubator','bag','ranch','daily','hatching','mainline','battles','gifts','commissions','exploration','maps','statistics','plans','yields'];
const plain = value => JSON.parse(JSON.stringify(value));
const settle = async () => { for (let i = 0; i < 40; i++) await Promise.resolve(); };
function deferred() {
let resolve, reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
return {promise, resolve, reject};
}
class Element extends EventTarget {
constructor(tag = 'div') {
super(); Object.assign(this, {tagName:tag.toUpperCase(), children:[], dataset:{}, value:'', hidden:false, isConnected:true, textContent:'', attributes:{}});
this.classList = {add(){}, toggle(){}};
}
append(...nodes) { this.children.push(...nodes); }
replaceChildren(...nodes) { this.children = nodes; }
setAttribute(key, value) { this.attributes[key] = value; }
querySelector(selector) { return selector === ':invalid' ? this.invalid : null; }
querySelectorAll() { return []; }
remove() { this.isConnected = false; }
focus() {}
click() {}
close() { this.open = false; }
}
async function fixture(t) {
const h = {calls:[], pages:[], notices:[], confirms:[], files:[], overrides:{}, now:100000, timers:new Map(), timerId:0};
h.accounts = new Map(['a', 'b'].map(id => [id, {id, label:id, connected:true, running:false, demo:true, revision:0, player:{name:id}}]));
h.configs = new Map(['a', 'b'].map(id => [id, {interval:30, policy:{egg_rules:{}}, log_visible:true, log_sizes:[420,140]}]));
h.base = {
auth:() => ({required:false, access_mode:'local'}), meta:() => ({version:'2.0.0', nested:{}}), schema:() => ({pages:[]}),
accounts:() => [...h.accounts.values()].map(value => structuredClone(value)),
config:id => ({config:structuredClone(h.configs.get(id)), revision:h.accounts.get(id).revision}),
save:(id, config) => { h.configs.set(id, structuredClone(config)); h.accounts.get(id).revision++; return h.base.config(id); },
status:id => structuredClone(h.accounts.get(id)),
view:(id, key) => ({data:{columns:[{key:'id'}], rows:[], marker:`${id}/${key}`}, loading:false}),
action:(id, operation) => {
if (operation === 'start' || operation === 'stop') h.accounts.get(id).running = operation === 'start';
return {id:`${id}/${operation}`, status:'succeeded', result:{}};
},
logs:() => ({entries:[], next:0}),
remove:id => { h.accounts.delete(id); },
job:() => ({status:'succeeded', result:{}}),
};
const api = new Proxy({}, {get:(_, name) => (...args) => {
h.calls.push({name, args:structuredClone(args), at:h.now});
return Promise.resolve().then(() => {
const fn = h.overrides[name] || h.base[name];
if (!fn) throw new Error(`Unexpected API call: ${String(name)}`);
return fn(...args);
});
}});
class PageView {
constructor(account, key, options) {
Object.assign(this, {account, key, options, root:new Element(), query:{}, data:null, renders:[], selected:[]});
this.login = key === 'login' ? {clearPassword(){}, update(){}} : null;
h.pages.push(this);
}
render(data) { this.data = data; this.renders.push(data); }
clearError() {}
showError(message) { this.error = message; }
selectedRows() { return this.selected; }
destroy() { this.destroyed = true; }
}
const document = Object.assign(new EventTarget(), {
hidden:false, body:new Element('body'), activeElement:null,
querySelector:selector => {
if (selector.startsWith('meta[')) return null;
if (selector === '#action-dialog') return {open:true, close(){}};
if (selector === '#notice') return null;
throw new Error(`Unexpected shell DOM query: ${selector}`);
},
querySelectorAll:() => [], createElement:tag => new Element(tag), createTextNode:text => Object.assign(new Element(), {textContent:text}),
});
const context = createContext({
shallowReactive, api, PageView, PAGES:keys.map(key => [key,key]), document, window:new EventTarget(),
location:{origin:'http://console.invalid', replace:target => { h.redirect = target; }},
structuredClone, AbortController, URL, Blob, Node:Element,
Date:class extends Date { static now() { return h.now; } },
setTimeout:(callback, delay = 0) => { const id = ++h.timerId; h.timers.set(id, {callback, at:h.now + delay}); return id; },
clearTimeout:id => h.timers.delete(id),
notice:(message, error) => h.notices.push({message,error}),
confirm:() => Promise.resolve(h.confirms.length ? h.confirms.shift() : true),
dialog:() => Promise.resolve(h.confirms.length ? h.confirms.shift() : null),
filePicker:() => Promise.resolve(h.files.shift() || null), fileBase64:async () => 'Zml4dHVyZQ==',
request:async path => { h.detailPath = path; return {details:{safe:true}}; },
});
runInContext(dom.replace(/^export /gm, ''), context);
runInContext(paths.replace(/^export /gm, ''), context);
runInContext(source.replace(/^import .+;\r?\n/gm, '').replace('export function createConsoleController', 'function createConsoleController'), context);
h.controller = runInContext('createConsoleController()', context);
h.document = document;
h.context = context;
h.advance = async duration => {
const until = h.now + duration;
for (;;) {
const next = [...h.timers].filter(([,timer]) => timer.at <= until).sort((a,b) => a[1].at - b[1].at)[0];
if (!next) break;
h.now = next[1].at; h.timers.delete(next[0]); next[1].callback(); await settle();
}
h.now = until; await settle();
};
h.findPage = (key, id = h.controller.state.activeId) => h.pages.find(page => page.key === key && page.account.id === id);
t.after(() => h.controller.dispose());
await h.controller.init(new Element()); await settle();
assert.equal(h.controller.state.error, null);
assert.equal(h.controller.state.ready, true);
return h;
}
test('exports the contract, keeps snapshots raw and skips APIs on shell pages', async t => {
const h = await fixture(t), c = h.controller;
assert.deepEqual(Object.keys(c).sort(), ['state','init','navigate','selectAccount','command','refresh','setInterval','retrySave','setLogDebug','inspectLog','dispose'].sort());
assert.ok(isReactive(c.state));
assert.equal(isReactive(c.state.accounts), false);
assert.equal(isReactive(c.state.meta.nested), false);
assert.equal(c.state.currentConfig.policy, undefined);
assert.ok(Object.isFrozen(c.state.currentConfig));
for (const key of ['overview','accounts','activity','system']) await c.navigate(key);
assert.equal(h.calls.filter(call => call.name === 'view').length, 0);
for (const key of keys) await c.navigate(key);
assert.deepEqual(h.calls.filter(call => call.name === 'view').map(call => call.args[1]), keys);
});
test('serializes edits added during an in-flight save and renders only the visible page', async t => {
const h = await fixture(t), c = h.controller, pending = deferred();
await c.navigate('bag'); const bag = h.findPage('bag');
await c.navigate('hatching'); const page = h.findPage('hatching');
const hiddenRenders = bag.renders.length;
h.overrides.save = (id, config) => h.calls.filter(call => call.name === 'save').length === 1 ? pending.promise : h.base.save(id, config);
c.setInterval(60); const saving = c.retrySave(); await settle();
c.setInterval(120); await settle();
assert.equal(h.calls.filter(call => call.name === 'save').length, 1);
pending.resolve({config:{...h.configs.get('a'), interval:60}, revision:1});
await saving; await settle();
const saves = h.calls.filter(call => call.name === 'save');
assert.deepEqual(saves.map(call => call.args[1].interval), [60,120]);
assert.equal(c.state.currentConfig.dirty, false);
assert.equal(c.state.interval, 120);
assert.equal(bag.renders.length, hiddenRenders);
assert.ok(page.renders.length > 1);
await c.navigate('bag');
assert.ok(bag.renders.length > hiddenRenders);
});
test('conflict rebasing retains explicit edits and respects server defaults and linked rules', async t => {
const h = await fixture(t), c = h.controller;
await c.navigate('bag'); const page = h.findPage('bag');
page.options.edit(page.account, ['policy','egg_rules','7','enabled'], true, {}, {
rule_path:['policy','egg_rules','7'], rule_defaults:{action:'feed', priority:1},
});
h.overrides.save = () => Promise.reject(Object.assign(new Error('conflict'), {status:409}));
h.configs.set('a', {interval:30, policy:{external:true, egg_rules:{7:{action:'feed', priority:8}}}});
h.accounts.get('a').revision = 8;
await c.retrySave();
assert.ok(c.state.saveError);
assert.equal(c.state.currentConfig.dirty, true);
h.overrides.save = h.base.save;
await c.retrySave();
const policy = h.configs.get('a').policy;
assert.deepEqual(plain(policy.egg_rules[7]), {action:'feed', priority:8, enabled:true});
assert.equal(policy.feed, true); assert.equal(policy.collect, true); assert.equal(policy.external, true);
assert.equal(c.state.saveError, null);
});
test('stop suppresses an unsent start waiting for a save after switching accounts', async t => {
const h = await fixture(t), c = h.controller, pending = deferred();
h.overrides.save = () => pending.promise;
c.setInterval(60); const saving = c.retrySave(); await settle();
const starting = c.command('start', 'a'); await settle();
await c.selectAccount('b');
await c.command('stop', 'a');
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','stop']]);
pending.resolve({config:{...h.configs.get('a'), interval:60}, revision:1});
await Promise.all([saving, starting]);
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','stop']]);
assert.equal(c.state.accounts.find(account => account.id === 'a').running, false);
assert.equal(c.state.activeId, 'b');
});
test('a delayed start stays bound to its original account when switching accounts without stop', async t => {
const h = await fixture(t), c = h.controller, pending = deferred();
h.overrides.save = () => pending.promise;
c.setInterval(60); const saving = c.retrySave(); await settle();
const starting = c.command('start', 'a'); await settle();
await c.selectAccount('b');
assert.equal(h.calls.filter(call => call.name === 'action').length, 0);
pending.resolve({config:{...h.configs.get('a'), interval:60}, revision:1});
await Promise.all([saving, starting]);
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','start']]);
assert.equal(c.state.activeId, 'b');
});
test('discards hidden-page responses and coalesces generation changes without overlapping views', async t => {
const h = await fixture(t), c = h.controller, pending = deferred();
let reads = 0;
h.overrides.view = () => ++reads === 1 ? pending.promise : {data:{marker:'fresh'}};
const navigation = c.navigate('bag'); await settle(); const page = h.findPage('bag');
page.query.search = 'new'; page.generation = 1;
const reloading = page.options.load(page, true); await settle(); assert.equal(reads, 1);
pending.resolve({data:{marker:'stale'}}); await Promise.all([navigation,reloading]);
assert.deepEqual(page.renders.map(data => data.marker), ['fresh']);
const hidden = deferred(); h.overrides.view = () => hidden.promise;
const second = c.navigate('ranch'); await settle(); await c.navigate('overview');
hidden.resolve({data:{marker:'hidden'}}); await second;
assert.equal(h.findPage('ranch').renders.length, 0);
});
test('removes the captured account without changing a newer selection, then selects after active removal', async t => {
const h = await fixture(t), c = h.controller, confirmation = deferred();
h.confirms.push(confirmation.promise);
const removing = c.command('remove-account', 'a'); await settle();
await c.selectAccount('b'); confirmation.resolve(true); await removing;
assert.equal(c.state.activeId, 'b');
assert.deepEqual(plain(c.state.accounts.map(account => account.id)), ['b']);
await c.command('remove-account', 'b');
assert.equal(c.state.activeId, null);
assert.equal(c.state.accounts.length, 0);
assert.equal(c.state.page, 'login');
const second = await fixture(t);
await second.controller.command('remove-account', 'a');
assert.equal(second.controller.state.activeId, 'b');
assert.equal(second.controller.state.page, 'login');
});
test('stop suppresses an unsent start waiting for an unselected account config', async t => {
const h = await fixture(t), c = h.controller, config = deferred();
h.overrides.config = id => id === 'b' ? config.promise : h.base.config(id);
const starting = c.command('start', 'b'); await settle();
assert.equal(h.calls.filter(call => call.name === 'config' && call.args[0] === 'b').length, 1);
assert.equal(h.calls.filter(call => call.name === 'action').length, 0);
await c.command('stop', 'b');
config.resolve(h.base.config('b')); await starting;
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['b','stop']]);
assert.equal(c.state.accounts.find(account => account.id === 'b').running, false);
assert.equal(c.state.activeId, 'a');
});
test('starting is synchronous and an older start cannot clear a newer pending start', async t => {
const h = await fixture(t), c = h.controller, config = deferred(), response = deferred();
const summary = () => c.state.accounts.find(account => account.id === 'b');
h.overrides.config = id => id === 'b' ? config.promise : h.base.config(id);
h.overrides.action = (id, operation) => operation === 'start' ? response.promise : h.base.action(id, operation);
const first = c.command('start', 'b');
assert.equal(summary().starting, true);
assert.equal(summary().running, false);
const stopping = c.command('stop', 'b');
assert.equal(summary().starting, false);
const second = c.command('start', 'b');
assert.equal(summary().starting, true);
await stopping;
config.resolve(h.base.config('b')); await first; await settle();
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['b','stop'],['b','start']]);
assert.equal(summary().starting, true);
assert.equal(summary().running, false);
h.accounts.get('b').running = true;
response.resolve({id:'latest-start', status:'succeeded', result:{}}); await second;
assert.equal(summary().starting, false);
assert.equal(summary().running, true);
});
test('stop on another account does not suppress a delayed start', async t => {
const h = await fixture(t), c = h.controller, pending = deferred();
h.overrides.save = () => pending.promise;
c.setInterval(60); const saving = c.retrySave(); await settle();
const starting = c.command('start', 'a'); await settle();
await c.command('stop', 'b');
pending.resolve({config:{...h.configs.get('a'), interval:60}, revision:1});
await Promise.all([saving, starting]);
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['b','stop'],['a','start']]);
});
test('stop preserves server tracking for a start whose request was already sent', async t => {
const h = await fixture(t), c = h.controller, response = deferred();
h.overrides.action = (id, operation) => operation === 'start' ? response.promise : h.base.action(id, operation);
h.overrides.job = () => ({id:'sent-start', status:'succeeded', result:{outcome:'server-result'}});
const starting = c.command('start', 'a'); await settle();
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','start']]);
await c.command('stop', 'a');
response.resolve({id:'sent-start', status:'queued', operation:'start'});
assert.deepEqual(plain(await starting), {outcome:'server-result'});
assert.equal(h.calls.filter(call => call.name === 'job' && call.args[1] === 'sent-start').length, 1);
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','start'],['a','stop']]);
});
test('jobs finish independently of blocked summaries; disposing rejects no unhandled job promises', async t => {
const h = await fixture(t), c = h.controller, summaries = deferred();
h.overrides.accounts = () => summaries.promise;
h.overrides.action = () => ({id:'job', status:'queued', operation:'stop'});
let polls = 0;
h.overrides.job = () => ++polls === 1 ? {id:'job',status:'running'} : {id:'job',status:'succeeded',result:{}};
const stopping = c.command('stop', 'a'); await settle();
assert.equal(c.state.jobs.length, 1);
await h.advance(1000); await stopping;
assert.equal(c.state.jobs.length, 0);
await h.advance(7000);
assert.equal(h.calls.filter(call => call.name === 'accounts').length, 2);
h.overrides.job = () => ({id:'job',status:'running'});
const disposedCommand = c.command('stop', 'b'); await settle();
c.dispose(); await disposedCommand; await settle();
const count = h.calls.length; await h.advance(20000); assert.equal(h.calls.length, count);
assert.equal(h.timers.size, 0);
summaries.resolve([]); await settle();
});
test('caps logs at 500, discards old debug responses and pauses hidden-document page and log reads', async t => {
const h = await fixture(t), c = h.controller, pending = deferred();
h.overrides.logs = (_, after, debug) => debug ? {entries:Array.from({length:650}, (_, id) => ({id, message:'debug'})), next:650} : pending.promise;
await h.advance(3000);
const debug = c.setLogDebug(true); await settle();
pending.resolve({entries:[{id:9000,message:'old'}],next:9001}); await debug;
assert.equal(c.state.logs.length, 500);
assert.equal(c.state.logs.some(entry => entry.message === 'old'), false);
assert.equal(c.state.logs[0].id, 150);
await c.navigate('bag'); h.document.hidden = true;
const before = h.calls.filter(call => call.name === 'view' || call.name === 'logs').length;
await h.advance(16000);
assert.equal(h.calls.filter(call => call.name === 'view' || call.name === 'logs').length, before);
});
+320
View File
@@ -0,0 +1,320 @@
// Run with node --test frontend/tests/table-*.test.mjs. Uses the project's
// Python Playwright and a system Chromium; every request is served in memory.
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {spawnSync} from 'node:child_process';
import test from 'node:test';
const sources = Object.fromEntries(['dom.js', 'forms.js', 'table.js', 'pages.js', 'ui.js'].map(name =>
[`/static/${name}`, readFileSync(new URL(`../../ranch_web/static/${name}`, import.meta.url), 'utf8')]));
const bootstrap = async () => {
const {DataTable, GroupedTables} = await import('/static/table.js');
const {PageView} = await import('/static/pages.js');
const {control, PolicyForm} = await import('/static/forms.js');
const {getPath, setPath} = await import('/static/dom.js');
Object.assign(globalThis, {DataTable, GroupedTables, PageView, control, PolicyForm});
globalThis.check = (condition, message) => { if (!condition) throw new Error(message); };
globalThis.tick = () => new Promise(resolve => setTimeout(resolve, 0));
globalThis.fixture = (count = 1000, options = {}) => {
const host = document.createElement('div');
document.body.append(host);
const config = {rules: {}, targets: {}};
const rows = Array.from({length: count}, (_, index) => {
const id = String(index + 1);
config.rules[id] = {priority: count - index, enabled: index % 2 === 0};
return {id, name: `条目 ${id}`, priority: index + 1, enabled: false, revision: 1};
});
const columns = [{key: 'name', label: '名称'},
{key: 'priority', label: '优先级', edit: {type: 'integer', min: 0, path: ['rules', '{id}', 'priority']}},
{key: 'enabled', label: '启用', edit: {type: 'boolean', path: ['rules', '{id}', 'enabled']}}];
const writes = [], selections = [];
const context = {
get: (path, fallback) => getPath(config, path, fallback),
set: (path, value, field, row) => { setPath(config, path, value); writes.push({path, value, field, row}); },
onSelection: selected => selections.push(selected),
};
const table = new DataTable(host, context, options);
table.update(columns, rows);
const ids = () => [...table.body.children].map(row => row.dataset.rowId);
return {host, config, rows, columns, context, table, writes, selections, ids};
};
};
const cases = {
'1000 rows create only current-page editors and all page sizes stay bounded': async () => {
const {host, table, columns, rows, ids} = fixture();
check(table.nodes.size === 50 && table.body.children.length === 50, '默认页应只有 50 行');
check(host.querySelectorAll('td input[type=number]').length === 50, '不可为其余 950 行创建编辑器');
check(table.count.textContent === '共 1000 项,显示 1–50 项', '中文总数和范围应正确');
check([...table.sizeSelect.options].map(option => option.value).join(',') === '25,50,100', '分页选项应为 25/50/100');
check(table.firstPage.disabled && !table.nextPage.disabled, '首页按钮边界应正确');
for (let page = 2; page <= 20; page++) {
table.setPage(page);
check(table.nodes.size === 50 && table.body.children.length === 50, '翻页后不可保留之前的 DOM 行');
}
check(ids()[0] === '951' && table.nextPage.disabled, '末页范围和按钮应正确');
table.sizeSelect.value = '25';
table.sizeSelect.dispatchEvent(new Event('change'));
check(table.page === 39 && table.pageCount === 40 && ids()[0] === '951', '改变页大小应保留原首条的位置');
check(table.nodes.size === 25, '25 条分页应只创建 25 行');
table.sizeSelect.value = '100';
table.sizeSelect.dispatchEvent(new Event('change'));
check(table.page === 10 && table.nodes.size === 100, '100 条分页应正确限制节点数量');
table.update(columns, rows);
check(table.body.children.length === 100, '轮询不得扩大 DOM');
table.pageInput.value = '0';
table.pageInput.dispatchEvent(new Event('change'));
check(table.pageInput.validationMessage === '请输入 1 到 10 之间的页码', '无效页码必须有中文错误');
},
'sorting uses all live configuration values before slicing a page': async () => {
const {table, columns, rows, config, ids} = fixture();
table.head.querySelector('[data-column=priority] button').click();
check(ids()[0] === '1000' && ids()[49] === '951', '应按全部 1000 条当前配置排序,而非快照或当前页');
check(table.body.querySelector('td[data-column=priority] input').value === '1', '编辑值必须与排序值相同');
config.rules['20'].priority = 0;
table.update(columns, rows);
check(ids()[0] === '20', '未渲染行的新配置应参与全局排序');
table.head.querySelector('[data-column=priority] button').click();
check(ids()[0] === '1', '降序应使用当前配置');
table.head.querySelector('[data-column=enabled] button').click();
check(ids().every(id => Number(id) % 2 === 0), '布尔编辑列应按配置排序');
const targetColumn = {key: 'selected', label: '目标', edit: {type: 'target', path: ['targets', '{id}']}};
config.targets['999'] = 100;
const overridden = rows.map(row => ({...row, selected: true, edits: {selected: {path: ['targets', row.id]}}}));
table.update([...columns, targetColumn], overridden);
table.head.querySelector('[data-column=selected] button').click();
table.head.querySelector('[data-column=selected] button').click();
check(ids()[0] === '999', '目标开关须按实际配置是否存在排序,不能读快照布尔值');
},
'selection persists across pages with explicit current-page and filtered scopes': async () => {
const {table, rows, columns, selections} = fixture();
table.nodes.get('1').check.click();
table.setPage(2);
check(table.selectedRows().length === 1 && table.selectedRows()[0].id === '1', '离开页面不应丢失选择');
check(table.allCheck.getAttribute('aria-label') === '选择本页全部 50 项', '表头全选范围应明确');
table.allCheck.click();
check(table.selectedRows().length === 51, '本页全选应保留其他分页的选择');
table.allCheck.click();
check(table.selectedRows().length === 1, '取消本页全选不得清除其他页');
table.selectFiltered.click();
check(table.selectedRows().length === 1000, '筛选全选应覆盖全部分页');
check(table.selectionCount.textContent === '已选择 1000 项(含其他分页)', '跨页总数应明确');
table.setPage(1);
check(table.nodes.get('1').check.checked, '回页后应恢复选中状态');
const fresh = rows.slice(499, 503).map(row => ({...row, revision: 2}));
table.update(columns, fresh);
check(table.selected.size === 4 && table.selectedRows().every(row => row.revision === 2), '缩减数据必须清除离页旧选择并返回最新行');
check(selections.at(-1).length === 4, '操作按钮应收到最新选择');
table.clearSelection.click();
check(table.selectedRows().length === 0 && table.clearSelection.disabled, '清除选择应涵盖所有分页');
},
'polling preserves a focused native editor and defers movement until blur': async () => {
const {table, columns, rows, config, ids, writes} = fixture();
for (const row of rows) config.rules[row.id].priority = Number(row.id);
table.head.querySelector('[data-column=priority] button').click();
const input = table.nodes.get('1').cells.get('priority').control.root;
input.focus();
input.value = '2000';
input.dispatchEvent(new Event('input', {bubbles: true}));
const fresh = rows.map(row => ({...row, revision: 2}));
table.update(columns, fresh);
check(document.activeElement === input && input.isConnected && input.value === '2000', '轮询不可替换、移动或覆盖正在编辑的输入框');
check(ids()[0] === '1' && table.pendingRender, '编辑中应暂缓将该行排到其他页');
check(table.nodes.size === 50, '编辑保护也必须保持 DOM 上限');
input.value = '2001';
input.dispatchEvent(new Event('input', {bubbles: true}));
check(writes.at(-1).row.revision === 2, '复用编辑器必须使用最新行,而非创建时的旧快照');
input.blur();
await tick();
check(ids()[0] === '2' && !table.nodes.has('1') && !table.pendingRender, '失焦后应立即完成排序和分页');
const other = table.nodes.get('2').cells.get('priority').control.root;
other.focus();
other.value = '';
table.update([...columns, {key: 'revision', label: '版本'}], fresh);
check(document.activeElement === other && other.value === '', '列变化时也必须保留未完成编辑');
other.blur();
await tick();
check(table.head.querySelector('[data-column=revision]'), '失焦后应应用延后的列变化');
},
'shrinking data clamps the page and removes even a deleted focused row': async () => {
const {table, columns, rows, ids} = fixture();
table.selectFiltered.click();
table.lastPage.click();
const removed = table.nodes.get('1000').cells.get('priority').control.root;
removed.focus();
table.update(columns, rows.slice(0, 3));
check(table.page === 1 && table.pageCount === 1, '数据缩减后应夹紧页码');
check(ids().join(',') === '1,2,3' && !removed.isConnected, '已删除的聚焦行不可残留');
check(table.selectedRows().length === 3 && table.selected.size === 3, '所有已删除选择均应清理');
table.update(columns, []);
check(table.nodes.size === 0 && table.body.children.length === 0, '空结果不可残留行');
check(!table.empty.hidden && table.count.textContent === '共 0 项,显示 0–0 项', '空状态及中文数量应正确');
check(table.allCheck.disabled && table.nextPage.disabled, '空结果应禁用选择与翻页');
},
'reused editors read fresh fallback rows and synchronize form disabled state': async () => {
const {table, columns, rows, config} = fixture(2);
delete config.rules['1'].priority;
const input = table.nodes.get('1').cells.get('priority').control.root;
table.update(columns, rows.map(row => ({...row, priority: 48, revision: 2})));
check(table.nodes.get('1').cells.get('priority').control.root === input && input.value === '48', '配置缺省时复用控件仍应读取最新行值');
const field = {type: 'integer', path: ['n'], label: '数量', value: 3};
const entry = control(field, {get: (_, fallback) => fallback, set: () => {}});
document.body.append(entry.root);
entry.root.focus();
entry.root.value = '12';
field.value = 9;
field.disabled = true;
entry.sync();
check(entry.root.value === '12' && !entry.root.disabled, '表单刷新应保留聚焦编辑');
entry.root.blur();
entry.sync();
check(entry.root.value === '9' && entry.root.disabled, '失焦后应同步最新值与禁用状态');
},
'closed grouped tables stay lazy and closed-group selections use current rows': async () => {
const {context, columns, rows, host} = fixture();
host.replaceChildren();
const grouped = new GroupedTables(host, context);
const items = rows.map((row, index) => ({...row, group: index < 500 ? 'a' : 'b'}));
grouped.update(columns, items, 'group', {a: '地区甲', b: '地区乙'});
check(host.querySelectorAll('tbody tr').length === 0, '折叠分组不可创建任何行或编辑器');
const group = grouped.groups.get('a');
group.root.open = true;
await tick();
check(group.table.nodes.size === 50 && grouped.groups.get('b').table === null, '仅展开的组应创建当前页');
group.table.selectFiltered.click();
group.root.open = false;
await tick();
const fresh = items.filter(row => row.group === 'b' || Number(row.id) <= 2).map(row => ({...row, revision: 5}));
grouped.update(columns, fresh, 'group');
check(grouped.selectedRows().length === 2 && grouped.selectedRows().every(row => row.revision === 5), '折叠组的选择不能返回过时行');
group.root.open = true;
await tick();
check(group.table.nodes.size === 2 && group.table.body.children.length === 2, '重新展开时不得残留缩减前的行');
grouped.update(columns, [], 'group');
check(grouped.groups.size === 0 && group.table.destroyed, '移除组应清理表格');
},
'polling preserves incomplete member choices without changing the three-member protocol': async () => {
const {table, rows, context, writes} = fixture(1);
const columns = [{key: 'members', label: '探险队', edit: {type: 'members', path: ['team'],
options: [{value: 1, label: '队长', level: 10}, {value: 2, label: '队员甲', level: 9}, {value: 3, label: '队员乙', level: 8}]}}];
table.update(columns, [{...rows[0], members: []}]);
const editor = table.nodes.get('1').cells.get('members').control.root;
const selects = [...editor.querySelectorAll('select')];
selects[0].focus();
selects[0].value = '1';
selects[0].dispatchEvent(new Event('change'));
check(writes.length === 0, '不完整队伍不可提交');
table.update(columns, [{...rows[0], name: '最新队伍', members: []}]);
check(document.activeElement === selects[0] && selects[0].value === '1', '轮询不可清空队伍草稿');
selects[1].value = '2';
selects[1].dispatchEvent(new Event('change'));
selects[2].value = '3';
selects[2].dispatchEvent(new Event('change'));
check(writes.length === 1 && writes[0].value.join(',') === '1,2,3', '只有完整三人队才应保存');
check(context.get(['team']).join(',') === '1,2,3', '保存的队伍配置格式不得变化');
},
'statistics retain lazy grouping and their measured chart source with a paginated table': async () => {
const account = {config: {}, edits: new Map()};
const options = {edit: () => {}, schema: () => [], load: () => {}, action: async () => {}, perform: async () => {}, command: () => {}};
const view = new PageView(account, 'statistics', options);
document.body.append(view.root);
view.root.hidden = false;
const stages = Array.from({length: 120}, (_, index) => ({id: String(index + 1), city_id: Math.floor(index / 30) + 1,
city_name: `地区 ${Math.floor(index / 30) + 1}`, label: `关卡 ${index + 1}`, levels: [{level: 1}, {level: 2}, {level: 3}]}));
const rows = Array.from({length: 1000}, (_, index) => ({id: String(index + 1), name: `实测物品 ${index + 1}`, rate: .5}));
const data = {columns: [{key: 'name', label: '物品'}, {key: 'rate', label: '实测概率'}], rows, stages,
chart: {series: [{label: '实际记录', value: .125}], max: 1}};
view.render(data);
check(view.statisticsPicker.querySelectorAll('.statistics-city').length === 4, '应按四个真实地区分组');
check(view.statisticsPicker.querySelectorAll('.statistics-levels button').length === 0, '统计难度列表必须保持惰性');
const city = view.statisticsPicker.querySelector('details');
city.open = true;
await tick();
check(view.statisticsPicker.querySelectorAll('.statistics-stage').length === 30, '展开地区应只创建该地区关卡');
city.querySelector('.statistics-stage').open = true;
await tick();
check(view.statisticsPicker.querySelectorAll('.statistics-levels button').length === 3, '展开关卡应只创建三种难度');
check(view.statisticsTable.nodes.size === 50 && view.statisticsTableHost.querySelectorAll('.selection-cell').length === 0, '统计表应分页且无选择列');
check(view.chart.querySelectorAll('.chart-bar').length === 1 && view.chart.textContent.includes('实际记录') && view.chart.textContent.includes('12.50%'), '图表应继续使用接口实测序列,而非当前分页或虚构数据');
view.statisticsTable.lastPage.click();
view.render({...data, rows: rows.slice(0, 3)});
check(view.statisticsTable.page === 1 && view.statisticsTable.nodes.size === 3, '统计表缩减后应清理末页');
check(view.chart.querySelectorAll('.chart-bar').length === 1, '分页不应改变图表来源');
view.destroy();
},
'destroy cancels deferred query loads and ignores late renders': async () => {
let loads = 0;
const view = new PageView({config: {}, edits: new Map()}, 'bag', {
edit: () => {}, schema: () => [], load: () => { loads++; }, action: async () => {}, perform: async () => {}, command: () => {},
});
document.body.append(view.root);
view.setQuery('search', '离线测试');
view.destroy();
view.setQuery('search', '不得重新安排');
view.render({rows: [], columns: []});
await new Promise(resolve => setTimeout(resolve, 260));
check(loads === 0 && !view.root.isConnected && view.data === null, '销毁后不可加载或重建页面');
},
};
const pythonHarness = String.raw`
import json, os, sys
from pathlib import Path
from playwright.sync_api import sync_playwright
payload = json.loads(sys.stdin.buffer.read().decode('utf-8'))
results = {}
with sync_playwright() as playwright:
candidates = [os.environ.get('RANCH_WEB_BROWSER', ''),
'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
'C:/Program Files/Google/Chrome/Application/chrome.exe']
executable = next((path for path in candidates if path and Path(path).is_file()), None)
browser = playwright.chromium.launch(headless=True, **({'executable_path': executable} if executable else {}))
for name, source in payload['cases'].items():
page = browser.new_page()
unexpected = []
errors = []
def serve(route):
path = route.request.url.removeprefix('http://table.test')
if path == '/':
route.fulfill(status=200, content_type='text/html; charset=utf-8', body='<!doctype html><html lang="zh-CN"><body><div id="notice" hidden></div></body></html>')
elif path in payload['sources']:
route.fulfill(status=200, content_type='text/javascript; charset=utf-8', body=payload['sources'][path])
else:
unexpected.append(route.request.url)
route.abort()
page.route('**/*', serve)
page.on('pageerror', lambda error: errors.append(str(error)))
try:
page.goto('http://table.test/')
page.evaluate(payload['bootstrap'])
page.evaluate(source)
assert not unexpected, 'Unexpected request: ' + str(unexpected)
assert not errors, 'Browser errors: ' + str(errors)
results[name] = {'ok': True}
except Exception as error:
results[name] = {'ok': False, 'error': str(error)}
finally:
page.close()
browser.close()
print(json.dumps(results, ensure_ascii=True))
`;
const run = spawnSync(process.env.PYTHON || 'python', ['-c', pythonHarness], {
input: JSON.stringify({sources, bootstrap: `(${bootstrap.toString()})`, cases: Object.fromEntries(
Object.entries(cases).map(([name, callback]) => [name, `(${callback.toString()})`]))}),
encoding: 'utf8', windowsHide: true, timeout: 60_000, maxBuffer: 2 * 1024 * 1024,
});
let results;
test('offline Chromium harness completes without external requests', () => {
assert.ifError(run.error);
assert.equal(run.status, 0, run.stderr);
results = JSON.parse(run.stdout.trim());
});
for (const name of Object.keys(cases)) {
test(name, () => {
assert.ok(results, 'Browser harness did not complete');
assert.deepEqual(results[name], {ok: true}, results[name]?.error);
});
}
+26
View File
@@ -0,0 +1,26 @@
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { fileURLToPath } from 'node:url';
const backend = 'http://127.0.0.1:8765';
const proxy = () => ({
target: backend,
// Keep Host and Origin paired; never rewrite an untrusted browser Origin.
changeOrigin: false,
});
export default defineConfig({
base: './',
plugins: [vue()],
build: {
outDir: '../ranch_web/static/console',
emptyOutDir: true,
sourcemap: false,
},
server: {
fs: {
allow: [fileURLToPath(new URL('.', import.meta.url)), fileURLToPath(new URL('../ranch_web/static', import.meta.url))],
},
proxy: { '/api': proxy(), '/login': proxy(), '/static': proxy() },
},
});