revert: restore the original pre-redesign web console

Revert 688aad3, 39ac03a, c84dc36, and ff6a828 in reverse chronological order. Restore the exact tracked tree from 99aff42 while preserving history.

Validation: 29 authentication and base-path tests passed offline. All 23 prior UI browser tests ran in system Edge: 22 passed initially; the fake-login test passed on an unchanged isolated retry. Live game HTTP was blocked throughout browser validation.
This commit is contained in:
AttilaNet
2026-11-11 10:08:02 +08:00
parent 688aad37c1
commit e26d37e9c5
46 changed files with 748 additions and 4554 deletions
-4
View File
@@ -5,10 +5,6 @@
!ranch_assistant/** !ranch_assistant/**
!ranch_web/ !ranch_web/
!ranch_web/** !ranch_web/**
!frontend/
!frontend/**
**/node_modules/
**/.vite/
**/__pycache__/ **/__pycache__/
**/*.pyc **/*.pyc
**/*.pyo **/*.pyo
-5
View File
@@ -3,11 +3,6 @@
*.as text eol=lf *.as text eol=lf
*.java text eol=lf *.java text eol=lf
*.json text eol=lf *.json text eol=lf
*.html text eol=lf
*.css text eol=lf
*.js text eol=lf
*.mjs text eol=lf
*.vue text eol=lf
*.md text eol=lf *.md text eol=lf
*.csv text eol=lf *.csv text eol=lf
*.sh text eol=lf *.sh text eol=lf
-10
View File
@@ -6,7 +6,6 @@ on:
pull_request: pull_request:
paths: paths:
- ranch_web/** - ranch_web/**
- frontend/**
- ranch_assistant/** - ranch_assistant/**
- deploy/web/** - deploy/web/**
- Dockerfile - Dockerfile
@@ -34,15 +33,6 @@ jobs:
- uses: actions/setup-python@v5 - uses: actions/setup-python@v5
with: with:
python-version: "3.12" python-version: "3.12"
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
cache-dependency-path: frontend/package-lock.json
- name: Build Vue console
run: |
npm --prefix frontend ci --no-audit --no-fund
npm --prefix frontend run build
- name: Validate source version and publish tag - name: Validate source version and publish tag
id: version id: version
env: env:
-3
View File
@@ -49,9 +49,6 @@ logs/
*.pyo *.pyo
**/__pycache__/ **/__pycache__/
.venv-web/ .venv-web/
frontend/node_modules/
frontend/.vite/
frontend/.cache/
.impeccable/ .impeccable/
.image.env .image.env
/updater-control/ /updater-control/
-11
View File
@@ -1,12 +1,3 @@
ARG NODE_IMAGE=node:22.23.3-bookworm-slim
FROM ${NODE_IMAGE} AS web-build
WORKDIR /build
COPY frontend/package*.json ./frontend/
RUN npm --prefix frontend ci --no-audit --no-fund
COPY frontend/ ./frontend/
COPY ranch_web/static/ ./ranch_web/static/
RUN npm --prefix frontend run build
FROM python:3.12-slim-bookworm FROM python:3.12-slim-bookworm
ARG WEB_VERSION=2.0.0.dev1 ARG WEB_VERSION=2.0.0.dev1
@@ -34,8 +25,6 @@ RUN python -m pip install --no-cache-dir -r /tmp/web-requirements.txt \
COPY ranch_assistant/ /app/ranch_assistant/ COPY ranch_assistant/ /app/ranch_assistant/
COPY ranch_web/ /app/ranch_web/ COPY ranch_web/ /app/ranch_web/
COPY --from=web-build /build/ranch_web/static/console/ /app/ranch_web/static/console/
COPY --from=web-build /build/ranch_web/static/index.html /app/ranch_web/static/index.html
USER 10001:10001 USER 10001:10001
EXPOSE 8765 EXPOSE 8765
+3 -3
View File
@@ -16,16 +16,16 @@
## Web 2 开发运行与部署入口 ## Web 2 开发运行与部署入口
`develop/v2.0.0` 提供 **2.0.0.dev1** 开发工作台,提供重新设计的管理后台:分组侧栏、顶部账号选择、面包屑、全部账号总览和账号工作区;原15项功能重新分组,复用现有 Engine 和策略。尚未合并 main 或发布正式版,桌面入口继续可用。 `develop/v2.0.0` 提供 **2.0.0.dev1** 开发工作台,保留原15页导航、多账号页签、顶部玩家数值与统一启停、可调整日志区,复用现有 Engine 和策略。尚未合并 main 或发布正式版,桌面入口继续可用。
- Windows:Python 3.12+,安装 `ranch_web/requirements.txt` 后运行 `Start_Ranch_Web.cmd`,访问 `http://127.0.0.1:8765`。 - Windows:Python 3.12+,安装 `ranch_web/requirements.txt` 后运行 `Start_Ranch_Web.cmd`,访问 `http://127.0.0.1:8765`。
- Web 使用 Vue 3 + Vite 与 FastAPI;普通运行使用随附静态产物,无需 Node/npm 或 PySide6。前端开发执行 `npm --prefix frontend ci` 和 `npm --prefix frontend run build`;数据独立保存在 `local_state/ranch_web`。 - Web 使用原生 HTML/CSS/ES 模块与 FastAPI,无需 Node/npm 或 PySide6;数据独立保存在 `local_state/ranch_web`。
- Linux:提供单服务 Docker、`/data` 持久化及宿主机受控更新;只接官方稳定 `v2.x.y`,默认只通知,未配置执行器时仅检查。 - Linux:提供单服务 Docker、`/data` 持久化及宿主机受控更新;只接官方稳定 `v2.x.y`,默认只通知,未配置执行器时仅检查。
- 配置管理密码后,先进入独立 `/login` 页面,登录后才能打开工作台;退出管理登录或会话失效后返回登录页。 - 配置管理密码后,先进入独立 `/login` 页面,登录后才能打开工作台;退出管理登录或会话失效后返回登录页。
本地虚拟环境、离线演示与环境配置见 [Web 开发运行说明](ranch_web/README.md);Linux 单服务 Docker、`/data` 持久化、GHCR 镜像与宿主机备份/回滚更新见 [Web 部署更新入口](deploy/web/README.md)。更新仅接受官方稳定 `v2.x.y`,没有 Web 2 正式版时不会安装旧桌面版;Windows 未配置执行器时仅检查更新。Linux Docker 部署烟测已通过,真实游戏 API 与生产升级/回滚仍待验收。 本地虚拟环境、离线演示与环境配置见 [Web 开发运行说明](ranch_web/README.md);Linux 单服务 Docker、`/data` 持久化、GHCR 镜像与宿主机备份/回滚更新见 [Web 部署更新入口](deploy/web/README.md)。更新仅接受官方稳定 `v2.x.y`,没有 Web 2 正式版时不会安装旧桌面版;Windows 未配置执行器时仅检查更新。Linux Docker 部署烟测已通过,真实游戏 API 与生产升级/回滚仍待验收。
完整离线后端验证 **201项:200通过、1跳过(Windows符号链接权限),0失败/错误**;浏览器 **30项全部通过,JS/CSP错误为0**。完整测试命令见 [Web 验证说明](ranch_web/README.md#离线验证)。管理登录与子路径部署已验证;新版管理后台的验证记录见 [Web 验证说明](ranch_web/README.md#离线验证)。真实游戏 API 不属于前端离线验收范围。 完整离线后端验证 **193项:192通过、1跳过(Windows符号链接权限),0失败/错误**;浏览器 **21项全部通过,JS/CSP错误为0**。完整测试命令见 [Web 验证说明](ranch_web/README.md#离线验证)。独立管理登录页补丁的线上重新部署验收待完成,真实游戏 API 尚未验收。
## 当前功能 ## 当前功能
+1 -1
View File
@@ -4,7 +4,7 @@
## 容器与持久化 ## 容器与持久化
需要 Linux、Docker Engine、带 `up --wait --wait-timeout` 和 `pull --policy` 的 Docker Compose v2。宿主机更新器另需 Python 3.12+(仅标准库)。镜像采用 Node 22 构建 Vue 前端,运行阶段仅使用 Python 3.12,无 PySide6、Node 或 npm,单服务、单 Uvicorn worker;账号由应用内独立线程并行。构建需要完整 `frontend/` 和 `ranch_web/static/` 源码;账号目录不参与构建。 需要 Linux、Docker Engine、带 `up --wait --wait-timeout` 和 `pull --policy` 的 Docker Compose v2。宿主机更新器另需 Python 3.12+(仅标准库)。镜像使用 Python 3.12,无 PySide6、Node 或 npm,单服务、单 Uvicorn worker;账号由应用内独立线程并行。
将审核后的项目源码放在 `/opt/ranch-web`,项目、Python 源码、Compose 及部署配置由 root 持有,且禁止其他用户写入。以下路径适用于全新部署,持久化账号目录使用单独的 UID/GID 10001: 将审核后的项目源码放在 `/opt/ranch-web`,项目、Python 源码、Compose 及部署配置由 root 持有,且禁止其他用户写入。以下路径适用于全新部署,持久化账号目录使用单独的 UID/GID 10001:
-11
View File
@@ -51,14 +51,3 @@ Main 确认最终非浏览器后端 **185项:184通过、1跳过(Windows符
本 owner 对此前五项问题复核完成:编码后与 requests 发送前的停止检查有效;修改配置不误关运行开关;120个筛选后视图缓存32项、已完成任务索引归零;主线/孵蛋标签 key 完整;12个并发错误登录得到10个401和2个429。六项定向回归与原始复现均通过,未扩大审查或重跑整套测试。 本 owner 对此前五项问题复核完成:编码后与 requests 发送前的停止检查有效;修改配置不误关运行开关;120个筛选后视图缓存32项、已完成任务索引归零;主线/孵蛋标签 key 完整;12个并发错误登录得到10个401和2个429。六项定向回归与原始复现均通过,未扩大审查或重跑整套测试。
完整后端及浏览器命令见 [Web 验证说明](../../ranch_web/README.md#离线验证)。未进行真实游戏 API、Linux Docker、systemd 或生产更新器实机验收,未发布镜像或触发部署。生产代码保持冻结,仅更新最终文档,交 Main 提交。 完整后端及浏览器命令见 [Web 验证说明](../../ranch_web/README.md#离线验证)。未进行真实游戏 API、Linux Docker、systemd 或生产更新器实机验收,未发布镜像或触发部署。生产代码保持冻结,仅更新最终文档,交 Main 提交。
## 2026-11-11:Vue 专用控制台改版
界面改为牧羊人之心专用的账号总览、账号管理、分组侧栏、面包屑和账号工作区,取消多游戏入口。业务Engine与持久化格式不变。Node22在独立Docker构建阶段生成Vue静态资源,最终运行容器仍是Python。
离线验收:后端201项(200通过、1项Windows跳过),浏览器30项全部通过,前端控制器/表格24项通过,Vue类型检查及生产构建通过。原23项浏览器功能覆盖保留,新增7项管理后台回归;详细命令见Web README。当前仍是2.0.0.dev1,不创建稳定tag或合并main。
既有 Linux 环境已使用 `39ac03a` 完成 Node/Vue 多阶段构建、数据备份、Compose 切换及健康检查。最终容器 UID10001,不含 Node 或 PySide6;账号目录和管理密码保留。Docker Hub 通用标签查询超时发生在旧服务仍在线时,使用已缓存的固定 Node22.23.3 构建镜像完成后续部署。
既有 HTTPS 子路径入口的实际浏览器验收通过:独立管理登录、15项业务入口、无游戏切换器、同源接口200、Secure/HttpOnly前缀Cookie、退出回登录页、零JavaScript错误;直接公网IP请求返回400。仅验证管理认证与只读页面,不执行真实游戏动作。部署重启后策略仍按既有规则保持停止。
-32
View File
@@ -1,32 +0,0 @@
<!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
@@ -1,14 +0,0 @@
{
"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
@@ -1,22 +0,0 @@
{
"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
@@ -1,11 +0,0 @@
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
@@ -1,212 +0,0 @@
<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
@@ -1,35 +0,0 @@
<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
@@ -1,53 +0,0 @@
<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
@@ -1,46 +0,0 @@
<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
@@ -1,904 +0,0 @@
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
@@ -1,38 +0,0 @@
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
@@ -1,15 +0,0 @@
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
@@ -1,33 +0,0 @@
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
@@ -1,204 +0,0 @@
/* 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
@@ -1,119 +0,0 @@
/* 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
@@ -1,87 +0,0 @@
: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
@@ -1,329 +0,0 @@
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
@@ -1,320 +0,0 @@
// 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
@@ -1,26 +0,0 @@
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() },
},
});
+20 -38
View File
@@ -1,52 +1,34 @@
# BOT 控制台 UX 与设计规范 # Web 工作台设计
此方案替代 Web 2 早期桌面式菜单、账号页签与横向功能标签;版本继续为 2.0.0 开发版。依据 UI UX Pro Max 的 operations monitoring dashboard 建议,采用功能优先的管理后台,舍弃其营销首页、试用转化和装饰动画建议。 ## 方向与依据
## 信息架构 按明确需求采用 Impeccable 的 code-led Operate 路径。现有 `ranch_assistant/gui.py`、`accounts_gui.py` 及各功能 `*_gui.py` 是视觉与交互依据;不增加营销封面或装饰卡片,不改变十五页的顺序。
| 导航组 | 页面 | 范围 | 页面是一张紧凑的浅色操作台。顶层是菜单、账号页签和运行工具栏,中层是功能页与可横向滚动表格,底层是可调日志。功能名称、绿色开启与红色停止对应现有桌面。页签选中使用细蓝边和浅蓝背景,状态文字与颜色一起说明结果。
| --- | --- | --- |
| 工作空间 | 运行总览、账号管理 | 全部牧羊人之心账号 |
| 游戏资源 | 连接管理、培育室、背包、牧场、每日事务 | 当前账号 |
| 自动化策略 | 孵蛋、赠礼、委托、探险、主线、扫荡与挑战 | 当前账号 |
| 运行观测 | 执行计划、战斗记录、数据分析、运行日志 | 当前账号 |
| 资料与系统 | 收益资料、系统与配置 | 收益和策略属于当前账号;版本和更新属于平台 |
布局为左侧分组导航、顶部账号选择、面包屑及右侧内容。总览展示实际账号摘要、运行状态、异常和更新时间;不编造收益曲线、成功率或健康分数。没有账号时提供新增入口。 ## 基础规格
平台仅一个管理员,不加入用户组织、权限、租户或审批。控制台专用于牧羊人之心,不提供游戏切换或其他游戏的预留入口。 - 字体:系统 UI,Windows 优先 Microsoft YaHei UI/Segoe UI,其他系统采用可用系统中文字体;不从网络下载。
- 正文字号 13px,辅助文字 12px,页内标题 14px;表格紧凑、数字使用等宽数字。
- 空间基准 4px,控件高 26–28px,表格行约 28px。表头置顶,长掉落文本省略并保留 tooltip。
- 界面背景 `#f1f3f5`,内容白色,分隔 `#cbd1d8`,正文 `#202832`,次要文字 `#55616e`,强调 `#245d9b`。
- 运行开启 `#20743a`,停止 `#b3261e`,警告 `#805300`。键盘焦点有 2px 可见轮廓,状态不会只靠颜色传达。
- 菜单和上下文菜单使用独立浮层,确认使用原生 dialog,避免被滚动表格裁切。
## 多账号交互 ## 交互要求
- 顶部账号选择器明确当前操作范围,面包屑、角色资源、功能数据与日志始终属于同一账号。账号列表行操作显式绑定该行 ID。 各账号独立保存内存中的页签、筛选、选中行、视图缓存和待保存配置。轮询期间不重建正在编辑的控件,不覆盖焦点所在输入。输入经 debounce 自动保存,执行策略前先完成待保存内容;冲突或校验错误保留用户输入并给出可重试状态。
- URL 带账号与功能,支持页面刷新、前进后退,不带密码或 token。切换账号不停止其他账号,也不覆盖输入和筛选。
- 各账号配置独立自动保存,显示保存中、已保存、失败可重试。版本冲突保留用户改动,开启前先保存成功。
- 绿色“开启”与红色“停止”控制当前账号执行;各功能开关决定参与执行的策略。停止不等待保存或长任务结束。
- 策略导入导出注明账号范围;导入不自动开启执行。平台退出与游戏退出分开;移除、喂养和扩建说明具体后果并确认。
- 账号任务结束后不得抢回用户后来切换的页面或账号。普通导航和筛选只读取数据,不触发游戏写操作。
## 视觉与可访问性 表格提供排序、行选择、多选、原生 checkbox、number 与 select。普通浏览不改变 number 数值;只有输入获得焦点时滚轮才可作用。地图地区默认收起;筛选本身只请求 GET 视图。主线默认当前任务。表单由中文 schema、路径、类型与选项驱动,不以 JSON 文本框代替业务控件。
深色侧栏 #162235、浅色画布 #f4f6fa、白色内容面板;主色 #2563eb,正文 #17243b,辅助文字 #526079,边界 #dbe2ec。运行绿、等待琥珀、失败红均配文字。优先状态识别和操作效率,不使用装饰性大卡片或营销区。 长任务保留任务状态并轮询;状态栏、账号切换和日志仍可使用。停止按钮提交即时停止操作,不等待前一任务完成。费用、消耗魔物和移除账号使用明确的二次确认。扩建先取服务端报价,确认后回传报价与批准字段。
系统中文字体,无外部字体/CDN;正文14–16px,辅助文字不小于12px,数字 tabular-nums。侧栏约224px,顶部约64px,内容留白20–24px,控件34–40px。图标使用一致SVG,图标按钮有名称和可见焦点。 日志只渲染文本,保留自动滚动开关;用户向上查看时不会被强行拉到底部。分隔条支持拖拽、方向键、Home/End。隐藏日志后内容区利用剩余高度。
页面按筛选、规则分组、数据、结果分区。长说明折叠,表格长值省略但可查看完整内容;宽表独立横向滚动,不撑宽网页。小屏使用可关闭侧栏抽屉,账号和启停仍可操作。支持键盘、焦点恢复、Escape与 reduced-motion。没有实时来源时只写最近更新时间。 ## 响应式与可访问性
## 性能与技术 1280/1600 宽使用相同层级。工具栏可换行,导航和宽表格独立横向滚动;小屏保留原字段而不压缩成卡片。页签与菜单支持键盘,原生表单有 label,错误和状态使用可访问 live region。遵从减少动效偏好,界面无装饰动画。
Vue 3 + Vite负责新壳层、状态与构建;现有Python Engine、协议、业务动作与表单数据契约复用。框架更换本身不是性能提升证明。 ## 技术默认假设
- 账号摘要采用浅层响应式状态,大数据与DOM控件不做深层代理。 静态 ES modules 由 FastAPI 同源提供;路径为 `/static/`,入口 `/`。安全逻辑以服务端认证、Origin 校验、公开 DTO 与脱敏日志为边界,前端使用 `textContent`/DOM API,不执行来自游戏的 HTML。浏览器不保存密码、token、key、会话原文。截图、E2E 只使用离线演示或显式 fixture;无样本图表不产生虚构柱形。
- 只刷新并绘制当前可见账号和页面;其他页面保留查询和选中状态,展示时再同步。
- 长表默认每页50条,可调整页容量;排序针对完整结果,跨页选中规则明确。
- 地区默认折叠,展开才创建行;日志按需获取、增量显示并限制长度。
- 视图、状态、日志请求防重叠;浏览器隐藏时减少查询,服务端策略继续运行。
- 定时刷新不覆盖正在编辑的值或焦点;数字框仅获得焦点后响应滚轮。
- 静态产物可直接由Python服务提供;Node仅用于开发与镜像构建。依赖锁定,生产不依赖CDN。
## 验收
保留既有十五项业务能力,以新导航重新组织。临时离线演示和fixture覆盖全页面、账号隔离、自动保存冲突、启停、确认动作、长表分页、日志、更新、管理认证及子路径部署;不使用真实游戏账号进行设计测试。
检查1440px、1280px和手机宽度的布局、键盘与可读性。长表性能以DOM数量和实际交互测试记录为准,不承诺采用Vue后固定倍数的提升。管理登录仍是独立页面,未认证时不提供工作台。
+7 -9
View File
@@ -2,19 +2,17 @@
## 产品约束 ## 产品约束
把现有辅助能力组织为单管理员、多账号的牧羊人之心 Web 控制台。界面依照 Web 场景重新设计,不以桌面布局或页面顺序为约束;业务名称、保护条件与操作语义继续复用。版本为 `2.0.0.dev1`,游戏数据版本 `1.9.68`;本次不合并 main、不发布正式版本。专用于牧羊人之心,不提供多游戏入口,不增加多用户或权限管理。 把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。版本为 `2.0.0.dev1`,游戏数据版本 `1.9.68`;本次不合并 main、不发布正式版本。
使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。 使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。
## 固定工作台结构 ## 固定工作台结构
1. 左侧分组导航,顶部账号选择器、面包屑,右侧内容区。 1. 顶部原生风格菜单:账号、策略、配置、帮助。
2. 全部账号运行总览和账号管理;各账号行可独立开启、停止和进入工作区。 2. 多账号页签,支持新增、切换、移除。
3. 当前账号昵称、等级、经验、金币、氪金、体力;随机刷新间隔、绿色开启/红色停止、刷新/预览、自动保存状态。 3. 当前角色昵称、等级、经验、金币、氪金、体力;随机刷新间隔、绿色开启/红色停止、刷新/预览、调试、日志显隐。
4. 原有十五项业务按游戏资源、自动化策略、运行观测、资料与系统分组;各账号保留独立查询和规则。 4. 同桌面顺序的功能页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。
5. 独立日志页与可收起的当前账号日志面板,提供级别筛选、搜索、跟随和脱敏详情;系统页提供配置导入导出、版本更新和连接管理。 5. 可拖动高度、可隐藏的底部日志和常驻状态栏。
视觉、路由、范围切换、性能与验收要求见 [UX 设计规范](DESIGN.md)。
## 核心操作 ## 核心操作
@@ -32,4 +30,4 @@
## 技术默认假设 ## 技术默认假设
Vue 3 + Vite 构建前端,FastAPI 同源提供静态资源和 `/api`,不加载 CDN 或网络字体。以共享 WebManager/API/视图 DTO 契约为准,前端不构造游戏在线成功数据。服务端拥有业务规则,前端拥有展示与交互;使用表格分页、分组懒加载和按需刷新减少浏览器负担。桌面使用侧栏,小屏使用抽屉,宽表格独立滚动。凭据不进入浏览器持久存储。 原生 HTML/CSS/ES modules,无 React、npm 构建、CDN 或网络字体。FastAPI 同源提供静态资源和 `/api`。以共享 WebManager/API/视图 DTO 契约为准,前端不构造游戏在线成功数据。桌面/服务端拥有业务规则,前端拥有展示与交互。1280 和 1600 宽桌面均可操作,小屏允许横向滚动。非业务的布局偏好可以存本机,凭据不可持久化。
+6 -30
View File
@@ -2,30 +2,16 @@
Web 包版本 **2.0.0.dev1**,游戏资料基线 **1.9.68**,开发分支 `develop/v2.0.0`。当前正式桌面版仍为 1.2.0;Web 未合并 main、未发布正式版本。桌面入口 `python -m ranch_assistant` 保留,Web 使用独立依赖与数据根。 Web 包版本 **2.0.0.dev1**,游戏资料基线 **1.9.68**,开发分支 `develop/v2.0.0`。当前正式桌面版仍为 1.2.0;Web 未合并 main、未发布正式版本。桌面入口 `python -m ranch_assistant` 保留,Web 使用独立依赖与数据根。
Web 采用 Vue 3 + Vite 前端和 FastAPI / Uvicorn 后端,运行时不安装 PySide6。界面重新组织为侧边导航、顶部账号范围、面包屑和内容区;总览与账号管理面向全部账号,业务与策略面向当前账号。现有策略核心与业务校验继续复用,各账号独立运行,同一账号操作串行。设计与交互规范见 [UX 方案](DESIGN.md)。 Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。
## 迁移清单 ## 迁移清单
- [x] 原15页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。 - [x] 原15页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。
- [x] 用分组侧栏和账号选择器替代桌面式横向标签;增加总览、账号管理与系统入口。当前账号资源和启停明确可见,规则自动保存,配置与统计按账号/角色隔离。 - [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,重启、恢复会话及导入策略后保持停止。
- [x] Windows Python 启动与离线演示;仓库包含已构建前端,普通运行无需 Node。修改前端需 Node 22 和 npm 构建;生产镜像运行阶段不含 Node。 - [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。
- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;已完成 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测。 - [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;已完成 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测。
- [x] 开发版本为 `2.0.0.dev1`,保留桌面兼容,不等同正式发布或真实游戏 API 验收。 - [x] 开发版本为 `2.0.0.dev1`,保留桌面兼容,不等同正式发布或真实游戏 API 验收。
## 前端开发与构建
正常运行可直接使用 Python 启动脚本。修改界面后,在项目根目录执行:
```console
npm --prefix frontend ci
npm --prefix frontend run build
python -B -m ranch_web --no-browser
```
源码位于 `frontend/`,构建输出至 `ranch_web/static/console/` 并更新工作台 HTML 入口。Docker 使用独立 Node 构建阶段,最终容器仅包含 Python 与同源静态文件。静态路径支持 `RANCH_WEB_BASE_PATH`,不使用外部 CDN。
长表默认分页,排序针对当前筛选后的完整数据;只渲染可见页面,后台浏览器减少查询。配置与状态按账号隔离,导航不自动开启策略。单账号“开启/停止”与各策略启用开关分别表达执行状态和参与运行的规则。
## Windows 本地开发 ## Windows 本地开发
使用 Python 3.12+,在项目根目录执行(本机已安装 3.13): 使用 Python 3.12+,在项目根目录执行(本机已安装 3.13):
@@ -83,13 +69,13 @@ Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、
## 离线验证 ## 离线验证
独立管理登录页调整后的完整非浏览器后端验证为 **201项:200通过、1跳过(Windows符号链接权限),0失败/错误,用时26.994秒**。以下命令显式列出全部10个后端模块,避免发现并混入浏览器测试: 独立管理登录页调整后的完整非浏览器后端验证为 **193项:192通过、1跳过(Windows符号链接权限),0失败/错误,用时26.994秒**。以下命令显式列出全部10个后端模块,避免发现并混入浏览器测试:
```console ```console
python -B -m unittest ranch_web.tests.test_base_path ranch_web.tests.test_api ranch_web.tests.test_auth ranch_web.tests.test_scheduler ranch_web.tests.test_service ranch_web.tests.test_store ranch_web.tests.test_updates ranch_web.tests.test_web_integration ranch_web.tests.test_web_policies ranch_web.tests.test_web_updater ranch_web.tests.test_web_views_actions -v python -B -m unittest ranch_web.tests.test_api ranch_web.tests.test_auth ranch_web.tests.test_scheduler ranch_web.tests.test_service ranch_web.tests.test_store ranch_web.tests.test_updates ranch_web.tests.test_web_integration ranch_web.tests.test_web_policies ranch_web.tests.test_web_updater ranch_web.tests.test_web_views_actions -v
``` ```
独立管理登录页调整后的浏览器验证为 **30项全部通过(13项原有工作台、7项密码保护登录、1项本机免密),JS/CSP错误为0**,覆盖独立登录页、工作台访问门禁、退出、会话失效和原有功能。浏览器测试需要 Python Playwright 和可用的 Edge,属于验证依赖: 独立管理登录页调整后的浏览器验证为 **21项全部通过(13项原有工作台、7项密码保护登录、1项本机免密),JS/CSP错误为0**,覆盖独立登录页、工作台访问门禁、退出、会话失效和原有功能。浏览器测试需要 Python Playwright 和可用的 Edge,属于验证依赖:
```console ```console
python -B -m unittest ranch_web.tests.browser.test_workbench_browser ranch_web.tests.browser.test_admin_login_browser -v python -B -m unittest ranch_web.tests.browser.test_workbench_browser ranch_web.tests.browser.test_admin_login_browser -v
@@ -102,13 +88,3 @@ python -B -m unittest ranch_web.tests.browser.test_base_path_browser -v
``` ```
上述离线验证使用临时目录、fake transport / GitHub / Docker 或内置离线演示,不读取私有账户,不访问真实游戏 API。停止取消、配置并发保存、视图索引清理、子页字段保留和并发认证限流的已报问题均已修复并复核。Linux Docker 部署烟测见上文;离线测试及部署烟测均不等同于真实游戏 API 或生产升级/回滚验收。 上述离线验证使用临时目录、fake transport / GitHub / Docker 或内置离线演示,不读取私有账户,不访问真实游戏 API。停止取消、配置并发保存、视图索引清理、子页字段保留和并发认证限流的已报问题均已修复并复核。Linux Docker 部署烟测见上文;离线测试及部署烟测均不等同于真实游戏 API 或生产升级/回滚验收。
## Vue 控制台改版验证(2026-11-11)
- 后端201项:200通过、1项Windows符号链接权限跳过;浏览器30项全部通过,保留原23项并新增路由、账号范围、分页与响应式回归。
- `npm --prefix frontend run check` 与 `npm --prefix frontend run build` 通过;`npm --prefix frontend test` 的24项控制器和表格测试通过。
- 覆盖账号切换、浏览器前进后退/刷新、自动保存与冲突、停止取消尚未发出的启动请求、独立管理登录、登录过期、前缀保留/剥离代理和脱敏日志详情。
- 本机相同1000行离线表格:实际渲染1000行降为50行,输入控件3000个降为150个。此记录衡量DOM负担,不代表真实账号全链路耗时。
- 主要功能页1440px与手机390px截图检查通过,没有整个页面横向溢出。宽表在自身容器内滚动;监控与业务规则不因界面刷新而改变。
测试使用临时演示与fixture,不使用真实游戏账号。上述命令需要Node22;表格浏览器测试另需Python Playwright和系统Chromium(可用 `RANCH_WEB_BROWSER` 指定路径)。
+530
View File
@@ -0,0 +1,530 @@
import {api, request} from './api.js';
import {apiPath, webPath} from './paths.js';
import {el, $, $$, clone, getPath, setPath, pathKey, textValue, number, chinaTime, download, csvBlob, optionsList, detailsList, tabKeys} from './dom.js';
import {PageView, PAGES} from './pages.js';
import {notice, dialog, confirm, filePicker, fileBase64} from './ui.js';
const state = {accounts:new Map(),active:null,schema:null,meta:null,ready:false,polling:false,seq:0,redirecting:false};
const current = () => state.accounts.get(state.active);
const currentPage = () => { const account=current(); return account?.pages.get(account.page); };
const terminal = new Set(['succeeded','failed','cancelled']);
const jobLabels = {queued:'排队中',running:'执行中',succeeded:'已完成',failed:'失败',cancelled:'已取消'};
const operationLabels = {login:'登录',enter_server:'进入区服',restore_session:'恢复会话',refresh:'刷新 / 预览',start:'开启策略',stop:'停止策略',set_config:'保存配置',import_config:'导入策略',import_yields:'导入收益',claim_daily:'领取每日奖励',quote_expansion:'读取扩建费用',expand:'扩建',sell:'派遣',feed:'喂养',lock:'锁定',unlock:'解锁'};
function makeAccount(summary) {
return {id:summary.id,summary,config:null,revision:null,edits:new Map(),pages:new Map(),page:'login',jobs:new Map(),savePromise:null,saveError:null,
logs:{entries:[],next:0,debug:false,loading:false},loadingConfig:false};
}
function setStatus(message) { $('#status-text').textContent=message; $('#status-text').title=message; }
function error(error) { if(state.redirecting)return;notice(error.message || String(error),true); setStatus(error.message || String(error)); }
function renderAccountTabs() {
const root=$('#account-tabs');
for (const child of [...root.children]) if (!state.accounts.has(child.dataset.account)) child.remove();
state.accounts.forEach(account=>{
let button=[...root.children].find(child=>child.dataset.account===account.id);
if (!button) {
button=el('button',{type:'button',class:'account-tab',role:'tab','data-account':account.id,onClick:()=>selectAccount(account.id)},el('span',{class:'account-dot'}),el('span',{class:'account-label'}));
root.append(button);
}
const summary=account.summary, selected=state.active===account.id;
$('.account-label',button).textContent=summary.label || summary.player?.name || '账号';
$('.account-dot',button).className=`account-dot${summary.error?' error':summary.running?' running':''}`;
button.setAttribute('aria-selected',String(selected));button.tabIndex=selected?0:-1;
button.title=`${summary.label || '账号'}${summary.demo?' · 离线演示':''}${summary.running?' · 策略运行中':''}${summary.error?' · '+summary.error:''}`;
});
}
function syncSaveStatus(account=current()) {
if (!account || account.id!==state.active) return;
const node=$('#save-status');
const message=account.saveError?'保存失败 · 点击重试':account.savePromise?'保存中…':account.edits.size?'修改待保存…':account.config?'策略已自动保存':'配置载入中…';
node.textContent=message;node.title=account.saveError || message;node.className=account.saveError?'failed':account.edits.size||account.savePromise?'pending':'';
}
function renderSummary() {
const account=current(),summary=account?.summary,player=summary?.player || {};
const connected=summary?.connected,demo=summary?.demo;
$('#connection').textContent=demo?'离线演示':connected?'已登录':'未登录';
$('#connection').className=`connection${demo?' demo':connected?' online':''}`;
$('#player-name').textContent=player.name || '—';$('#player-name').title=player.name || '';
for (const [id,key] of [['player-level','level'],['player-money','money'],['player-ke','ke'],['player-ti','ti']]) $('#'+id).textContent=number(player[key]);
$('#player-exp').textContent=player.exp==null?'—':`${number(player.exp)} / ${number(player.next_exp)}`;
$('#experience-progress').max=Math.max(1,Number(player.next_exp)||1);$('#experience-progress').value=Number(player.exp)||0;
const run=$('#strategy-toggle');run.textContent=summary?.running?'停止':'开启';run.classList.toggle('running',Boolean(summary?.running));run.disabled=!account || !account.config || !connected && !demo;
run.setAttribute('aria-pressed',String(Boolean(summary?.running)));
run.title=summary?.running?'停止自动执行已勾选功能;取消尚未发送的请求':'开启后自动执行各页面已勾选功能';
if (account?.config && document.activeElement!==$('#refresh-interval')) $('#refresh-interval').value=String(account.config.interval);
$('#refresh-interval').disabled=!account?.config;
$('#refresh').disabled=!account;
const task=account?[...account.jobs.values()].at(-1)?.job:null;
$('#job-status').textContent=task?`${operationLabels[task.operation] || task.operation} · ${jobLabels[task.status]}`:summary?.busy?'后台任务执行中':'';
$('#data-summary').textContent=summary?.error || (demo?'当前为离线演示,不连接游戏服务器。':connected?'角色状态自动刷新;配置功能后开启策略。':'请在登录页输入账号密码,或恢复已保存会话。');
syncSaveStatus(account);
}
async function refreshConfig(account) {
if (account.loadingConfig) return;
account.loadingConfig=true;
try {
const response=await api.config(account.id);
account.config=clone(response.config);account.revision=response.revision;
account.edits.forEach(edit=>applyEdit(account.config,edit));
account.pages.forEach(page=>page.data&&page.render(page.data));
if (account.id===state.active) {renderSummary();applyLogLayout(account);}
} finally {account.loadingConfig=false;}
}
function applyEdit(config,edit) {
if(!edit.ifMissing || getPath(config,edit.path)===undefined)setPath(config,edit.path,edit.value);
}
function writeEdit(account,path,value,{ifMissing=false}={}) {
if(ifMissing && (getPath(account.config,path)!==undefined || account.edits.get(pathKey(path))?.ifMissing===false))return;
setPath(account.config,path,value);
account.edits.set(pathKey(path),{path:[...path],value:clone(value),seq:++state.seq,ifMissing});
}
function editConfig(account,path,value,field={},row) {
if (!account.config) throw new Error('配置尚未载入,请稍后再试。');
if (row?.rule_path && row.rule_defaults)Object.entries(row.rule_defaults).forEach(([key,value])=>writeEdit(account,[...row.rule_path,key],value,{ifMissing:true}));
writeEdit(account,path,value);
// Preserve the desktop's linked switches when enabling an individual rule.
if (path[0]==='policy') {
const section=path[1];
if (section==='egg_rules') {
const rule=getPath(account.config,path.slice(0,3),{});
if (rule.enabled && ['enabled','action'].includes(path[3])) {
if (rule.action==='sell') writeEdit(account,['policy','dispatch'],true);
else {writeEdit(account,['policy','collect'],true);if(rule.action==='feed')writeEdit(account,['policy','feed'],true);}
}
}
if (section==='gift_items'&&value===true) writeEdit(account,['policy','gift_enabled'],true);
if (section==='feed_targets'&&value!==undefined) {writeEdit(account,['policy','feed'],true);writeEdit(account,['policy','collect'],true);}
if (section==='gift_targets'&&value!==undefined) writeEdit(account,['policy','gift_enabled'],true);
}
account.saveError=null;clearTimeout(account.saveTimer);
account.saveTimer=setTimeout(()=>flushConfig(account).catch(error),500);
syncSaveStatus(account);
// Update other controls, while every control protects its own focused input.
account.pages.forEach(page=>page.data&&page.render(page.data));
if (path[0]==='log_visible'||path[0]==='log_sizes') applyLogLayout(account);
}
async function flushConfig(account=current()) {
if (!account) return;
clearTimeout(account.saveTimer);
if (account.savePromise) {await account.savePromise;if(account.edits.size)return flushConfig(account);return;}
if (!account.edits.size) return;
const invalid=account.pages.get(account.page)?.root.querySelector(':invalid');
if (invalid) {invalid.reportValidity();throw new Error('请先补全当前输入,再保存或开启策略。');}
const sent=[...account.edits.values()].map(clone),config=clone(account.config);
account.saveError=null;
account.savePromise=(async()=>{
try {
let response=await api.save(account.id,config,account.revision);
if (response.pending && response.job_id) {
const result=await trackJob(account,response.job || {id:response.job_id,status:'queued',operation:'set_config'});
response=result?.config?result:await api.config(account.id);
}
if (!response?.config) response=await api.config(account.id);
sent.forEach(edit=>{if(account.edits.get(pathKey(edit.path))?.seq===edit.seq)account.edits.delete(pathKey(edit.path));});
account.config=clone(response.config);account.revision=response.revision;
account.edits.forEach(edit=>applyEdit(account.config,edit));
account.saveError=null;
} catch(failure) {
if(failure.status===409){
const latest=await api.config(account.id);account.config=clone(latest.config);account.revision=latest.revision;
account.edits.forEach(edit=>applyEdit(account.config,edit));
account.saveError='配置已被另一浏览器更新。已保留你修改的字段,请点击保存状态重试。';
} else account.saveError=failure.message;
throw new Error(account.saveError);
} finally {account.savePromise=null;syncSaveStatus(account);renderSummary();}
})();
syncSaveStatus(account);
await account.savePromise;
if(account.edits.size)return flushConfig(account);
account.pages.forEach(page=>page.data&&page.render(page.data));
const page=account.pages.get(account.page);if(page)loadPage(page,true);
}
function trackJob(account,job) {
if (!job?.id || !job.status) return Promise.resolve(job);
if (terminal.has(job.status)) return job.status==='succeeded'?Promise.resolve(job.result):Promise.reject(new Error(job.error || jobLabels[job.status]));
if(account.jobs.has(job.id))return account.jobs.get(job.id).promise;
let resolve,reject;
const promise=new Promise((yes,no)=>{resolve=yes;reject=no;});
const record={job,promise,resolve,reject,polling:false};account.jobs.set(job.id,record);
pollJob(account,record);renderSummary();
return promise;
}
async function pollJob(account,record) {
if(record.polling)return;record.polling=true;
try {
const job=await api.job(account.id,record.job.id);record.job=job;
if(terminal.has(job.status)){
account.jobs.delete(job.id);
if(job.status==='succeeded')record.resolve(job.result);
else record.reject(new Error(job.error || '任务已取消'));
}
}catch(failure){if([400,401,403,404].includes(failure.status)){account.jobs.delete(record.job.id);record.reject(failure);}}
finally{record.polling=false;renderSummary();}
}
async function perform(account,operation,payload={},options={}) {
if(!account)throw new Error('请先新增或选择一个账号。');
if(operation==='start'){
const invalid=account.pages.get(account.page)?.root.querySelector(':invalid');
if(invalid){invalid.reportValidity();throw new Error('请先完成当前输入,再开启策略。');}
}
if(operation!=='stop')await flushConfig(account);
const job=await api.action(account.id,operation,payload);
setStatus(`${operationLabels[operation] || '操作'}:${jobLabels[job.status] || '已提交'}`);
const result=await trackJob(account,job);
if(!state.accounts.has(account.id))return result;
if(result?.config){account.config=clone(result.config);account.revision=result.revision;}
if(['enter_server','restore_session','logout','forget_login','import_config','import_yields'].includes(operation))await refreshConfig(account);
account.summary=await api.status(account.id);
renderAccountTabs();renderSummary();
const page=options.page || account.pages.get(account.page);if(page)await loadPage(page,true);
if(operation==='login'&&result)account.pages.get('login')?.login?.update(result);
if(operation==='enter_server'||operation==='restore_session')notice('已读取角色。策略保持关闭,请配置功能后开启。');
else if(result?.message)notice(result.message);
setStatus(result?.message || `${operationLabels[operation] || '操作'}已完成`);
return result;
}
function getPage(account,key) {
if(!account.pages.has(key)){
const page=new PageView(account,key,{edit:editConfig,perform,load:loadPage,action:pageAction,command,
schema:pageKey=>state.schema?.pages?.find(page=>page.key===pageKey)?.form || []});
account.pages.set(key,page);$('#page-host').append(page.root);
}
return account.pages.get(key);
}
async function loadPage(page,force=false) {
if(page.fetching){if(force)page.reload=true;return;}
page.fetching=true;const generation=page.generation || 0;
try {
const response=await api.view(page.account.id,page.key,page.query);
if(generation!==(page.generation||0))return;
page.clearError();page.render(response.data,response.loading);page.lastLoad=Date.now();
if(response.loading){clearTimeout(page.loadTimer);page.loadTimer=setTimeout(()=>loadPage(page),650);}
}catch(failure){page.showError(failure.message);}
finally{page.fetching=false;if(page.reload){page.reload=false;loadPage(page);}}
}
function selectPage(key) {
const account=current();if(!account)return;
if(account.page!==key)account.pages.get(account.page)?.login?.clearPassword();
account.page=key;
state.accounts.forEach(other=>other.pages.forEach(page=>{page.root.hidden=other.id!==account.id||page.key!==key;}));
const page=getPage(account,key);page.root.hidden=false;
$$('.page-tab').forEach(tab=>{const selected=tab.dataset.page===key;tab.setAttribute('aria-selected',String(selected));tab.tabIndex=selected?0:-1;});
loadPage(page,true);
}
async function selectAccount(id) {
const previous=current();previous?.pages.get('login')?.login?.clearPassword();
if(previous?.edits.size)flushConfig(previous).catch(error);
state.active=id;const account=current();if(!account)return;
$('#page-host').querySelector('.initial-state')?.remove();
renderAccountTabs();renderSummary();renderLogs(true);applyLogLayout(account);selectPage(account.page);
if(!account.config)try{await refreshConfig(account);}catch(failure){error(failure);}
fetchLogs(account);
}
async function addAccount(demo=false) {
const label=el('input',{type:'text','aria-label':'账号页签名称',placeholder:demo?'离线演示':'账号名称(可留空)',maxlength:80});
const result=await dialog(demo?'新增离线演示账号':'新增账号',el('div',{},el('label',{class:'field'},el('span',{class:'field-label',text:'账号名称'}),label),el('p',{class:'info-note',text:demo?'使用服务端离线演示状态,不连接游戏服务器。':'创建独立账号工作区,然后在登录页连接游戏角色。'})),{confirm:'新增',read:()=>({label:label.value.trim()})});
if(!result)return;
const summary=await api.create(result.label,demo);state.accounts.set(summary.id,makeAccount(summary));await selectAccount(summary.id);notice(demo?'离线演示账号已创建':'账号已创建,请在登录页登录。');
}
async function pageAction(page,action,currency) {
const account=page.account,operation=action.operation;
if(operation==='configure_bag'||operation==='configure_ranch'){selectPage(operation==='configure_bag'?'bag':'ranch');return;}
if(operation==='reveal_breakthrough'){page.root.querySelector('th[data-column=breakthrough_selected]')?.scrollIntoView({block:'nearest',inline:'center'});return;}
if(operation==='apply_preset'){
const preset=page.data.details.preset;
if(account.summary.running)await perform(account,'stop');
Object.entries(preset.patch || {}).forEach(([section,fields])=>Object.entries(fields).forEach(([key,value])=>editConfig(account,[section,key],value)));
editConfig(account,['policy','egg_rules'],preset.egg_rules);
await flushConfig(account);notice('预设已保存。开启顶部策略后运行。');return;
}
if(operation==='expand_regions'||operation==='collapse_regions'){page.table?.expand(operation==='expand_regions');return;}
if(operation==='import_yields'){return importYields(account);}
if(operation==='download_yields'){return exportYields(account);}
const payload=clone(action.payload || {}),selected=page.selectedRows();
if(action.selection==='monster_ids'){
if(!selected.length)throw new Error('请先选择一只或多只魔物。');
payload.monster_ids=selected.map(row=>Number(row.id));
}
if(operation==='quote_expansion'){
payload.currency=currency || 'money';
if(payload.kind==='stack'&&selected.length)payload.position=Number(selected[0].position ?? selected[0].id);
const quote=await perform(account,'quote_expansion',payload,{page});
if(await confirm(payload.kind==='stack'?'确认开启坑位':'确认新建牧场',`${quote.description}\n确认消费并开通?`,{confirm:'确认消费',danger:true}))return perform(account,'expand',{quote_id:quote.quote_id,confirm:true},{page});
return;
}
if(operation==='feed'){
const options=optionsList(action.target_options || page.data.feed_targets).filter(option=>!payload.monster_ids.includes(Number(option.value)));
if(!options.length)throw new Error('没有可接收经验的目标魔物,请检查当前突破上限。');
const select=el('select',{'aria-label':'喂养目标'},...options.map(option=>el('option',{value:option.value,text:option.label})));
const result=await dialog('确认喂养',el('div',{},el('p',{text:`将选中 ${selected.length} 只魔物作为经验素材,无法撤销。`}),el('label',{class:'field'},el('span',{class:'field-label',text:'喂养目标'}),select)),{confirm:'确认喂养',danger:true,read:()=>({target_id:Number(select.value)})});
if(!result)return;payload.target_id=result.target_id;payload.confirm=true;
}else if(action.confirm || operation==='reset_map_pending'){
if(!await confirm(action.label,`${action.confirm || '仅在游戏内核对后处理未完成记录;缺少服务器结算证据时将保留记录。'}${selected.length?'\n已选择 '+selected.length+' 项':''}`,{confirm:'确认',danger:true}))return;
payload.confirm=true;
}
return perform(account,operation,payload,{page});
}
async function importYields(account=current()) {
const file=await filePicker('.csv,.xlsx');if(!file)return;
if(file.size>8*1024*1024)throw new Error('收益资料文件最大为 8 MiB。');
const result=await perform(account,'import_yields',{filename:file.name,content_base64:await fileBase64(file)});
notice(result?.message || '收益资料已导入并保存。');
}
async function exportYields(account=current()) {
if(!account)throw new Error('请先选择账号。');
const page=getPage(account,'yields');await loadPage(page,true);
const deadline=Date.now()+30000;
while(!page.data?.columns?.length&&Date.now()<deadline){await new Promise(resolve=>setTimeout(resolve,250));await loadPage(page);}
if(!page.data?.columns?.length)throw new Error('收益资料尚未载入,请稍后重试。');
const columns=[{key:'type_id',label:'编号'},{key:'name',label:'名称'},{key:'star',label:'星'},{key:'time_total',label:'孵化秒数'},{key:'sell_money',label:'派遣金币'},{key:'sell_exp',label:'强化经验'},{key:'gold_per_hour',label:'金币/小时'},{key:'exp_per_hour',label:'经验/小时'}];
download(csvBlob(columns,page.data.rows || []),'牧场收益资料.csv');
}
async function command(name,account=current()) {
try {
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.0.dev1'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`}),el('p',{class:'info-note',text:'与桌面助手共用核心策略。配置在服务端自动保存;运行开关在重启和恢复会话后保持关闭。'})),{info:true});
if(name==='updates')return await showUpdates();
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
if(!account)throw new Error('请先新增或选择账号。');
if(name==='debug'){account.logs.debug=!account.logs.debug;account.logs.entries=[];account.logs.next=0;account.logs.generation=(account.logs.generation || 0)+1;$('#debug-log').checked=account.logs.debug;setLogVisible(true);renderLogs(true);await fetchLogs(account);return;}
if(name==='save'){await flushConfig(account);notice('策略已保存。');return;}
if(name==='stop'||name==='start')return await perform(account,name);
if(name==='start-all'||name==='stop-all'){await Promise.all([...state.accounts.values()].map(item=>perform(item,name==='start-all'?'start':'stop')));return;}
if(name==='logout')return await perform(account,'logout');
if(name==='forget-login'){
if(await confirm('退出并清除登录记录','将退出当前角色,删除当前账号保存的登录会话和账号密码。培养策略和其他账号不受影响。',{confirm:'清除登录记录',danger:true}))await perform(account,'forget_login');return;
}
if(name==='remove-account'){
if(!await confirm('移除当前账号',`移除“${account.summary.label || '当前账号'}”及其保存的会话和策略?此操作无法撤销。`,{confirm:'移除账号',danger:true}))return;
await api.remove(account.id);account.jobs.forEach(record=>record.reject(new Error('账号已移除')));account.pages.forEach(page=>{clearTimeout(page.loadTimer);page.root.remove();});clearTimeout(account.saveTimer);state.accounts.delete(account.id);state.active=null;
if(state.accounts.size)await selectAccount(state.accounts.keys().next().value);else showNoAccounts();renderAccountTabs();renderSummary();return;
}
if(name==='export-config'){
await flushConfig(account);const result=await trackJob(account,await api.exportConfig(account.id));
download(new Blob([JSON.stringify(result,null,2)],{type:'application/json'}),'牧场策略.json');return;
}
if(name==='import-config'){
const file=await filePicker('.json');if(!file)return;if(file.size>1024*1024)throw new Error('策略文件过大。');
let config;try{config=JSON.parse(await file.text());}catch{throw new Error('策略文件不是有效的 JSON。');}
if(!await confirm('导入当前账号策略','将替换当前账号策略,策略运行保持关闭。',{confirm:'导入策略'}))return;
await flushConfig(account);const result=await trackJob(account,await api.importConfig(account.id,config));await refreshConfig(account);notice('策略已导入,运行保持关闭。');await loadPage(getPage(account,account.page),true);return result;
}
if(name==='import-yields')return await importYields(account);
if(name==='export-yields')return await exportYields(account);
}catch(failure){error(failure);}
}
async function showUpdates() {
const content=el('div',{class:'detail-sections'}),values=el('div'),message=el('p'),check=el('button',{type:'button',text:'检查 GitHub 正式版本'}),apply=el('button',{type:'button',text:'提交更新请求…',disabled:true});
const labels={unchecked:'尚未检查',no_release:'尚无正式版本',up_to_date:'已是最新版本',available:'发现新版本',check_failed:'版本检查失败',unavailable:'更新器未就绪',pending:'等待宿主机处理',applying:'正在更新并检查健康',succeeded:'更新完成,健康检查通过',rolled_back:'更新失败,已回滚',failed:'更新失败'};
const lifetime=new AbortController();
let status,timer,closed=false,busy=false;
const active=()=>!closed && content.isConnected && $('#action-dialog').open;
const bounded=async callback=>{
const controller=new AbortController(),abort=()=>controller.abort();
lifetime.signal.addEventListener('abort',abort,{once:true});
const deadline=setTimeout(abort,5000);
try{return await callback(controller.signal);}
finally{clearTimeout(deadline);lifetime.signal.removeEventListener('abort',abort);}
};
const render=data=>{
if(!active())return;
status=data;
const host=data.host_status;
values.replaceChildren(detailsList({current:data.current_version || state.meta?.version,latest:data.latest_version,checked:data.checked_at,executor:data.executor?.enabled?'已就绪':'未配置或未启用',automatic:data.executor?.auto_apply?'已启用':'未启用',status:labels[data.status] || '状态未确认',...(host?{host:labels[host.status] || '状态未确认',hostVersion:host.version,hostUpdated:host.updated_at}:{})},{current:'当前版本',latest:'最新正式版本',checked:'上次检查',executor:'宿主机更新器',automatic:'定时更新',status:'更新状态',host:'宿主机回报',hostVersion:'宿主机版本',hostUpdated:'回报时间'}));
message.textContent=[...new Set([data.message,data.error,host?.message,host?.error].filter(Boolean))].join('\n');apply.disabled=!data.can_apply;
if(!data.executor?.enabled)message.textContent+=' 当前仅可检查版本;部署器未配置或未启用,无法执行更新。';
};
const schedule=()=>{clearTimeout(timer);if(active())timer=setTimeout(poll,3000);};
const disconnected=async failure=>{
if(!active())return;
message.textContent=failure.status===401?'服务已重新要求管理登录,请登录后继续查看更新状态。':'服务暂时断开,正在等待恢复;每 3 秒重新读取更新状态。';
apply.disabled=true;
try{await bounded(signal=>api.health({signal}));}catch{}
};
async function poll(){
if(!active())return;
if(busy){schedule();return;}
busy=true;
try{render(await bounded(signal=>api.updates({signal})));}
catch(failure){await disconnected(failure);}
finally{busy=false;schedule();}
}
check.addEventListener('click',async()=>{
if(busy)return;busy=true;clearTimeout(timer);check.disabled=true;check.textContent='正在检查…';
try{render(await bounded(signal=>api.checkUpdates({signal})));}
catch(failure){if(active())message.textContent=failure.name==='AbortError'?'版本检查暂未返回,稍后将自动读取最新状态。':failure.message;}
finally{busy=false;check.disabled=false;check.textContent='检查 GitHub 正式版本';schedule();}
});
apply.addEventListener('click',async()=>{
if(busy || !status?.can_apply)return;
const version=status.latest_version;
if(!window.confirm(`提交 ${version} 更新请求?执行器将处理请求并可能重启服务。`))return;
busy=true;clearTimeout(timer);apply.disabled=true;
try{render(await bounded(signal=>api.applyUpdate(version,{signal})));}
catch(failure){await disconnected(failure);}
finally{busy=false;schedule();}
});
content.append(values,message,el('div',{class:'page-toolbar'},check,apply),el('p',{class:'info-note',text:'仅检查 GitHub 正式版本。窗口打开时每 3 秒读取宿主机状态;提交请求后由受控更新器处理,服务恢复且健康检查通过后才显示完成。'}));
const open=dialog('版本与更新',content,{info:true});
poll();
try{await open;}
finally{closed=true;clearTimeout(timer);lifetime.abort();}
}
function setLogVisible(visible) {
const account=current();if(account?.config)editConfig(account,['log_visible'],visible);
else applyLogLayout(null,visible);
}
function applyLogLayout(account=current(),visibleOverride) {
if(account&&account.id!==state.active)return;
const visible=visibleOverride ?? account?.config?.log_visible ?? true;
$('#log-panel').hidden=!visible;$('#log-resizer').hidden=!visible;$('#log-toggle').textContent=visible?'隐藏日志':'显示日志';$('#log-toggle').setAttribute('aria-expanded',String(visible));
const size=account?.config?.log_sizes?.[1];if(size)setLogHeight(size);
}
function setLogHeight(height) {
height=Math.max(64,Math.min(Math.min(480,innerHeight*.5),Math.round(height)));
document.documentElement.style.setProperty('--log-height',`${height}px`);$('#log-resizer').setAttribute('aria-valuenow',String(height));return height;
}
function renderLogs(reset=false) {
const account=current(),root=$('#log-lines');if(!account){root.replaceChildren();return;}
const log=account.logs;
if(reset){root.replaceChildren();log.rendered=0;}
const follow=$('#log-follow').checked&& (reset || root.scrollHeight-root.scrollTop-root.clientHeight<45);
for(const entry of log.entries.slice(log.rendered || 0)){
const line=el('div',{class:`log-entry ${entry.level || entry.kind || ''}`,'data-entry-id':entry.id});
const stamp=entry.time || entry.timestamp || entry.at || '';
line.append(el('span',{class:'log-time',text:chinaTime(stamp),title:String(stamp)}),document.createTextNode(entry.message || entry.operation || textValue(entry)));
if(entry.details_available || entry.detail_url || entry.debug_url){line.classList.add('inspectable');line.tabIndex=0;line.setAttribute('role','button');line.title='查看脱敏请求 / 响应 JSON';line.addEventListener('click',()=>showDebugEntry(account,entry));line.addEventListener('keydown',event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();showDebugEntry(account,entry);}});}
root.append(line);
}
log.rendered=log.entries.length;
while(root.childElementCount>600)root.firstElementChild.remove();
$('#log-count').textContent=`${Math.min(600,log.entries.length)} 条`;$('#debug-log').checked=log.debug;$('#log-heading').textContent=log.debug?'调试日志(已脱敏)':'运行日志';
if(follow)root.scrollTop=root.scrollHeight;
}
async function fetchLogs(account) {
if(account.logs.loading)return;account.logs.loading=true;const generation=account.logs.generation || 0;
try{const response=await api.logs(account.id,account.logs.next,account.logs.debug);if(generation!==(account.logs.generation || 0))return;
const seen=new Set(account.logs.entries.map(entry=>entry.id));
account.logs.entries.push(...(response.entries || []).filter(entry=>entry.id==null||!seen.has(entry.id)));account.logs.next=response.next;
if(account.id===state.active)renderLogs();
if(account.logs.entries.length>1200){account.logs.entries=account.logs.entries.slice(-600);if(account.id===state.active)renderLogs(true);}
}catch(failure){if(failure.status!==401)setStatus(failure.message);}finally{account.logs.loading=false;}
}
async function showDebugEntry(account,entry) {
const pre=el('pre',{class:'debug-json',text:'正在读取所选条目的脱敏详情…'});const open=dialog('请求 / 响应详情(已脱敏)',pre,{info:true});
try{
let path;
try{path=apiPath(entry.detail_url || entry.debug_url);}catch{/* Use the account's own endpoint for untrusted URLs. */}
const detail=await (path?request(path):api.debugEntry(account.id,entry.id));
pre.textContent=JSON.stringify(detail.details ?? detail,null,2);
}catch(failure){pre.textContent=failure.message;}
await open;
}
function showNoAccounts() {
state.active=null;$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:'尚未添加账号。新增账号后登录游戏,或使用离线演示查看工作台。'}),el('div',{class:'page-toolbar'},el('button',{text:'新增账号…',onClick:()=>command('add-account')}),el('button',{text:'新增离线演示账号',onClick:()=>command('add-demo')}))));
renderAccountTabs();renderSummary();renderLogs(true);setStatus('等待新增账号');
}
async function syncAccounts() {
const response=await api.accounts(),summaries=Array.isArray(response)?response:response.accounts || [];
const ids=new Set(summaries.map(summary=>summary.id));
for(const [id,account]of state.accounts)if(!ids.has(id)){account.pages.forEach(page=>{clearTimeout(page.loadTimer);page.root.remove();});state.accounts.delete(id);}
summaries.forEach(summary=>{
const account=state.accounts.get(summary.id);if(account){account.summary=summary;if(account.config&&account.revision!==summary.revision&&!account.edits.size&&!account.savePromise)refreshConfig(account).catch(error);}
else state.accounts.set(summary.id,makeAccount(summary));
});
renderAccountTabs();renderSummary();
if(!state.accounts.size)showNoAccounts();else if(!state.accounts.has(state.active))await selectAccount(state.accounts.keys().next().value);
}
async function tick() {
if(!state.ready||state.polling)return;state.polling=true;
try{
const account=current();await Promise.allSettled([syncAccounts(),...([...state.accounts.values()].flatMap(item=>[...item.jobs.values()].map(job=>pollJob(item,job))))]);
if(state.ready&&account&&state.accounts.has(account.id)){fetchLogs(account);const page=account.pages.get(account.page);if(page&&Date.now()-(page.lastLoad||0)>4000)loadPage(page);}
}finally{state.polling=false;}
}
function hideWorkbench() {
state.ready=false;
$('#app').hidden=true;$('#notice').hidden=true;
$$('dialog[open]').forEach(root=>root.close());
$$('.context-menu').forEach(root=>root.remove());
$$('input[type="password"]').forEach(input=>input.value='');
state.accounts.forEach(account=>{clearTimeout(account.saveTimer);account.pages.forEach(page=>clearTimeout(page.loadTimer));});
}
function requireAuth() {
if(state.redirecting)return;
state.redirecting=true;hideWorkbench();location.replace(webPath('/login'));
}
async function bootstrap() {
try{
const auth=await api.auth();if(state.redirecting)return;if(auth.required&&!auth.authenticated){requireAuth();return;}
$('#app').hidden=false;
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
if(state.redirecting)return;
$('#app-version').textContent=meta.version || '2.0.0.dev1';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接');
}catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
}
PAGES.forEach(([key,label])=>$('#page-tabs').append(el('button',{type:'button',class:'page-tab',role:'tab','data-page':key,'aria-selected':String(key==='login'),tabindex:key==='login'?0:-1,text:label,onClick:()=>selectPage(key)})));
tabKeys($('#account-tabs'),'.account-tab');tabKeys($('#page-tabs'),'.page-tab');
$('#menu-bar').addEventListener('click',event=>{const button=event.target.closest('[data-command]');if(button){$$('.menu[open]').forEach(menu=>menu.open=false);command(button.dataset.command);}});
document.addEventListener('click',event=>{if(!event.target.closest('.menu'))$$('.menu[open]').forEach(menu=>menu.open=false);});
document.addEventListener('keydown',event=>{if(event.key==='Escape')$$('.menu[open]').forEach(menu=>menu.open=false);});
$$('.menu').forEach(menu=>menu.addEventListener('toggle',()=>{if(menu.open)$$('.menu').filter(other=>other!==menu).forEach(other=>other.open=false);}));
$('#add-account').addEventListener('click',()=>command('add-account'));
$('#strategy-toggle').addEventListener('click',()=>command(current()?.summary.running?'stop':'start'));
$('#refresh').addEventListener('click',()=>{const account=current();if(account)perform(account,'refresh',{page:account.page}).catch(error);});
$('#refresh-interval').addEventListener('change',event=>{if(current())editConfig(current(),['interval'],Number(event.target.value));});
$('#save-status').tabIndex=0;$('#save-status').addEventListener('click',()=>command('save'));$('#save-status').addEventListener('keydown',event=>{if(event.key==='Enter')command('save');});
$('#debug-toggle').addEventListener('click',()=>command('debug'));$('#debug-log').addEventListener('change',()=>command('debug'));
$('#log-toggle').addEventListener('click',()=>setLogVisible($('#log-panel').hidden));
$('#clear-log').addEventListener('click',()=>{if(current()){current().logs.entries=[];current().logs.rendered=0;renderLogs(true);}});
$('#download-log').addEventListener('click',()=>{const account=current();if(account)download(new Blob([account.logs.entries.map(entry=>[entry.time || entry.timestamp || '',entry.message || entry.operation || ''].join(' ')).join('\n')],{type:'text/plain;charset=utf-8'}),'牧场日志.txt');});
$('#log-lines').addEventListener('scroll',()=>{const node=$('#log-lines');if(node.scrollHeight-node.scrollTop-node.clientHeight>55)$('#log-follow').checked=false;});
$('#log-follow').addEventListener('change',()=>{if($('#log-follow').checked)$('#log-lines').scrollTop=$('#log-lines').scrollHeight;});
let resize;
$('#log-resizer').addEventListener('pointerdown',event=>{resize={y:event.clientY,height:$('#log-panel').getBoundingClientRect().height};event.currentTarget.setPointerCapture(event.pointerId);event.preventDefault();});
$('#log-resizer').addEventListener('pointermove',event=>{if(resize)setLogHeight(resize.height+resize.y-event.clientY);});
$('#log-resizer').addEventListener('pointerup',()=>{if(!resize)return;resize=null;const account=current();if(account?.config)editConfig(account,['log_sizes'],[$('#workspace').clientHeight,Number($('#log-resizer').getAttribute('aria-valuenow'))]);});
$('#log-resizer').addEventListener('keydown',event=>{if(!['ArrowUp','ArrowDown','Home','End'].includes(event.key))return;event.preventDefault();const height=Number(event.currentTarget.getAttribute('aria-valuenow'));const next=setLogHeight(event.key==='Home'?64:event.key==='End'?480:height+(event.key==='ArrowUp'?16:-16));if(current()?.config)editConfig(current(),['log_sizes'],[$('#workspace').clientHeight,next]);});
window.addEventListener('auth-required',requireAuth);
window.addEventListener('pagehide',hideWorkbench);
window.addEventListener('pageshow',event=>{if(event.persisted){state.redirecting=false;bootstrap();}});
window.addEventListener('beforeunload',event=>{if(!state.redirecting&&[...state.accounts.values()].some(account=>account.edits.size||account.savePromise)){event.preventDefault();event.returnValue='';}});
setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString('zh-CN',{hour12:false});},1000);
setInterval(tick,1000);
bootstrap();
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-34
View File
@@ -1,34 +0,0 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="ranch-web-base-path" content="">
<meta name="color-scheme" content="light">
<meta name="theme-color" content="#172435">
<link rel="icon" href="data:,">
<title>牧羊人之心 · 自动化控制台</title>
<script type="module" crossorigin src="./assets/index-DdG7ejiq.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-Br0WZ5ge.css">
</head>
<body>
<div id="app" hidden></div>
<div id="notice" class="notice" role="status" hidden></div>
<dialog id="action-dialog" aria-labelledby="dialog-title">
<form id="dialog-form">
<header class="dialog-header">
<h1 id="dialog-title"></h1>
<button type="button" class="dialog-close" aria-label="关闭对话框">×</button>
</header>
<div id="dialog-content" class="dialog-content"></div>
<p id="dialog-error" class="error-text" role="alert" hidden></p>
<footer class="dialog-footer">
<button type="button" id="dialog-cancel">取消</button>
<button type="submit" id="dialog-confirm" class="primary">确认</button>
</footer>
</form>
</dialog>
<noscript>请启用 JavaScript 以使用牧场管理控制台。</noscript>
</body>
</html>
+4 -16
View File
@@ -29,7 +29,7 @@ export function control(field, {get, set, onError = () => {}}) {
} else if (['boolean', 'bool', 'checkbox'].includes(type)) { } else if (['boolean', 'bool', 'checkbox'].includes(type)) {
root = el('input', {type: 'checkbox', 'aria-label': label}); root = el('input', {type: 'checkbox', 'aria-label': label});
root.addEventListener('change', () => commit(root.checked)); root.addEventListener('change', () => commit(root.checked));
sync = () => { if (document.activeElement !== root) root.checked = Boolean(value()); }; sync = () => { root.checked = Boolean(value()); };
} else if (['select', 'enum'].includes(type)) { } else if (['select', 'enum'].includes(type)) {
root = el('select', {'aria-label': label}); root = el('select', {'aria-label': label});
let optionsSignature; let optionsSignature;
@@ -58,10 +58,7 @@ export function control(field, {get, set, onError = () => {}}) {
root.append(el('label', {}, check, option.label)); root.append(el('label', {}, check, option.label));
return {check, option}; return {check, option};
}); });
sync = () => { sync = () => items.forEach(({check, option}) => { check.checked = (value() || []).includes(option.value); });
const selected = value() || [];
items.forEach(({check, option}) => { if (document.activeElement !== check) check.checked = selected.includes(option.value); });
};
} else if (['id_counts', 'counts', 'reserves'].includes(type)) { } else if (['id_counts', 'counts', 'reserves'].includes(type)) {
root = el('div', {class: 'counts-editor', role: 'group', 'aria-label': label}); root = el('div', {class: 'counts-editor', role: 'group', 'aria-label': label});
const lines = el('div', {class: 'counts-lines'}); const lines = el('div', {class: 'counts-lines'});
@@ -126,15 +123,7 @@ export function control(field, {get, set, onError = () => {}}) {
} }
root.dataset.configPath = pathKey(path); root.dataset.configPath = pathKey(path);
root.title = field.help || field.description || label; root.title = field.help || field.description || label;
const syncValue = sync; root.disabled = Boolean(field.disabled || field.readonly);
sync = () => {
if (!root.contains(document.activeElement)) {
const disabled = Boolean(field.disabled || field.readonly);
if (root.matches('input,select,button,textarea')) root.disabled = disabled;
else root.querySelectorAll('input,select,button,textarea').forEach(input => { input.disabled = disabled; });
}
syncValue();
};
sync(); sync();
return {root, sync, field}; return {root, sync, field};
} }
@@ -183,9 +172,8 @@ export class PolicyForm {
this.signature = signature; this.signature = signature;
} }
this.host.hidden = !fields.length; this.host.hidden = !fields.length;
const latestByPath = new Map(fields.map(field => [pathKey(field.path), field]));
this.controls.forEach(entry => { this.controls.forEach(entry => {
const latest = latestByPath.get(pathKey(entry.field.path)); const latest = fields.find(field => pathKey(field.path) === pathKey(entry.field.path));
if (latest) Object.assign(entry.field, latest); if (latest) Object.assign(entry.field, latest);
entry.sync(); entry.sync();
entry.row.dataset.dirty = String(Boolean(this.context.dirty?.(entry.field.path))); entry.row.dataset.dirty = String(Boolean(this.context.dirty?.(entry.field.path)));
+47 -31
View File
@@ -1,34 +1,50 @@
<!doctype html> <!doctype html>
<html lang="zh-CN"> <html lang="zh-CN">
<head> <head>
<meta charset="UTF-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="ranch-web-base-path" content=""> <meta name="ranch-web-base-path" content="">
<meta name="color-scheme" content="light"> <meta name="color-scheme" content="light">
<meta name="theme-color" content="#172435"> <title>牧羊人之心牧场助手 · Web</title>
<link rel="icon" href="data:,"> <link rel="icon" href="data:,">
<title>牧羊人之心 · 自动化控制台</title> <link rel="stylesheet" href="/static/styles.css">
<script type="module" crossorigin src="/static/console/assets/index-DdG7ejiq.js"></script> <script type="module" src="/static/app.js"></script>
<link rel="stylesheet" crossorigin href="/static/console/assets/index-Br0WZ5ge.css"> </head>
</head> <body>
<body> <div id="app" class="workbench" aria-label="牧羊人之心牧场助手" hidden>
<div id="app" hidden></div> <header class="window-header">
<div id="notice" class="notice" role="status" hidden></div> <nav id="menu-bar" class="menu-bar" aria-label="主菜单">
<dialog id="action-dialog" aria-labelledby="dialog-title"> <details class="menu"><summary accesskey="a">账号<span class="access-key">(A)</span></summary><div class="menu-popup">
<form id="dialog-form"> <button data-command="add-account">新增账号…</button><button data-command="add-demo">新增离线演示账号</button>
<header class="dialog-header"> <button data-command="remove-account">移除当前账号…</button><hr><button data-command="logout">退出游戏登录</button><button data-command="forget-login">退出并清除登录记录…</button><hr><button data-command="admin-logout">退出管理工作台</button>
<h1 id="dialog-title"></h1> </div></details>
<button type="button" class="dialog-close" aria-label="关闭对话框">×</button> <details class="menu"><summary accesskey="r">策略<span class="access-key">(R)</span></summary><div class="menu-popup">
</header> <button data-command="start">开启当前账号策略</button><button data-command="stop">停止当前账号策略</button><hr><button data-command="start-all">开启全部账号策略</button><button data-command="stop-all">停止全部账号策略</button>
<div id="dialog-content" class="dialog-content"></div> </div></details>
<p id="dialog-error" class="error-text" role="alert" hidden></p> <details class="menu"><summary accesskey="s">配置<span class="access-key">(S)</span></summary><div class="menu-popup">
<footer class="dialog-footer"> <button data-command="save">保存当前账号策略</button><button data-command="import-config">导入当前账号策略…</button><button data-command="export-config">导出当前账号策略</button><hr><button data-command="import-yields">导入收益 CSV / XLSX…</button><button data-command="export-yields">下载收益 CSV</button>
<button type="button" id="dialog-cancel">取消</button> </div></details>
<button type="submit" id="dialog-confirm" class="primary">确认</button> <details class="menu"><summary accesskey="h">帮助<span class="access-key">(H)</span></summary><div class="menu-popup"><button data-command="updates">检查版本更新…</button><button data-command="debug">调试日志</button><button data-command="about">关于…</button></div></details>
</footer> </nav>
</form> <span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.0.dev1</span></span>
</dialog> <span id="access-mode" class="muted">正在连接本地服务</span>
<noscript>请启用 JavaScript 以使用牧场管理控制台。</noscript> </header>
<div class="account-bar"><div id="account-tabs" class="account-tabs" role="tablist" aria-label="账号"></div><button id="add-account" class="compact" title="新增账号">+ 新增账号</button></div>
</body> <div class="toolbar" aria-label="角色状态和运行控制">
<div class="player-line"><span id="connection" class="connection">未登录</span><strong id="player-name">—</strong><span>等级 <b id="player-level">—</b></span><span class="experience">经验 <b id="player-exp">—</b><progress id="experience-progress" max="1" value="0" aria-label="角色经验"></progress></span><span>金币 <b id="player-money">—</b></span><span>氪金 <b id="player-ke">—</b></span><span>体力 <b id="player-ti">—</b></span></div>
<div class="run-controls"><label>刷新 <select id="refresh-interval" aria-label="随机刷新间隔" title="整体刷新完成后,从 0 到所选上限随机等待;空坑装填与到期同步独立执行"><option value="30">随机30秒</option><option value="60">随机60秒</option><option value="120">随机2分钟</option><option value="300">随机5分钟</option></select></label><button id="strategy-toggle" class="run-button" disabled>开启</button><button id="refresh">刷新 / 预览策略</button><button id="debug-toggle">调试日志</button><button id="log-toggle" aria-expanded="true" aria-controls="log-panel">隐藏日志</button></div>
</div>
<div class="summary-line"><span id="data-summary">等待连接服务</span><span id="save-status" role="status">配置未载入</span></div>
<main id="workspace" class="workspace">
<nav id="page-tabs" class="page-tabs" role="tablist" aria-label="功能页面"></nav>
<div id="page-host" class="page-host"><div class="initial-state" role="status">正在载入工作台…</div></div>
</main>
<div id="log-resizer" class="log-resizer" role="separator" tabindex="0" aria-label="调整日志高度" aria-orientation="horizontal" aria-valuemin="64" aria-valuemax="480" aria-valuenow="150" title="上下拖动调整日志高度;也可使用方向键"></div>
<section id="log-panel" class="log-panel" aria-label="运行日志"><div class="log-toolbar"><strong id="log-heading">运行日志</strong><label><input id="debug-log" type="checkbox">调试 / 脱敏</label><label><input id="log-follow" type="checkbox" checked>自动滚动</label><span id="log-count" class="muted"></span><span class="spacer"></span><button id="download-log" class="small">下载日志</button><button id="clear-log" class="small">清空显示</button></div><div id="log-lines" class="log-lines" tabindex="0" role="log" aria-live="off" aria-label="日志内容"></div></section>
<footer class="status-bar"><span id="status-text" role="status">连接中</span><span id="job-status" class="muted"></span><span class="spacer"></span><span>游戏 <span id="game-version">1.9.68</span></span><span id="clock"></span></footer>
</div>
<div id="notice" class="notice" role="status" hidden></div>
<dialog id="action-dialog" aria-labelledby="dialog-title"><form id="dialog-form"><header class="dialog-header"><h1 id="dialog-title"></h1><button type="button" class="dialog-close" aria-label="关闭对话框">×</button></header><div id="dialog-content" class="dialog-content"></div><p id="dialog-error" class="error-text" role="alert" hidden></p><footer class="dialog-footer"><button type="button" id="dialog-cancel">取消</button><button type="submit" id="dialog-confirm" class="primary">确认</button></footer></form></dialog>
<noscript>此工作台需要启用 JavaScript 才能连接本地服务。</noscript>
</body>
</html> </html>
+11 -14
View File
@@ -1,29 +1,26 @@
:root { :root {
font-family: "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif; font-family: "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
font-size: 14px; font-size: 13px;
color: #17243b; color: #202832;
background: #f4f6fa; background: #f1f3f5;
font-synthesis: none; font-synthesis: none;
color-scheme: light; color-scheme: light;
} }
* { box-sizing: border-box; } * { box-sizing: border-box; }
[hidden] { display: none !important; } [hidden] { display: none !important; }
body { margin: 0; min-height: 100dvh; display: grid; place-items: center; padding: 24px 16px; } body { margin: 0; min-height: 100dvh; display: grid; place-items: center; padding: 24px 16px; }
.admin-login { width: 100%; max-width: 420px; padding: 36px; background: #fff; border: 1px solid #dbe2ec; border-radius: 14px; box-shadow: 0 12px 40px rgb(22 34 53 / 6%); } .admin-login { width: 100%; max-width: 370px; padding: 24px; background: #fff; border: 1px solid #cbd1d8; border-radius: 5px; }
.login-brand { display: flex; align-items: center; gap: 10px; margin-bottom: 32px; font-weight: 700; color: #2563eb; } h1 { margin: 0 0 12px; font-size: 18px; font-weight: 600; }
.login-brand svg { width: 28px; height: 28px; }
h1 { margin: 0 0 10px; font-size: 24px; font-weight: 650; letter-spacing: -.5px; }
p { margin: 0; line-height: 1.65; overflow-wrap: anywhere; } p { margin: 0; line-height: 1.65; overflow-wrap: anywhere; }
#auth-description { color: #526079; margin-bottom: 28px; } #auth-description { color: #55616e; margin-bottom: 20px; }
form { display: flex; flex-direction: column; gap: 8px; } form { display: flex; flex-direction: column; gap: 8px; }
input, button { font: inherit; min-width: 0; min-height: 44px; padding: 9px 12px; border: 1px solid #bdc9d9; border-radius: 7px; } input, button { font: inherit; min-width: 0; min-height: 36px; padding: 7px 10px; border: 1px solid #afb8c2; border-radius: 3px; }
input { width: 100%; background: #fff; color: inherit; caret-color: #2563eb; } input { width: 100%; background: #fff; color: inherit; caret-color: #245d9b; }
button { margin-top: 12px; background: #2563eb; color: #fff; border-color: #2563eb; cursor: pointer; font-weight: 600; } button { margin-top: 8px; background: #245d9b; color: #fff; border-color: #245d9b; cursor: pointer; }
button:hover { background: #1d4ed8; } button:hover { background: #1c4d83; }
button:disabled { cursor: default; opacity: .58; } button:disabled { cursor: default; opacity: .58; }
input:focus-visible, button:focus-visible { outline: 2px solid #2563eb; outline-offset: 3px; } input:focus-visible, button:focus-visible { outline: 2px solid #245d9b; outline-offset: 2px; }
#auth-status { color: #55616e; } #auth-status { color: #55616e; }
#auth-error { color: #99251e; white-space: pre-wrap; } #auth-error { color: #99251e; white-space: pre-wrap; }
noscript { display: block; margin-top: 16px; line-height: 1.65; } noscript { display: block; margin-top: 16px; line-height: 1.65; }
::selection { background: #c5dbf5; color: #142b46; } ::selection { background: #c5dbf5; color: #142b46; }
@media (max-width: 480px) { .admin-login { padding: 28px 24px; } }
+3 -4
View File
@@ -5,16 +5,15 @@
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="ranch-web-base-path" content=""> <meta name="ranch-web-base-path" content="">
<meta name="color-scheme" content="light"> <meta name="color-scheme" content="light">
<title>管理登录 · 牧羊人之心控制台</title> <title>管理登录 · 牧羊人之心牧场助手</title>
<link rel="icon" href="data:,"> <link rel="icon" href="data:,">
<link rel="stylesheet" href="/static/login.css"> <link rel="stylesheet" href="/static/login.css">
<script type="module" src="/static/login.js"></script> <script type="module" src="/static/login.js"></script>
</head> </head>
<body> <body>
<main class="admin-login" aria-labelledby="auth-title"> <main class="admin-login" aria-labelledby="auth-title">
<div class="login-brand"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M12 21v-9M12 16C5 16 3 11 3 5c6 0 9 3 9 9M12 12c0-6 3-9 9-9 0 6-3 9-9 9"/></svg><span>牧羊人之心控制台</span></div> <h1 id="auth-title">登录管理工作台</h1>
<h1 id="auth-title">登录管理控制台</h1> <p id="auth-description">请输入此 Web 工作台的管理密码。</p>
<p id="auth-description">输入管理密码,进入你的牧羊人之心工作空间。</p>
<form id="auth-form" method="post" action="/api/auth/login" aria-describedby="auth-description"> <form id="auth-form" method="post" action="/api/auth/login" aria-describedby="auth-description">
<label for="admin-password">管理密码</label> <label for="admin-password">管理密码</label>
<input id="admin-password" name="password" type="password" autocomplete="current-password" required aria-describedby="auth-error" disabled> <input id="admin-password" name="password" type="password" autocomplete="current-password" required aria-describedby="auth-error" disabled>
+2 -15
View File
@@ -111,21 +111,11 @@ export class PageView {
clearError() { this.errorBox.hidden = true; } clearError() { this.errorBox.hidden = true; }
setQuery(key, value) { setQuery(key, value) {
if (this.destroyed || this.query[key] === value) return; if (this.query[key] === value) return;
this.query[key] = value; this.query[key] = value;
this.generation = (this.generation || 0) + 1; this.generation = (this.generation || 0) + 1;
clearTimeout(this.queryTimer); clearTimeout(this.queryTimer);
this.queryTimer = setTimeout(() => { if (!this.destroyed) this.options.load(this, true); }, key === 'search' ? 220 : 0); this.queryTimer = setTimeout(() => this.options.load(this, true), key === 'search' ? 220 : 0);
}
destroy() {
this.destroyed = true;
clearTimeout(this.queryTimer);
this.generation = (this.generation || 0) + 1;
this.table?.destroy?.();
this.statisticsTable?.destroy();
this.login?.clearPassword();
this.root.remove();
} }
updateFilters(filters) { updateFilters(filters) {
@@ -207,7 +197,6 @@ export class PageView {
} }
render(data, loading = false) { render(data, loading = false) {
if (this.destroyed) return;
if (!data) { this.loading.textContent = '正在读取…'; this.loading.dataset.loading = 'true'; return; } if (!data) { this.loading.textContent = '正在读取…'; this.loading.dataset.loading = 'true'; return; }
this.data = data; this.data = data;
this.loading.dataset.loading = String(loading); this.loading.dataset.loading = String(loading);
@@ -235,8 +224,6 @@ export class PageView {
const mode = this.key === 'statistics' ? 'statistics' : grouped ? 'grouped' : 'table'; const mode = this.key === 'statistics' ? 'statistics' : grouped ? 'grouped' : 'table';
if (this.contentMode !== mode) { if (this.contentMode !== mode) {
if (this.content.contains(document.activeElement)) return; if (this.content.contains(document.activeElement)) return;
this.table?.destroy?.();
this.statisticsTable?.destroy();
this.content.replaceChildren(); this.content.replaceChildren();
this.contentMode = mode; this.contentMode = mode;
this.table = mode === 'grouped' ? new GroupedTables(this.content, this.context, {collapsed: this.key === 'maps'}) : mode === 'table' ? new DataTable(this.content, this.context, {emptyMessage: this.key === 'plans' ? '当前没有执行计划。请配置策略并刷新 / 预览,查看下一步或等待原因。' : '当前筛选下没有条目。可调整筛选,或登录后刷新状态。'}) : null; this.table = mode === 'grouped' ? new GroupedTables(this.content, this.context, {collapsed: this.key === 'maps'}) : mode === 'table' ? new DataTable(this.content, this.context, {emptyMessage: this.key === 'plans' ? '当前没有执行计划。请配置策略并刷新 / 预览,查看下一步或等待原因。' : '当前筛选下没有条目。可调整筛选,或登录后刷新状态。'}) : null;
+14
View File
@@ -0,0 +1,14 @@
:root{font-family:"Segoe UI","Microsoft YaHei UI","Microsoft YaHei",system-ui,sans-serif;font-size:13px;color:#202832;background:#f1f3f5;font-synthesis:none;color-scheme:light;--border:#cbd1d8;--muted:#55616e;--accent:#245d9b;--tint:#e8f0f9;--log-height:150px;--danger:#b3261e;--green:#20743a}
*{box-sizing:border-box}body{margin:0}button,input,select,textarea{font:inherit;color:inherit}button,select,input[type=number],input[type=text],input[type=password],input[type=search],textarea{border:1px solid #afb8c2;border-radius:3px;background:#fff;min-height:27px}button{padding:3px 10px;cursor:pointer;white-space:nowrap;background:#f8f9fb}button:hover{background:#e9edf2;border-color:#8291a1}button:active{background:#dce4ed}button:disabled,input:disabled,select:disabled{cursor:default;opacity:.58}input,select{padding:2px 6px}input[type=checkbox]{width:14px;height:14px;min-height:0;margin:0 4px 0 0;accent-color:var(--accent);vertical-align:middle;flex-shrink:0}input[type=number]{font-variant-numeric:tabular-nums;min-width:62px;width:88px}input[type=search]{min-width:170px}select{max-width:100%}textarea{padding:6px;resize:vertical;min-height:60px}button:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible,[tabindex]:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:2px}::selection{background:#c5dbf5;color:#142b46}input,textarea{caret-color:var(--accent)}[hidden]{display:none!important}h1,h2,h3,p{margin:0}h1{font-size:16px;font-weight:600}h2,h3{font-size:14px;font-weight:600}p{line-height:1.65}a{color:var(--accent);text-underline-offset:3px}.muted{color:var(--muted);font-size:12px}.spacer{flex:1}.primary{background:#245d9b;color:#fff;border-color:#245d9b}.primary:hover{background:#1c4d83;color:#fff}.danger{color:#94231d;border-color:#c39c99}.error-text{color:#99251e;white-space:pre-wrap;overflow-wrap:anywhere}.small,.compact{min-height:24px;padding:2px 8px;font-size:12px}
.workbench{height:100dvh;min-height:420px;display:flex;flex-direction:column;overflow:hidden}.window-header{display:flex;align-items:center;min-height:29px;gap:16px;padding:0 10px 0 4px;border-bottom:1px solid var(--border);background:#f6f7f9}.window-title{font-size:12px;color:#404c59}.window-title #app-version{margin-left:5px;color:var(--muted)}#access-mode{margin-left:auto}.menu-bar{display:flex;gap:1px}.menu{position:relative}.menu>summary{list-style:none;padding:5px 9px;cursor:pointer;border-radius:2px}.menu>summary::-webkit-details-marker{display:none}.menu[open]>summary,.menu>summary:hover{background:#dfe8f3}.access-key{font-size:11px;margin-left:3px;color:var(--muted)}.menu-popup{position:absolute;top:100%;left:0;z-index:30;min-width:220px;padding:4px;background:#fff;border:1px solid #acb6c1;box-shadow:0 5px 14px #172a4026}.menu-popup button{display:block;width:100%;border:0;border-radius:0;text-align:left;background:transparent;padding:6px 12px}.menu-popup button:hover{background:var(--tint)}.menu-popup hr{border:0;border-top:1px solid var(--border);margin:4px 2px}
.account-bar{display:flex;gap:6px;align-items:center;padding:5px 6px 0;min-height:36px;background:#e7ebef;border-bottom:1px solid var(--border)}.account-tabs{display:flex;overflow-x:auto;gap:3px;align-self:stretch;min-width:0;scrollbar-width:thin}.account-tab{border-radius:4px 4px 0 0;border:1px solid var(--border);border-bottom:0;display:flex;gap:6px;align-items:center;max-width:230px;background:#f1f3f5;min-height:30px;padding:4px 13px}.account-tab[aria-selected=true]{background:#fff;box-shadow:inset 0 2px 0 var(--accent)}.account-tab .account-label{overflow:hidden;text-overflow:ellipsis}.account-dot{width:6px;height:6px;border-radius:50%;background:#7b8490;flex-shrink:0}.account-dot.running{background:var(--green)}.account-dot.error{background:var(--danger)}#add-account{margin:0 0 5px;flex-shrink:0}.toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:8px 18px;padding:8px 8px 5px;background:#fff}.player-line{display:flex;align-items:center;flex-wrap:wrap;gap:12px;min-height:27px;flex:1 1 auto}.player-line>span{white-space:nowrap}.player-line b{font-weight:600;font-variant-numeric:tabular-nums}.player-line>strong{max-width:180px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.connection{font-size:12px;color:var(--muted)}.connection.online{color:#176331}.connection.demo{color:#805300}.experience{display:inline-flex;gap:5px;align-items:center}progress{width:58px;height:6px;accent-color:var(--accent)}progress::-webkit-progress-bar{background:#e2e7ee;border-radius:2px}progress::-webkit-progress-value{background:#467aa9;border-radius:2px}.run-controls{display:flex;align-items:center;gap:5px;flex-wrap:wrap}.run-controls>label{display:flex;align-items:center;gap:5px}.run-button{min-width:76px;font-weight:600;background:var(--green);border-color:#185b2d;color:#fff}.run-button:hover{background:#1b6332;color:#fff;border-color:#185b2d}.run-button.running{background:var(--danger);border-color:#8f1e18}.run-button.running:hover{background:#992019}.run-button:disabled{opacity:1;background:#727b82;border-color:#727b82}.summary-line{display:flex;gap:10px;align-items:center;min-height:25px;padding:2px 8px 5px;background:#fff;font-size:12px;color:var(--muted)}#data-summary{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;flex:1}#save-status{flex-shrink:0}#save-status.pending{color:#805300}#save-status.failed{color:#99251e}
.workspace{display:flex;flex-direction:column;flex:1;min-height:155px;padding:0 6px;overflow:hidden;background:#fff}.page-tabs{display:flex;flex-shrink:0;overflow-x:auto;gap:0;border-bottom:1px solid #9eabb9;scrollbar-width:thin}.page-tab{border-radius:3px 3px 0 0;border:1px solid transparent;background:#f1f3f5;padding:6px 10px;min-height:30px;margin-right:1px;font-size:12px}.page-tab[aria-selected=true]{background:#fff;border-color:#9eabb9;border-bottom-color:#fff;color:#174d83;box-shadow:inset 0 2px 0 #245d9b;font-weight:600}.page-tab:hover{background:#e8f0f9}.page-host{flex:1;min-height:0;overflow:hidden;position:relative}.page-panel{height:100%;display:flex;flex-direction:column;overflow:auto;padding:7px 2px 4px;gap:7px;scrollbar-gutter:stable}.page-header{display:flex;gap:8px;align-items:center;flex-wrap:wrap;min-height:25px}.page-header h2{margin-right:7px}.page-summary{color:var(--muted);font-size:12px;line-height:1.6;white-space:pre-wrap;overflow-wrap:anywhere}.page-toolbar,.filter-bar{display:flex;flex-wrap:wrap;gap:5px 9px;align-items:center}.filter-bar label{display:inline-flex;gap:5px;align-items:center}.page-loading{font-size:12px;color:var(--muted);margin-left:auto}.page-loading[data-loading=true]::before{content:"";display:inline-block;width:7px;height:7px;background:#688aaf;border-radius:50%;margin-right:5px}.subtabs{display:flex;gap:2px;border-bottom:1px solid var(--border);flex-shrink:0}.subtab{background:#f0f2f5;border:1px solid var(--border);border-bottom:0;border-radius:3px 3px 0 0;font-size:12px;padding:4px 10px}.subtab[aria-selected=true]{background:#e8f0f9;color:#174d83;border-color:#94adc7}.initial-state,.empty-state{padding:24px 18px;color:var(--muted);line-height:1.8}.empty-state p{max-width:65ch}.empty-state button{margin-top:12px}.page-error{padding:8px 10px;background:#fff4f3;border:1px solid #ddbbb7;color:#8e251f;display:flex;align-items:center;gap:10px;white-space:pre-wrap}.info-note{font-size:12px;color:var(--muted);line-height:1.65;padding:5px 0;max-width:115ch}.inline-note{color:var(--muted);font-size:12px}
.table-scroll{overflow:auto;min-height:80px;flex:1;border:1px solid var(--border);background:#fff;position:relative}.data-table{border-collapse:separate;border-spacing:0;width:100%;font-size:12px;white-space:nowrap;text-align:left;font-variant-numeric:tabular-nums}.data-table th{position:sticky;top:0;z-index:2;background:#eef1f5;color:#303d4c;font-weight:500;border-bottom:1px solid #bac4cf;border-right:1px solid #d5dbe2;height:28px;padding:3px 8px;white-space:nowrap}.data-table th button{font:inherit;border:0;background:transparent;padding:0;min-height:20px;display:flex;align-items:center;gap:6px;width:100%;text-align:left}.data-table th .sort-mark{color:#506a85;font-size:10px;min-width:8px}.data-table td{border-bottom:1px solid #e4e8ed;border-right:1px solid #eef0f3;padding:2px 7px;height:29px;max-width:300px;overflow:hidden;text-overflow:ellipsis}.data-table tr:nth-child(even)>td{background:#fafbfc}.data-table tr:hover>td{background:#f0f5fa}.data-table tr[aria-selected=true]>td{background:#dfecfa}.data-table td.number{text-align:right}.data-table td.cell-edit{padding:2px 4px;overflow:visible}.data-table td.cell-edit input[type=number]{min-height:24px;height:24px;width:76px;font-size:12px}.data-table td.cell-edit select{min-height:24px;height:24px;font-size:12px;max-width:220px}.data-table td.cell-edit input[type=text]{min-height:24px;width:140px;font-size:12px}.data-table .selection-cell{width:29px;min-width:29px;text-align:center;padding:0 5px;position:sticky;left:0;z-index:1}.data-table th.selection-cell{z-index:3}.data-table .cell-wrap{white-space:normal;min-width:190px;line-height:1.5}.data-table .cell-ellipsis{max-width:260px}.data-table .cell-boolean{color:#176331}.table-footer{display:flex;gap:12px;align-items:center;min-height:20px;font-size:12px;color:var(--muted)}.table-footer>button{margin-left:auto}.grouped-tables{display:flex;flex-direction:column;gap:5px;overflow:auto;flex:1;min-height:100px}.table-group{border:1px solid var(--border);background:#fff}.table-group>summary{cursor:pointer;font-weight:600;font-size:12px;padding:7px 9px;background:#eef1f5;position:sticky;top:0;z-index:3}.table-group>summary small{font-weight:400;color:var(--muted);margin-left:10px}.table-group .table-scroll{border:0;max-height:410px}.table-group .data-table th{top:0}.table-group .table-footer{padding:3px 8px}
.policy-form{display:flex;flex-direction:column;gap:9px;flex-shrink:0}.form-section{margin:0;border:1px solid #d6dce3;padding:7px 10px 10px;min-width:0}.form-section legend{font-size:12px;font-weight:600;padding:0 5px;color:#344458}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(270px,1fr));gap:7px 22px;max-width:1100px}.field{display:flex;align-items:center;gap:8px;min-width:0;font-size:12px}.field>.field-label{min-width:135px;flex:0 1 195px;line-height:1.5}.field>.field-input{flex:1;min-width:0;max-width:310px}.field input[type=number].field-input{max-width:130px}.field.checkbox-field{min-height:27px}.field-help{font-size:12px;color:var(--muted);line-height:1.5;display:block;grid-column:1/-1}.field-wide{grid-column:1/-1}.field.invalid input{border-color:var(--danger)}.field[data-dirty=true] .field-label::after{content:" ·";color:#805300}.inline-editor{display:inline-flex;align-items:center;gap:3px}.multi-select{display:flex;flex-wrap:wrap;gap:4px 12px;padding:4px 0;min-width:0}.multi-select label{display:inline-flex;align-items:center;gap:2px}.member-selects{display:flex;gap:3px;flex-wrap:wrap;align-items:center}.member-selects select{width:165px}.member-selects button{min-height:24px}.login-layout{max-width:790px;display:flex;flex-direction:column;gap:10px;padding:4px 8px}.login-layout .form-grid{grid-template-columns:1fr}.login-layout input[type=text],.login-layout input[type=password]{width:320px;max-width:100%}.login-layout .field>.field-label{flex-basis:145px;min-width:145px}.login-layout .field>.field-input{max-width:none}.login-options{display:flex;gap:14px;margin-left:153px;font-size:12px}.login-actions{display:flex;gap:6px;margin-left:153px;flex-wrap:wrap}.server-row{display:flex;gap:6px;flex:1;min-width:0}.server-row select{min-width:180px;flex:1}.session-block{margin-top:4px;padding-top:14px;border-top:1px solid var(--border)}.demo-note{font-size:12px;color:#805300;background:#fff9ea;border:1px solid #e1d0a7;padding:6px 9px;line-height:1.6}.detail-list{display:grid;grid-template-columns:max-content 1fr;gap:6px 18px;font-size:12px}.detail-list dt{color:var(--muted)}.detail-list dd{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}.detail-sections{display:flex;flex-direction:column;gap:12px}.statistics-layout{display:flex;gap:9px;min-height:180px;flex:1}.statistics-picker{width:260px;flex-shrink:0;overflow:auto;border:1px solid var(--border)}.statistics-picker button{display:block;border:0;border-radius:0;width:100%;text-align:left;overflow:hidden;text-overflow:ellipsis;font-size:12px}.statistics-picker button[aria-selected=true]{background:var(--tint);color:#174d83}.statistics-main{min-width:0;flex:1;display:flex;flex-direction:column;gap:8px}.chart-scroll{min-height:120px;max-height:310px;overflow:auto;border:1px solid var(--border);padding:8px}.drop-chart{display:block;min-width:450px;width:100%;height:auto}.chart-label{font-size:12px;fill:#344458}.chart-value{font-size:11px;fill:#344458;font-variant-numeric:tabular-nums}.chart-bar{fill:#4979a4}.chart-grid{stroke:#e3e7ed;stroke-width:1}
.log-resizer{height:7px;min-height:7px;cursor:row-resize;background:#e3e7ec;position:relative;border-top:1px solid #b8c1cb;border-bottom:1px solid #c8d0d9}.log-resizer::after{content:"";position:absolute;width:34px;height:2px;background:#8f9ba8;left:calc(50% - 17px);top:2px}.log-resizer:hover{background:#cedbe9}.log-panel{height:var(--log-height);min-height:64px;max-height:55vh;display:flex;flex-direction:column;background:#fff}.log-toolbar{display:flex;gap:13px;align-items:center;padding:3px 8px;background:#f1f3f5;border-bottom:1px solid var(--border);min-height:29px;font-size:12px}.log-toolbar strong{font-weight:600}.log-toolbar label{display:flex;align-items:center;gap:2px}.log-lines{padding:4px 9px;overflow:auto;flex:1;font:12px/1.65 Consolas,"Microsoft YaHei UI",monospace;white-space:pre-wrap;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.log-entry{min-height:19px}.log-entry .log-time{color:#6a7480;margin-right:8px}.log-entry.error{color:#99251e}.log-entry.warning{color:#805300}.log-entry.debug{color:#55616e}.status-bar{min-height:24px;display:flex;align-items:center;gap:14px;padding:3px 8px;border-top:1px solid var(--border);background:#f1f3f5;font-size:12px;overflow:hidden;white-space:nowrap}.status-bar #status-text{overflow:hidden;text-overflow:ellipsis;max-width:50vw}.status-bar #job-status{overflow:hidden;text-overflow:ellipsis}.notice{position:fixed;right:16px;bottom:35px;max-width:min(540px,calc(100vw - 32px));background:#eef5fc;color:#1d456d;border:1px solid #99b5d1;padding:10px 14px;z-index:80;box-shadow:0 4px 14px #1b2d4326;font-size:13px;line-height:1.5;white-space:pre-wrap}.notice.error{background:#fff2f0;border-color:#d2aaa5;color:#99251e}dialog{border:1px solid #a4afbb;border-radius:5px;padding:0;max-width:min(740px,calc(100vw - 28px));width:560px;max-height:88dvh;background:#fff;color:#202832;box-shadow:0 12px 44px #172a4040}dialog::backdrop{background:#152d493d}dialog>form{display:flex;flex-direction:column;max-height:85dvh}.dialog-header{display:flex;align-items:center;gap:12px;padding:10px 14px;border-bottom:1px solid var(--border);background:#f4f6f8}.dialog-close{margin-left:auto;border:0;background:transparent;padding:0 5px;font-size:22px;line-height:1}.dialog-content{padding:14px;overflow:auto;display:flex;flex-direction:column;gap:12px;min-height:40px}.dialog-content p{font-size:13px;white-space:pre-wrap;overflow-wrap:anywhere}.dialog-content .field{align-items:flex-start}.dialog-content .field input{flex:1;min-width:0}.dialog-content .form-grid{grid-template-columns:1fr}.dialog-footer{display:flex;justify-content:flex-end;gap:7px;padding:10px 14px;border-top:1px solid var(--border);background:#f6f7f9}#dialog-error{padding:0 14px 10px}#auth-dialog{width:370px;padding:18px}#auth-dialog form{gap:13px}#auth-dialog .dialog-footer{margin:0 -18px -18px}#auth-dialog .field{display:flex;flex-direction:column;align-items:stretch;gap:6px}.context-menu{position:fixed;z-index:50;background:#fff;border:1px solid #acb6c1;box-shadow:0 5px 14px #172a4026;padding:4px;min-width:190px}.context-menu button{display:block;width:100%;text-align:left;background:transparent;border:0;border-radius:0;padding:5px 10px}.context-menu button:hover{background:var(--tint)}
@media(min-width:1450px){.toolbar{gap:22px}.player-line{gap:18px}.page-tab{padding-left:13px;padding-right:13px}.form-grid{grid-template-columns:repeat(3,minmax(240px,1fr));max-width:1450px}.login-layout .form-grid{grid-template-columns:1fr}}
@media(max-width:1000px){.window-title{display:none}.toolbar{gap:5px}.run-controls{width:100%}.player-line{gap:10px}.page-tab{padding-left:8px;padding-right:8px}.form-grid{grid-template-columns:repeat(2,minmax(240px,1fr))}.statistics-picker{width:220px}}
@media(max-width:650px){:root{--log-height:120px}.workbench{min-width:340px}.window-header{gap:5px}.menu>summary{padding:5px 7px}.access-key{display:none}#access-mode{font-size:11px}.toolbar{padding:6px}.player-line{gap:7px 10px}.player-line>strong{max-width:135px}.experience progress{display:none}.run-controls{gap:4px}.run-controls>button{padding-left:7px;padding-right:7px;font-size:12px}.form-grid{grid-template-columns:1fr}.field>.field-label{min-width:120px}.field-wide{grid-column:auto}.login-layout{padding:3px}.login-layout .field{align-items:stretch;flex-direction:column;gap:4px}.login-layout .field>.field-label{flex-basis:auto;min-width:0}.login-layout input[type=text],.login-layout input[type=password]{width:100%}.login-options,.login-actions{margin-left:0}.server-row{flex-wrap:wrap}.statistics-layout{flex-direction:column}.statistics-picker{width:100%;max-height:130px}.log-toolbar{gap:7px}#download-log{display:none}.status-bar{gap:8px}.status-bar #game-version{display:none}dialog .field{flex-direction:column;align-items:stretch}dialog .field-label{flex-basis:auto}#save-status{max-width:160px;overflow:hidden;text-overflow:ellipsis}}
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important}}
.page-content{display:flex;flex-direction:column;gap:7px;flex:1;min-height:0}.statistics-table-host{display:flex;flex-direction:column;flex:1;min-height:100px}.count-id{width:100px}.statistics-city>summary,.statistics-stage>summary{cursor:pointer;font-size:12px;padding:6px 7px;line-height:1.5;overflow-wrap:anywhere}.statistics-city>summary{background:#eef1f5;border-bottom:1px solid #d8dee6;font-weight:600}.statistics-stage{margin-left:10px}.statistics-stage>summary:hover{background:#edf3fa}.statistics-levels{padding-left:12px}.statistics-levels button{padding:5px 8px}.debug-json{margin:0;font:12px/1.6 Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere}.log-entry.inspectable{cursor:pointer}.log-entry.inspectable:hover{background:#e8f0f9}.member-draft-note{font-size:11px;color:#805300}.counts-lines{display:flex;flex-direction:column;gap:3px;margin-bottom:4px}
.chart-axis{font-size:11px;fill:#55616e;font-variant-numeric:tabular-nums}
+43 -172
View File
@@ -11,24 +11,17 @@ export function editPath(template, row) {
}); });
} }
function columnEdit(column, row) {
return row.edits?.[column.key] ? {...column.edit, ...row.edits[column.key]} : column.edit;
}
function editableSpec(column, row) { function editableSpec(column, row) {
const edit = columnEdit(column, row); const edit = column.edit || row.edits?.[column.key] ? {...column.edit, ...row.edits?.[column.key]} : null;
if (!edit) return null; if (!edit) return null;
return {...edit, path: editPath(edit.path, row), label: `${column.label} · ${row.name || row.label || row.id}`, return {...edit, path: editPath(edit.path, row), label: `${column.label} · ${row.name || row.label || row.id}`,
options: row[edit.options_key] || row[`${column.key}_options`] || edit.options, options: row[edit.options_key] || row[`${column.key}_options`] || edit.options,
disabled: edit.disabled || row[`${column.key}_disabled`] || row.editable === false}; disabled: edit.disabled || row[`${column.key}_disabled`] || row.editable === false};
} }
function createCellControl(spec, getRow, context, key) { function createCellControl(spec, row, context, key) {
const get = (path, fallback) => context.get(path, fallback ?? getRow()[key]); const get = (path, fallback) => context.get(path, fallback ?? row[key]);
const set = (path, value, field) => { const set = (path, value, field) => context.set(path, value, field, row);
try { context.set(path, value, field, getRow()); }
catch (error) { context.onError?.(error); }
};
const target = ['target', 'priority_target', 'target_priority'].includes(spec.type); const target = ['target', 'priority_target', 'target_priority'].includes(spec.type);
if (target) { if (target) {
const checkbox = el('input', {type: 'checkbox', 'aria-label': spec.label}); const checkbox = el('input', {type: 'checkbox', 'aria-label': spec.label});
@@ -37,7 +30,7 @@ function createCellControl(spec, getRow, context, key) {
checkbox.addEventListener('change', () => set(spec.path, checkbox.checked ? spec.default || 100 : undefined, spec)); checkbox.addEventListener('change', () => set(spec.path, checkbox.checked ? spec.default || 100 : undefined, spec));
const sync = () => { const sync = () => {
const current = context.get(spec.path); const current = context.get(spec.path);
if (document.activeElement !== checkbox) checkbox.checked = current !== undefined && current !== null && current !== false && current !== 0; checkbox.checked = current !== undefined && current !== null && current !== false && current !== 0;
checkbox.disabled = Boolean(spec.disabled); checkbox.disabled = Boolean(spec.disabled);
}; };
sync(); sync();
@@ -45,7 +38,7 @@ function createCellControl(spec, getRow, context, key) {
} }
if (['members', 'monster_list', 'team_members'].includes(spec.type)) { if (['members', 'monster_list', 'team_members'].includes(spec.type)) {
const root = el('div', {class: 'member-selects', 'data-config-path': pathKey(spec.path)}); const root = el('div', {class: 'member-selects', 'data-config-path': pathKey(spec.path)});
const options = optionsList(spec.options || getRow().member_options || getRow().members_options || []); const options = optionsList(spec.options || row.member_options || row.members_options || []);
let drafting=false; let drafting=false;
const hint=el('span',{class:'member-draft-note',hidden:true}); const hint=el('span',{class:'member-draft-note',hidden:true});
const selects = Array.from({length: spec.count || 3}, (_, index) => { const selects = Array.from({length: spec.count || 3}, (_, index) => {
@@ -76,16 +69,13 @@ function createCellControl(spec, getRow, context, key) {
selects.forEach((select, index) => { if (document.activeElement !== select) select.value = String(selected[index] ?? ''); }); selects.forEach((select, index) => { if (document.activeElement !== select) select.value = String(selected[index] ?? ''); });
}; };
sync(); sync();
return {root, sync, field: spec, isDrafting: () => drafting}; return {root, sync, field: spec};
} }
return control(spec, {get, set, onError: context.onError}); return control(spec, {get, set, onError: context.onError});
} }
const rowId = (row, index) => String(row.id ?? index);
const collator = new Intl.Collator('zh-CN', {numeric: true});
export class DataTable { export class DataTable {
constructor(host, context, {selection = true, emptyMessage = '当前筛选下没有条目。', pageSize = 50} = {}) { constructor(host, context, {selection = true, emptyMessage = '当前筛选下没有条目。'} = {}) {
this.host = host; this.host = host;
this.context = context; this.context = context;
this.selection = selection; this.selection = selection;
@@ -94,107 +84,43 @@ export class DataTable {
this.nodes = new Map(); this.nodes = new Map();
this.selected = new Set(); this.selected = new Set();
this.sort = null; this.sort = null;
this.page = 1;
this.pageSize = [25, 50, 100].includes(pageSize) ? pageSize : 50;
this.pageCount = 1;
this.table = el('table', {class: 'data-table'}); this.table = el('table', {class: 'data-table'});
this.head = el('thead'); this.head = el('thead');
this.body = el('tbody'); this.body = el('tbody');
this.table.append(this.head, this.body); this.table.append(this.head, this.body);
this.empty = el('div', {class: 'empty-state', text: emptyMessage}); this.empty = el('div', {class: 'empty-state', text: emptyMessage});
this.scroller = el('div', {class: 'table-scroll'}, this.table, this.empty); this.scroller = el('div', {class: 'table-scroll'}, this.table, this.empty);
this.footer = el('nav', {class: 'table-footer table-pagination', 'aria-label': '表格分页'}); this.footer = el('div', {class: 'table-footer'});
this.count = el('span', {class: 'table-pagination-summary', role: 'status', 'aria-live': 'polite', 'aria-atomic': 'true'}); this.count = el('span');
this.selectionCount = el('span', {class: 'table-selection-summary', role: 'status', 'aria-live': 'polite', hidden: !selection}); this.selectionCount = el('span');
this.sizeSelect = el('select', {'aria-label': '每页条目数'}, ...[25, 50, 100].map(size => el('option', {value: size, text: size}))); this.footer.append(this.count, this.selectionCount);
this.sizeSelect.value = String(this.pageSize);
this.sizeSelect.addEventListener('change', () => {
const size = Number(this.sizeSelect.value);
if (![25, 50, 100].includes(size)) return;
const first = (this.page - 1) * this.pageSize;
this.pageSize = size;
this.setPage(Math.floor(first / size) + 1);
});
this.firstPage = el('button', {type: 'button', text: '首页', onClick: () => this.setPage(1)});
this.previousPage = el('button', {type: 'button', text: '上一页', onClick: () => this.setPage(this.page - 1)});
this.nextPage = el('button', {type: 'button', text: '下一页', onClick: () => this.setPage(this.page + 1)});
this.lastPage = el('button', {type: 'button', text: '末页', onClick: () => this.setPage(this.pageCount)});
this.pageInput = el('input', {type: 'number', min: 1, step: 1, value: 1, 'aria-label': '当前页码'});
this.pageInput.addEventListener('input', () => this.pageInput.setCustomValidity(''));
this.pageInput.addEventListener('change', () => {
const page = Number(this.pageInput.value);
if (!Number.isInteger(page) || page < 1 || page > this.pageCount) {
this.pageInput.setCustomValidity(`请输入 1 到 ${this.pageCount} 之间的页码`);
this.pageInput.reportValidity();
return;
}
this.setPage(page);
});
this.pageInput.addEventListener('blur', () => {
this.pageInput.setCustomValidity('');
this.pageInput.value = String(this.page);
});
this.pageTotal = el('span');
this.footer.append(this.count, this.selectionCount,
el('label', {class: 'table-page-size'}, '每页', this.sizeSelect, '项'),
el('div', {class: 'table-page-controls'}, this.firstPage, this.previousPage,
el('label', {class: 'table-page-current'}, '第', this.pageInput, this.pageTotal), this.nextPage, this.lastPage));
if (selection) {
this.selectFiltered = el('button', {type: 'button', onClick: () => {
this.rows.forEach((row, index) => this.selected.add(rowId(row, index)));
this.syncSelection();
}});
this.clearSelection = el('button', {type: 'button', text: '清除选择', onClick: () => { this.selected.clear(); this.syncSelection(); }});
this.footer.append(el('div', {class: 'table-selection-controls'}, this.selectFiltered, this.clearSelection));
}
host.append(this.scroller, this.footer); host.append(this.scroller, this.footer);
this.onFocusOut = () => queueMicrotask(() => {
if (this.pendingRender && !this.destroyed) this.update(this.columns, this.rows);
});
this.table.addEventListener('focusout', this.onFocusOut);
this.table.addEventListener('contextmenu', event => { this.table.addEventListener('contextmenu', event => {
const tr = event.target.closest('tr[data-row-id]'); const tr = event.target.closest('tr[data-row-id]');
if (!tr) return; if (!tr) return;
event.preventDefault(); event.preventDefault();
const id = tr.dataset.rowId; const id = tr.dataset.rowId;
if (this.selection && !this.selected.has(id)) { if (!this.selected.has(id)) {
this.selected.clear(); this.selected.clear();
this.selected.add(id); this.selected.add(id);
this.syncSelection(); this.syncSelection();
} }
context.onContext?.(event, this.selectedRows(), this.rowById.get(id)); context.onContext?.(event, this.selectedRows(), this.rows.find(row => String(row.id) === id));
}); });
} }
selectedRows() { return this.rows.filter((row, index) => this.selected.has(rowId(row, index))); } selectedRows() { return this.rows.filter(row => this.selected.has(String(row.id))); }
setPage(page) {
if (this.body.contains(document.activeElement)) document.activeElement.blur();
this.page = Math.max(1, Math.min(Math.max(1, Math.ceil(this.rows.length / this.pageSize)), page));
this.update(this.columns, this.rows);
this.scroller.scrollTop = 0;
}
syncSelection() { syncSelection() {
for (const [id, item] of this.nodes) { for (const [id, item] of this.nodes) {
item.tr.setAttribute('aria-selected', String(this.selected.has(id))); item.tr.setAttribute('aria-selected', String(this.selected.has(id)));
if (item.check) item.check.checked = this.selected.has(id); if (item.check) item.check.checked = this.selected.has(id);
} }
const selectionText = this.selected.size ? `已选择 ${this.selected.size} 项(含其他分页)` : ''; this.selectionCount.textContent = this.selected.size ? `已选择 ${this.selected.size} 项` : '';
if (this.selectionCount.textContent !== selectionText) this.selectionCount.textContent = selectionText;
if (this.allCheck) { if (this.allCheck) {
const ids = [...this.nodes.keys()]; const selected = this.rows.filter(row => this.selected.has(String(row.id))).length;
const selected = ids.filter(id => this.selected.has(id)).length; this.allCheck.checked = selected > 0 && selected === this.rows.length;
this.allCheck.checked = selected > 0 && selected === ids.length; this.allCheck.indeterminate = selected > 0 && selected < this.rows.length;
this.allCheck.indeterminate = selected > 0 && selected < ids.length;
this.allCheck.disabled = !ids.length;
this.allCheck.setAttribute('aria-label', `选择本页全部 ${ids.length} 项`);
this.allCheck.title = `仅选择本页 ${ids.length} 项;其他分页的选择保持不变`;
}
if (this.selectFiltered) {
this.selectFiltered.textContent = `全选筛选结果(${this.rows.length} 项,含其他分页)`;
this.selectFiltered.disabled = !this.rows.length || this.selected.size === this.rows.length;
this.clearSelection.disabled = !this.selected.size;
} }
this.context.onSelection?.(this.selectedRows()); this.context.onSelection?.(this.selectedRows());
} }
@@ -205,9 +131,10 @@ export class DataTable {
this.body.replaceChildren(); this.body.replaceChildren();
const row = el('tr'); const row = el('tr');
if (this.selection) { if (this.selection) {
this.allCheck = el('input', {type: 'checkbox', 'aria-label': '选择本页全部条目'}); this.allCheck = el('input', {type: 'checkbox', 'aria-label': '选择当前表格全部条目'});
this.allCheck.addEventListener('change', () => { this.allCheck.addEventListener('change', () => {
this.nodes.forEach((_, id) => this.allCheck.checked ? this.selected.add(id) : this.selected.delete(id)); this.selected.clear();
if (this.allCheck.checked) this.rows.forEach(item => this.selected.add(String(item.id)));
this.syncSelection(); this.syncSelection();
}); });
row.append(el('th', {scope: 'col', class: 'selection-cell'}, this.allCheck)); row.append(el('th', {scope: 'col', class: 'selection-cell'}, this.allCheck));
@@ -220,7 +147,6 @@ export class DataTable {
if (column.width) th.style.minWidth = `${Number(column.width)}px`; if (column.width) th.style.minWidth = `${Number(column.width)}px`;
button.addEventListener('click', () => { button.addEventListener('click', () => {
this.sort = {key: column.key, direction: this.sort?.key === column.key && this.sort.direction === 1 ? -1 : 1}; this.sort = {key: column.key, direction: this.sort?.key === column.key && this.sort.direction === 1 ? -1 : 1};
this.page = 1;
this.update(this.columns, this.rows); this.update(this.columns, this.rows);
}); });
row.append(th); row.append(th);
@@ -228,54 +154,30 @@ export class DataTable {
this.head.append(row); this.head.append(row);
} }
setRows(rows) {
this.rows = rows;
this.rowById = new Map(rows.map((row, index) => [rowId(row, index), row]));
for (const id of this.selected) if (!this.rowById.has(id)) this.selected.delete(id);
}
update(columns = [], rows = []) { update(columns = [], rows = []) {
if (this.destroyed) return;
this.columns = columns;
this.setRows(rows);
const focusedId = this.body.contains(document.activeElement) ? document.activeElement.closest('tr[data-row-id]')?.dataset.rowId : undefined;
const keepFocus = focusedId !== undefined && this.rowById.has(focusedId);
const signature = JSON.stringify(columns); const signature = JSON.stringify(columns);
if (this.signature !== signature && !keepFocus) { if (this.signature !== signature) {
if (this.host.contains(document.activeElement) && this.signature) return;
this.columns = columns;
this.signature = signature; this.signature = signature;
this.renderedColumns = columns;
this.buildHead(columns); this.buildHead(columns);
} }
if (this.sort && !columns.some(column => column.key === this.sort.key)) this.sort = null; this.rows = rows;
const sorted = rows.map((row, index) => ({row, id: rowId(row, index), index})); const active = new Set(rows.map(row => String(row.id)));
for (const [id, node] of this.nodes) {
if (!active.has(id) && !node.tr.contains(document.activeElement)) { node.tr.remove(); this.nodes.delete(id); this.selected.delete(id); }
}
const sorted = [...rows];
if (this.sort) { if (this.sort) {
const column = columns.find(column => column.key === this.sort.key); const {key, direction} = this.sort;
sorted.forEach(item => { item.value = this.sortValue(column, item.row); });
sorted.sort((a, b) => { sorted.sort((a, b) => {
const difference = typeof a.value === 'number' && typeof b.value === 'number' const aValue = a[key], bValue = b[key];
? a.value - b.value : collator.compare(textValue(a.value), textValue(b.value)); if (typeof aValue === 'number' && typeof bValue === 'number') return (aValue - bValue) * direction;
return difference * this.sort.direction || a.index - b.index; return textValue(aValue).localeCompare(textValue(bValue), 'zh-CN', {numeric: true}) * direction;
}); });
} }
this.pageCount = Math.max(1, Math.ceil(rows.length / this.pageSize)); sorted.forEach((row, index) => {
this.page = Math.min(this.page, this.pageCount); const id = String(row.id ?? index);
let visible = sorted.slice((this.page - 1) * this.pageSize, this.page * this.pageSize);
const currentIds = [...this.body.children].map(tr => tr.dataset.rowId);
const orderChanged = visible.length !== currentIds.length || visible.some((item, index) => item.id !== currentIds[index]);
this.pendingRender = keepFocus && (orderChanged || signature !== this.signature);
if (this.pendingRender) {
// Hold the current arrangement until focus leaves. Deleted rows still leave
// immediately, and the retained editors always stay within the page limit.
const retained = currentIds.filter(id => this.rowById.has(id)).slice(0, this.pageSize);
const retainedIds = new Set(retained);
visible = [...retained.map(id => ({id, row: this.rowById.get(id)})),
...visible.filter(item => !retainedIds.has(item.id)).slice(0, this.pageSize - retained.length)];
}
const visibleIds = new Set(visible.map(item => item.id));
for (const [id, node] of this.nodes) {
if (!visibleIds.has(id)) { node.tr.remove(); this.nodes.delete(id); }
}
visible.forEach(({row, id}, index) => {
let node = this.nodes.get(id); let node = this.nodes.get(id);
if (!node) { if (!node) {
const tr = el('tr', {'data-row-id': id, 'aria-selected': 'false', tabindex: -1}); const tr = el('tr', {'data-row-id': id, 'aria-selected': 'false', tabindex: -1});
@@ -285,7 +187,7 @@ export class DataTable {
tr.append(el('td', {class: 'selection-cell'}, check)); tr.append(el('td', {class: 'selection-cell'}, check));
} }
tr.addEventListener('click', event => { tr.addEventListener('click', event => {
if (!this.selection || event.target.closest('input,select,textarea,button,a,label')) return; if (event.target.closest('input,select,button,a,label')) return;
if (!event.ctrlKey && !event.metaKey && !event.shiftKey) this.selected.clear(); if (!event.ctrlKey && !event.metaKey && !event.shiftKey) this.selected.clear();
this.selected.add(id); this.selected.add(id);
this.syncSelection(); this.syncSelection();
@@ -297,8 +199,7 @@ export class DataTable {
this.nodes.set(id, node); this.nodes.set(id, node);
} }
node.row = row; node.row = row;
if (node.check) node.check.setAttribute('aria-label', `选择 ${row.name || row.label || id}`); columns.forEach(column => {
this.renderedColumns.forEach(column => {
let cell = node.cells.get(column.key); let cell = node.cells.get(column.key);
if (!cell) { if (!cell) {
const td = el('td', {'data-column': column.key}); const td = el('td', {'data-column': column.key});
@@ -309,18 +210,14 @@ export class DataTable {
const spec = editableSpec(column, row); const spec = editableSpec(column, row);
if (spec) { if (spec) {
const controlSignature = JSON.stringify(spec); const controlSignature = JSON.stringify(spec);
if (!cell.control || cell.controlSignature !== controlSignature && !cell.td.contains(document.activeElement) && !cell.control.isDrafting?.()) { if (!cell.control || cell.controlSignature !== controlSignature && !cell.td.contains(document.activeElement)) {
cell.control = createCellControl(spec, () => node.row, this.context, column.key); cell.control = createCellControl(spec, row, this.context, column.key);
cell.controlSignature = controlSignature; cell.controlSignature = controlSignature;
cell.td.replaceChildren(cell.control.root); cell.td.replaceChildren(cell.control.root);
cell.td.className = 'cell-edit'; cell.td.className = 'cell-edit';
} }
if (cell.controlSignature !== controlSignature) this.pendingRender = true;
cell.control?.sync(); cell.control?.sync();
} else { } else {
if (cell.td.contains(document.activeElement)) { this.pendingRender = true; return; }
cell.control = null;
cell.controlSignature = null;
const value = row[column.key]; const value = row[column.key];
const text = typeof value==='number'?number(value):textValue(value); const text = typeof value==='number'?number(value):textValue(value);
if (cell.td.textContent !== text) cell.td.textContent = text; if (cell.td.textContent !== text) cell.td.textContent = text;
@@ -334,15 +231,7 @@ export class DataTable {
}); });
this.empty.hidden = Boolean(rows.length); this.empty.hidden = Boolean(rows.length);
this.table.hidden = !columns.length; this.table.hidden = !columns.length;
const first = rows.length ? (this.page - 1) * this.pageSize + 1 : 0; this.count.textContent = `共 ${rows.length} 项`;
const last = rows.length ? Math.min(rows.length, first + visible.length - 1) : 0;
const countText = `共 ${rows.length} 项,显示 ${first}–${last} 项${this.pendingRender ? ';编辑完成后更新排列' : ''}`;
if (this.count.textContent !== countText) this.count.textContent = countText;
this.firstPage.disabled = this.previousPage.disabled = this.page === 1;
this.nextPage.disabled = this.lastPage.disabled = this.page === this.pageCount;
this.pageInput.max = String(this.pageCount);
if (document.activeElement !== this.pageInput) this.pageInput.value = String(this.page);
this.pageTotal.textContent = `页 / 共 ${this.pageCount} 页`;
for (const th of this.head.querySelectorAll('[data-column]')) { for (const th of this.head.querySelectorAll('[data-column]')) {
const activeSort = this.sort?.key === th.dataset.column; const activeSort = this.sort?.key === th.dataset.column;
th.setAttribute('aria-sort', activeSort ? this.sort.direction === 1 ? 'ascending' : 'descending' : 'none'); th.setAttribute('aria-sort', activeSort ? this.sort.direction === 1 ? 'ascending' : 'descending' : 'none');
@@ -350,22 +239,6 @@ export class DataTable {
} }
this.syncSelection(); this.syncSelection();
} }
sortValue(column, row) {
const edit = columnEdit(column, row);
const value = edit ? this.context.get(editPath(edit.path, row), ['target', 'priority_target', 'target_priority'].includes(edit.type) ? undefined : edit.value ?? row[column.key]) : row[column.key];
if (['target', 'priority_target', 'target_priority'].includes(edit?.type)) return Number(value !== undefined && value !== null && value !== false && value !== 0);
const type = edit?.type || column.type;
if (['boolean', 'bool', 'checkbox'].includes(type)) return Number(Boolean(value));
if (['integer', 'int', 'number', 'float', 'priority'].includes(type) && value !== '' && value != null && Number.isFinite(Number(value))) return Number(value);
return value;
}
destroy() {
this.destroyed = true;
this.table.removeEventListener('focusout', this.onFocusOut);
this.nodes.clear();
}
} }
export class GroupedTables { export class GroupedTables {
@@ -384,7 +257,7 @@ export class GroupedTables {
if (!grouped.has(key)) grouped.set(key, []); if (!grouped.has(key)) grouped.set(key, []);
grouped.get(key).push(row); grouped.get(key).push(row);
}); });
for (const [key, group] of this.groups) if (!grouped.has(key)) { group.table?.destroy(); group.root.remove(); this.groups.delete(key); } for (const [key, group] of this.groups) if (!grouped.has(key)) { group.root.remove(); this.groups.delete(key); }
grouped.forEach((items, key) => { grouped.forEach((items, key) => {
let group = this.groups.get(key); let group = this.groups.get(key);
if (!group) { if (!group) {
@@ -402,7 +275,6 @@ export class GroupedTables {
group.summary.replaceChildren(document.createTextNode(labels[key] || key), el('small', {text: `${items.length} 项`})); group.summary.replaceChildren(document.createTextNode(labels[key] || key), el('small', {text: `${items.length} 项`}));
group.columns=columns;group.items=items; group.columns=columns;group.items=items;
if(group.root.open)this.renderGroup(group); if(group.root.open)this.renderGroup(group);
else if(group.table) { group.table.setRows(items); group.table.syncSelection(); }
}); });
if (!grouped.size) { if (!grouped.size) {
if (!this.empty) { this.empty = el('div', {class: 'empty-state', text: '当前筛选下没有条目。'}); this.host.append(this.empty); } if (!this.empty) { this.empty = el('div', {class: 'empty-state', text: '当前筛选下没有条目。'}); this.host.append(this.empty); }
@@ -417,5 +289,4 @@ export class GroupedTables {
expand(open) { this.groups.forEach(group => { group.root.open = open; }); } expand(open) { this.groups.forEach(group => { group.root.open = open; }); }
selectedRows() { return [...this.groups.values()].flatMap(group => group.table?.selectedRows() || []); } selectedRows() { return [...this.groups.values()].flatMap(group => group.table?.selectedRows() || []); }
destroy() { this.groups.forEach(group => group.table?.destroy()); this.groups.clear(); }
} }
@@ -6,7 +6,6 @@ Only temporary demo accounts and a synthetic administrator password are used.
from __future__ import annotations from __future__ import annotations
import json import json
import re
from pathlib import Path from pathlib import Path
import socket import socket
import tempfile import tempfile
@@ -14,9 +13,8 @@ import threading
import time import time
import unittest import unittest
from unittest.mock import patch from unittest.mock import patch
from urllib.parse import urlsplit
from .test_workbench_browser import AVAILABLE, EDGE, OfflineUpdates, assert_navigation from .test_workbench_browser import AVAILABLE, EDGE, OfflineUpdates
if AVAILABLE: if AVAILABLE:
from playwright.sync_api import expect from playwright.sync_api import expect
@@ -83,11 +81,9 @@ class AdminLoginBrowserTests(unittest.TestCase):
self.context.route("**/*", offline_only) self.context.route("**/*", offline_only)
self.page = self.context.new_page() self.page = self.context.new_page()
self.requests = [] self.requests = []
self.script_requests = []
self.errors = [] self.errors = []
self.csp_errors = [] self.csp_errors = []
self.page.on("request", lambda request: self.requests.append(request.url)) self.page.on("request", lambda request: self.requests.append(request.url))
self.page.on("request", lambda request: self.script_requests.append(request.url) if request.resource_type == "script" else None)
self.page.on("pageerror", lambda failure: self.errors.append(str(failure))) self.page.on("pageerror", lambda failure: self.errors.append(str(failure)))
self.page.on("console", lambda message: self.csp_errors.append(message.text) self.page.on("console", lambda message: self.csp_errors.append(message.text)
if message.type == "error" and ("security policy" in message.text.lower() or "csp" in message.text.lower()) else None) if message.type == "error" and ("security policy" in message.text.lower() or "csp" in message.text.lower()) else None)
@@ -102,7 +98,7 @@ class AdminLoginBrowserTests(unittest.TestCase):
expect(page).to_have_url(self.base + "/login") expect(page).to_have_url(self.base + "/login")
expect(page.locator("#auth-form")).to_be_visible() expect(page.locator("#auth-form")).to_be_visible()
expect(page.locator("#admin-password")).to_be_enabled() expect(page.locator("#admin-password")).to_be_enabled()
self.assertEqual(page.locator("#app, nav, #sidebar, #topbar, #account-select, #account-tabs, #page-tabs, #page-host, #auth-dialog").count(), 0) self.assertEqual(page.locator("#app, nav, #account-tabs, #page-tabs, #page-host, #auth-dialog").count(), 0)
self.assertEqual(page.locator("script:not([src]), [style], [onclick], [onsubmit]").count(), 0) self.assertEqual(page.locator("script:not([src]), [style], [onclick], [onsubmit]").count(), 0)
self.assertEqual(page.locator("script").count(), 1) self.assertEqual(page.locator("script").count(), 1)
expect(page.locator("script")).to_have_attribute("type", "module") expect(page.locator("script")).to_have_attribute("type", "module")
@@ -116,15 +112,11 @@ class AdminLoginBrowserTests(unittest.TestCase):
self.page.locator('#auth-form button[type="submit"]').click() self.page.locator('#auth-form button[type="submit"]').click()
self.assertEqual(pending.value.status, 200) self.assertEqual(pending.value.status, 200)
self.assertEqual(pending.value.request.post_data_json, {"password": self.password}) self.assertEqual(pending.value.request.post_data_json, {"password": self.password})
expect(self.page).to_have_url(re.compile("^" + re.escape(self.base + "/") + r"(?:#.*)?$")) expect(self.page).to_have_url(self.base + "/")
expect(self.page.locator("#app")).to_be_visible() expect(self.page.locator("#app")).to_be_visible()
assert_navigation(self.page) expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
expect(self.page.locator('.nav-link[data-page="overview"]')).to_have_attribute("aria-current", "page") expect(self.page.locator("#status-text")).to_have_text("工作台已连接")
expect(self.page.locator("#status-text")).to_contain_text("已连接")
self.assertEqual(self.page.locator("#auth-dialog, #auth-form").count(), 0) self.assertEqual(self.page.locator("#auth-dialog, #auth-form").count(), 0)
self.console_assets = self.page.locator('script[src], link[rel="stylesheet"], link[rel="modulepreload"]').evaluate_all(
"nodes => nodes.map(node => node.src || node.href)")
self.assertTrue(self.console_assets)
def observe_login_transition(self): def observe_login_transition(self):
snapshots = [] snapshots = []
@@ -155,16 +147,15 @@ class AdminLoginBrowserTests(unittest.TestCase):
context.add_cookies(cookies) context.add_cookies(cookies)
page = context.new_page() page = context.new_page()
requested = [] requested = []
page.on("request", lambda request: requested.append(request.url) if request.resource_type == "script" else None) page.on("request", lambda request: requested.append(request.url))
page.goto(self.base + "/", wait_until="networkidle") page.goto(self.base + "/", wait_until="networkidle")
self.assert_login_only(page) self.assert_login_only(page)
self.assertEqual(requested, [self.base + "/static/login.js"]) self.assertFalse(any(url.endswith("/static/app.js") for url in requested))
response = context.request.get(self.base + "/static/index.html", max_redirects=0) response = context.request.get(self.base + "/static/index.html", max_redirects=0)
self.assertIn(response.status, (302, 303, 307, 401, 403)) self.assertIn(response.status, (302, 303, 307, 401, 403))
self.assertNotIn('id="app"', response.text()) self.assertNotIn('id="app"', response.text())
for url in self.console_assets: response = context.request.get(self.base + "/static/app.js", max_redirects=0)
response = context.request.get(url, max_redirects=0) self.assertIn(response.status, (302, 303, 307, 401, 403))
self.assertIn(response.status, (302, 303, 307, 401, 403), url)
def test_fresh_root_serves_only_login_and_public_assets_with_csp(self): def test_fresh_root_serves_only_login_and_public_assets_with_csp(self):
response = self.page.goto(self.base + "/", wait_until="networkidle") response = self.page.goto(self.base + "/", wait_until="networkidle")
@@ -178,7 +169,7 @@ class AdminLoginBrowserTests(unittest.TestCase):
self.assertIn(self.base + "/api/auth/status", self.requests) self.assertIn(self.base + "/api/auth/status", self.requests)
scripts = self.page.evaluate("performance.getEntriesByType('resource').filter(item => item.initiatorType === 'script').map(item => new URL(item.name).pathname)") scripts = self.page.evaluate("performance.getEntriesByType('resource').filter(item => item.initiatorType === 'script').map(item => new URL(item.name).pathname)")
self.assertEqual(scripts, ["/static/login.js"]) self.assertEqual(scripts, ["/static/login.js"])
self.assertEqual(self.script_requests, [self.base + "/static/login.js"]) self.assertFalse(any(url.endswith(("/app.js", "/api.js", "/pages.js", "/dom.js", "/ui.js")) for url in self.requests))
for width in (1280, 390): for width in (1280, 390):
self.page.set_viewport_size({"width": width, "height": 800}) self.page.set_viewport_size({"width": width, "height": 800})
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width) self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
@@ -194,10 +185,10 @@ class AdminLoginBrowserTests(unittest.TestCase):
self.assertEqual(self.page.evaluate("localStorage.length + sessionStorage.length"), 0) self.assertEqual(self.page.evaluate("localStorage.length + sessionStorage.length"), 0)
self.assertNotIn(self.password, self.page.url) self.assertNotIn(self.password, self.page.url)
self.page.goto(self.base + "/login", wait_until="networkidle") self.page.goto(self.base + "/login", wait_until="networkidle")
self.assertEqual(urlsplit(self.page.url).path, "/") expect(self.page).to_have_url(self.base + "/")
assert_navigation(self.page) expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
snapshots = self.observe_login_transition() snapshots = self.observe_login_transition()
self.page.locator('.nav-link[data-page="system"]').click() self.page.locator(".menu > summary").first.click()
self.page.locator('[data-command="admin-logout"]').click() self.page.locator('[data-command="admin-logout"]').click()
self.assert_hidden_transition(snapshots) self.assert_hidden_transition(snapshots)
self.assert_login_only() self.assert_login_only()
@@ -216,13 +207,12 @@ class AdminLoginBrowserTests(unittest.TestCase):
expect(self.page.locator("#admin-password")).to_be_focused() expect(self.page.locator("#admin-password")).to_be_focused()
self.assert_login_only() self.assert_login_only()
self.assertEqual(self.page.evaluate("localStorage.length + sessionStorage.length"), 0) self.assertEqual(self.page.evaluate("localStorage.length + sessionStorage.length"), 0)
self.assertFalse(any("offline-wrong-admin-password" in url for url in self.requests)) self.assertFalse(any("offline-wrong-admin-password" in url or url.endswith("/app.js") for url in self.requests))
self.assertEqual(self.script_requests, [self.base + "/static/login.js"])
def test_expired_server_session_hides_workbench_and_rejects_old_cookie(self): def test_expired_server_session_hides_workbench_and_rejects_old_cookie(self):
self.login() self.login()
cookies = self.context.cookies() cookies = self.context.cookies()
self.page.locator('.nav-link[data-page="system"]').click() self.page.locator(".menu > summary").nth(3).click()
self.page.locator('[data-command="about"]').click() self.page.locator('[data-command="about"]').click()
expect(self.page.locator("#action-dialog")).to_be_visible() expect(self.page.locator("#action-dialog")).to_be_visible()
snapshots = self.observe_login_transition() snapshots = self.observe_login_transition()
@@ -243,8 +233,6 @@ class AdminLoginBrowserTests(unittest.TestCase):
route.fulfill(status=401, content_type="application/json", body=json.dumps({"detail": "会话已失效"})) route.fulfill(status=401, content_type="application/json", body=json.dumps({"detail": "会话已失效"}))
self.page.route("**/api/accounts/*/actions/refresh", unauthorized) self.page.route("**/api/accounts/*/actions/refresh", unauthorized)
self.page.locator('.nav-link[data-page="login"]').click()
expect(self.page.locator('.page-panel[data-page="login"]:not([hidden]) .page-loading[data-loading="false"]')).to_have_count(1)
self.page.locator('#page-host input[type="password"]').fill("unsent-offline-game-password") self.page.locator('#page-host input[type="password"]').fill("unsent-offline-game-password")
self.page.locator("#refresh").click() self.page.locator("#refresh").click()
self.assert_hidden_transition(snapshots) self.assert_hidden_transition(snapshots)
@@ -284,7 +272,7 @@ class AdminLoginBrowserTests(unittest.TestCase):
response = page.goto(self.base + "/", wait_until="networkidle") response = page.goto(self.base + "/", wait_until="networkidle")
expect(page).to_have_url(self.base + "/login") expect(page).to_have_url(self.base + "/login")
self.assertNotIn('id="app"', response.text()) self.assertNotIn('id="app"', response.text())
self.assertEqual(page.locator("#app, nav, #sidebar, #topbar, #account-select, #account-tabs, #page-tabs").count(), 0) self.assertEqual(page.locator("#app, nav, #account-tabs, #page-tabs").count(), 0)
expect(page.locator("#auth-form")).to_be_visible() expect(page.locator("#auth-form")).to_be_visible()
expect(page.locator("#auth-form button")).to_be_disabled() expect(page.locator("#auth-form button")).to_be_disabled()
expect(page.locator("noscript")).to_be_visible() expect(page.locator("noscript")).to_be_visible()
@@ -6,7 +6,6 @@ Only disposable demo accounts and a synthetic administrator password are used.
from __future__ import annotations from __future__ import annotations
from pathlib import Path from pathlib import Path
import re
import socket import socket
import tempfile import tempfile
import threading import threading
@@ -15,8 +14,7 @@ import unittest
from unittest.mock import patch from unittest.mock import patch
from urllib.parse import urlsplit from urllib.parse import urlsplit
from ranch_web.tests.test_api import FrontendAssets from .test_workbench_browser import AVAILABLE, EDGE, OfflineUpdates
from .test_workbench_browser import AVAILABLE, EDGE, OfflineUpdates, GAME_PAGES, GLOBAL_PAGES, assert_navigation
if AVAILABLE: if AVAILABLE:
from playwright.sync_api import expect from playwright.sync_api import expect
@@ -101,7 +99,7 @@ class BasePathBrowserTests(unittest.TestCase):
expect(page.locator("#auth-form")).to_be_visible() expect(page.locator("#auth-form")).to_be_visible()
expect(page.locator("#admin-password")).to_be_enabled() expect(page.locator("#admin-password")).to_be_enabled()
expect(page.locator("#auth-form")).to_have_attribute("action", prefix + "/api/auth/login") expect(page.locator("#auth-form")).to_have_attribute("action", prefix + "/api/auth/login")
self.assertEqual(page.locator("#app, nav, #sidebar, #topbar, #account-select, #account-tabs, #page-tabs, #page-host").count(), 0) self.assertEqual(page.locator("#app, nav, #account-tabs, #page-tabs, #page-host").count(), 0)
self.assertEqual(page.locator("script").count(), 1) self.assertEqual(page.locator("script").count(), 1)
expect(page.locator("script")).to_have_attribute("src", prefix + "/static/login.js") expect(page.locator("script")).to_have_attribute("src", prefix + "/static/login.js")
expect(page.locator('link[rel="stylesheet"]')).to_have_attribute("href", prefix + "/static/login.css") expect(page.locator('link[rel="stylesheet"]')).to_have_attribute("href", prefix + "/static/login.css")
@@ -120,45 +118,26 @@ class BasePathBrowserTests(unittest.TestCase):
page.locator('#auth-form button[type="submit"]').click() page.locator('#auth-form button[type="submit"]').click()
self.assertEqual(login.value.status, 200) self.assertEqual(login.value.status, 200)
self.assertEqual(login.value.request.post_data_json, {"password": self.password}) self.assertEqual(login.value.request.post_data_json, {"password": self.password})
expect(page).to_have_url(re.compile("^" + re.escape(base + "/") + r"(?:#.*)?$")) expect(page).to_have_url(base + "/")
expect(page.locator("#app")).to_be_visible() expect(page.locator("#app")).to_be_visible()
assert_navigation(page) expect(page.locator("#status-text")).to_have_text("工作台已连接")
expect(page.locator("#status-text")).to_contain_text("已连接")
expect(page.locator("#save-status")).to_have_text("策略已自动保存") expect(page.locator("#save-status")).to_have_text("策略已自动保存")
assets = FrontendAssets(page.content()) expect(page.locator('link[rel="stylesheet"]')).to_have_attribute("href", prefix + "/static/styles.css")
self.assertTrue(assets.scripts)
self.assertTrue(assets.stylesheets)
for url in assets.urls:
self.assertTrue(url.startswith(prefix + "/static/"), url)
self.assertNotIn(prefix + prefix, url)
response = context.request.get(origin + url)
self.assertEqual(response.status, 200, url)
self.assertEqual(context.cookies()[0]["path"], prefix or "/") self.assertEqual(context.cookies()[0]["path"], prefix or "/")
self.assertEqual(page.evaluate("localStorage.length + sessionStorage.length"), 0) self.assertEqual(page.evaluate("localStorage.length + sessionStorage.length"), 0)
for key in GAME_PAGES: for key in "login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split():
page.locator(f'.nav-link[data-page="{key}"]').click() page.locator(f'.page-tab[data-page="{key}"]').click()
panel = page.locator(f'.page-panel[data-page="{key}"]:not([hidden])') panel = page.locator(f'.page-panel[data-page="{key}"]:not([hidden])')
expect(panel.locator('.page-loading[data-loading="false"]')).to_have_count(1) expect(panel.locator('.page-loading[data-loading="false"]')).to_have_count(1)
self.assertEqual(panel.locator(".page-error:not([hidden])").count(), 0) self.assertEqual(panel.locator(".page-error:not([hidden])").count(), 0)
if key == "bag":
route_url = page.url
self.assertEqual(urlsplit(route_url).fragment, f"/accounts/{account}/bag")
page.reload(wait_until="networkidle")
expect(page).to_have_url(route_url)
expect(page.locator("#account-select")).to_have_value(account)
expect(page.locator('.nav-link[data-page="bag"]')).to_have_attribute("aria-current", "page")
expect(panel.locator('.page-loading[data-loading="false"]')).to_have_count(1)
for key in GLOBAL_PAGES:
page.locator(f'.nav-link[data-page="{key}"]').click()
expect(page.locator(f'.nav-link[data-page="{key}"]')).to_have_attribute("aria-current", "page")
# The server redirects an authenticated login URL back to this workbench. # The server redirects an authenticated login URL back to this workbench.
page.goto(base + "/login", wait_until="networkidle") page.goto(base + "/login", wait_until="networkidle")
self.assertEqual(urlsplit(page.url).path, prefix + "/") expect(page).to_have_url(base + "/")
expect(page.locator("#status-text")).to_contain_text("已连接") expect(page.locator("#status-text")).to_have_text("工作台已连接")
cookies = context.cookies() cookies = context.cookies()
page.locator('.nav-link[data-page="system"]').click() page.locator(".menu > summary").first.click()
with page.expect_response(base + "/api/auth/logout") as logout: with page.expect_response(base + "/api/auth/logout") as logout:
page.locator('[data-command="admin-logout"]').click() page.locator('[data-command="admin-logout"]').click()
self.assertEqual(logout.value.status, 200) self.assertEqual(logout.value.status, 200)
@@ -169,8 +148,7 @@ class BasePathBrowserTests(unittest.TestCase):
assert_login() assert_login()
self.assertEqual(escapes, [], "Browser requests escaped the configured prefix or local server") self.assertEqual(escapes, [], "Browser requests escaped the configured prefix or local server")
self.assertEqual(errors, [], "JavaScript or CSP errors") self.assertEqual(errors, [], "JavaScript or CSP errors")
for url, _ in assets.scripts: self.assertTrue(any(request.url == base + "/static/paths.js" for request in requests))
self.assertTrue(any(request.url == origin + url for request in requests), url)
def test_preserved_prefix(self): def test_preserved_prefix(self):
self.check_deployment("/ranch") self.check_deployment("/ranch")
+23 -320
View File
@@ -18,7 +18,6 @@ import tempfile
import threading import threading
import time import time
import unittest import unittest
from unittest.mock import patch
from urllib.parse import parse_qs, urlsplit from urllib.parse import parse_qs, urlsplit
@@ -28,20 +27,6 @@ if AVAILABLE:
from playwright.sync_api import expect from playwright.sync_api import expect
GAME_PAGES = "login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split()
GLOBAL_PAGES = ["overview", "accounts", "activity", "system"]
def assert_navigation(page):
expect(page.locator("#sidebar")).to_be_visible()
expect(page.locator("#topbar")).to_be_visible()
expect(page.locator("#sidebar .nav-link[data-page]")).to_have_count(len(GAME_PAGES) + len(GLOBAL_PAGES))
for key in GAME_PAGES + GLOBAL_PAGES:
expect(page.locator(f'#sidebar .nav-link[data-page="{key}"]')).to_have_count(1)
expect(page.locator("#account-select")).to_have_attribute("aria-label", "当前游戏账号")
expect(page.get_by_role("combobox", name="当前游戏", exact=True)).to_have_count(0)
class OfflineUpdates: class OfflineUpdates:
def status(self): def status(self):
return {"current_version": "2.0.0.dev1", "latest_version": None, "status": "unchecked", return {"current_version": "2.0.0.dev1", "latest_version": None, "status": "unchecked",
@@ -59,9 +44,6 @@ class WorkbenchBrowserTests(unittest.TestCase):
from ranch_web.config import WebConfig from ranch_web.config import WebConfig
from ranch_web.service import WebManager from ranch_web.service import WebManager
cls.network = patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP is forbidden"))
cls.network.start()
cls.addClassCleanup(cls.network.stop)
cls.temp = tempfile.TemporaryDirectory(prefix="ranch-web-browser-test-") cls.temp = tempfile.TemporaryDirectory(prefix="ranch-web-browser-test-")
cls.manager = WebManager(cls.temp.name, start_scheduler=False) cls.manager = WebManager(cls.temp.name, start_scheduler=False)
cls.first = cls.manager.create_account("浏览器离线演示", demo=True)["id"] cls.first = cls.manager.create_account("浏览器离线演示", demo=True)["id"]
@@ -104,18 +86,10 @@ class WorkbenchBrowserTests(unittest.TestCase):
self.errors = [] self.errors = []
self.page.on("pageerror", lambda failure: self.errors.append(str(failure))) self.page.on("pageerror", lambda failure: self.errors.append(str(failure)))
self.page.on("console", lambda message: self.errors.append(message.text) if message.type == "error" else None) self.page.on("console", lambda message: self.errors.append(message.text) if message.type == "error" else None)
self.external_requests = [] self.context.route("https://**", lambda route: route.abort())
def offline_only(route):
if route.request.url.startswith(self.base + "/"):
route.continue_()
else:
self.external_requests.append(route.request.url)
route.abort()
self.context.route("**/*", offline_only)
def tearDown(self): def tearDown(self):
self.context.close() self.context.close()
self.assertEqual(self.external_requests, [], "Browser requests must stay on the offline server")
def await_job(self, identifier, job_id): def await_job(self, identifier, job_id):
deadline = time.monotonic() + 10 deadline = time.monotonic() + 10
@@ -130,30 +104,15 @@ class WorkbenchBrowserTests(unittest.TestCase):
def open(self, page=None): def open(self, page=None):
page=page or self.page page=page or self.page
page.goto(self.base, wait_until="networkidle") page.goto(self.base, wait_until="networkidle")
page.locator('#account-select').select_option(self.first) page.locator(f'.account-tab[data-account="{self.first}"]').click()
expect(page.locator('#save-status')).to_have_text('策略已自动保存') expect(page.locator('#save-status')).to_have_text('策略已自动保存')
def go(self, key, page=None): def go(self, key, page=None):
page=page or self.page page=page or self.page
page.locator(f'#sidebar .nav-link[data-page="{key}"]').click() page.locator(f'.page-tab[data-page="{key}"]').click()
page.wait_for_selector(f'.page-panel[data-page="{key}"]:not([hidden]) .page-loading[data-loading="false"]') page.wait_for_selector(f'.page-panel[data-page="{key}"]:not([hidden]) .page-loading[data-loading="false"]')
return page.locator(f'.page-panel[data-page="{key}"]:not([hidden])') return page.locator(f'.page-panel[data-page="{key}"]:not([hidden])')
def global_page(self, key, page=None):
page = page or self.page
page.locator(f'#sidebar .nav-link[data-page="{key}"]').click()
expect(page.locator(f'#sidebar .nav-link[data-page="{key}"]')).to_have_attribute("aria-current", "page")
expect(page.locator("#page-host .page-panel:not([hidden])")).to_have_count(0)
def system_command(self, name):
self.global_page("system")
self.page.locator(f'[data-command="{name}"]').click()
def edit_and_save(self, field, value):
with self.page.expect_response(lambda response: response.request.method == "PUT" and response.url.endswith("/config")):
field.fill(value)
self.wait_saved()
@staticmethod @staticmethod
def field(root,path): def field(root,path):
return root.locator("[data-config-path='"+json.dumps(path,separators=(',',':'))+"']") return root.locator("[data-config-path='"+json.dumps(path,separators=(',',':'))+"']")
@@ -167,10 +126,9 @@ class WorkbenchBrowserTests(unittest.TestCase):
def test_local_no_password_login_route_returns_to_workbench(self): def test_local_no_password_login_route_returns_to_workbench(self):
self.page.goto(self.base + "/login", wait_until="networkidle") self.page.goto(self.base + "/login", wait_until="networkidle")
self.assertEqual(urlsplit(self.page.url).path, "/") expect(self.page).to_have_url(self.base + "/")
expect(self.page.locator("#app")).to_be_visible() expect(self.page.locator("#app")).to_be_visible()
assert_navigation(self.page) expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
expect(self.page.locator('.nav-link[data-page="overview"]')).to_have_attribute("aria-current", "page")
self.assertEqual(self.page.locator("#auth-dialog, #auth-form").count(), 0) self.assertEqual(self.page.locator("#auth-dialog, #auth-form").count(), 0)
self.assertEqual(self.errors, []) self.assertEqual(self.errors, [])
@@ -178,8 +136,8 @@ class WorkbenchBrowserTests(unittest.TestCase):
self.open() self.open()
writes = [] writes = []
self.page.on("request", lambda request: writes.append(request.url) if request.method in ("POST", "PUT", "DELETE") else None) self.page.on("request", lambda request: writes.append(request.url) if request.method in ("POST", "PUT", "DELETE") else None)
assert_navigation(self.page) keys = ["login", "incubator", "bag", "ranch", "daily", "hatching", "mainline", "battles", "gifts", "commissions", "exploration", "maps", "statistics", "plans", "yields"]
for key in GAME_PAGES: for key in keys:
panel = self.go(key) panel = self.go(key)
self.assertEqual(panel.locator(".page-error:not([hidden])").count(), 0) self.assertEqual(panel.locator(".page-error:not([hidden])").count(), 0)
if key=='hatching': if key=='hatching':
@@ -195,16 +153,14 @@ class WorkbenchBrowserTests(unittest.TestCase):
expect(self.field(panel,['progression_policy','enabled'])).to_be_visible() expect(self.field(panel,['progression_policy','enabled'])).to_be_visible()
panel.locator('.subtab[data-key="status"]').click() panel.locator('.subtab[data-key="status"]').click()
expect(self.field(panel,['progression_policy','enabled'])).to_have_count(0) expect(self.field(panel,['progression_policy','enabled'])).to_have_count(0)
for key in GLOBAL_PAGES:
self.global_page(key)
self.assertEqual(writes, [], "Switching pages must not submit game or configuration actions") self.assertEqual(writes, [], "Switching pages must not submit game or configuration actions")
expect(self.page.locator('.nav-link[data-page="statistics"]')).to_contain_text("数据分析") self.assertEqual(self.page.locator('.page-tab[data-page="statistics"]').inner_text(), "数据分析")
expect(self.page.locator('.nav-link[data-page="plans"]')).to_contain_text("执行计划") self.assertEqual(self.page.locator('.page-tab[data-page="plans"]').inner_text(), "执行计划")
self.go("bag") self.go("bag")
for width, height in ((1280, 800), (1600, 900), (390, 844)): for width, height in ((1280, 800), (1600, 900), (390, 844)):
self.page.set_viewport_size({"width": width, "height": height}) self.page.set_viewport_size({"width": width, "height": height})
self.assertTrue(self.page.locator("#strategy-toggle").is_visible()) self.assertTrue(self.page.locator("#strategy-toggle").is_visible())
self.assertTrue(self.page.locator("#topbar").is_visible()) self.assertTrue(self.page.locator("#page-tabs").is_visible())
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width) self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
self.assertEqual(self.errors, []) self.assertEqual(self.errors, [])
@@ -229,266 +185,15 @@ class WorkbenchBrowserTests(unittest.TestCase):
self.wait_saved() self.wait_saved()
self.page.locator("#strategy-toggle").click() self.page.locator("#strategy-toggle").click()
expect(self.page.locator('#strategy-toggle')).to_have_text('停止') expect(self.page.locator('#strategy-toggle')).to_have_text('停止')
expect(self.page.locator('.workspace-meta')).to_contain_text('策略运行中')
self.assertTrue(self.manager.status(self.first)["running"])
self.page.locator("#strategy-toggle").click() self.page.locator("#strategy-toggle").click()
expect(self.page.locator('#strategy-toggle')).to_have_text('开启') expect(self.page.locator('#strategy-toggle')).to_have_text('开启')
self.page.locator('#account-select').select_option(self.second) self.page.locator(f'.account-tab[data-account="{self.second}"]').click()
expect(self.page.locator('#save-status')).to_have_text('策略已自动保存') expect(self.page.locator('#save-status')).to_have_text('策略已自动保存')
self.assertEqual(self.manager.get_config(self.second)["config"]["policy"]["egg_rules"], {}) self.assertEqual(self.manager.get_config(self.second)["config"]["policy"]["egg_rules"], {})
self.page.locator('#account-select').select_option(self.first) self.page.locator(f'.account-tab[data-account="{self.first}"]').click()
self.assertEqual(self.go("bag").locator(f'tr[data-row-id="{species}"] td[data-column="priority"] input').input_value(), "17") self.assertEqual(self.go("bag").locator(f'tr[data-row-id="{species}"] td[data-column="priority"] input').input_value(), "17")
self.assertEqual(self.errors, []) self.assertEqual(self.errors, [])
def test_account_routes_restore_back_reload_and_isolated_configuration(self):
self.open()
panel = self.go("bag")
species = panel.locator("tbody tr[data-row-id]").first.get_attribute("data-row-id")
cell = f'tr[data-row-id="{species}"] td[data-column="priority"] input'
self.edit_and_save(panel.locator(cell), "31")
first_url = self.page.url
self.assertEqual(urlsplit(first_url).fragment, f"/accounts/{self.first}/bag")
self.page.locator("#account-select").select_option(self.second)
expect(self.page.locator("#save-status")).to_have_text("策略已自动保存")
panel = self.go("bag")
self.assertNotEqual(panel.locator(cell).input_value(), "31")
self.edit_and_save(panel.locator(cell), "47")
second_url = self.page.url
self.assertEqual(urlsplit(second_url).fragment, f"/accounts/{self.second}/bag")
self.assertNotEqual(first_url, second_url, "Routes must identify the selected account")
self.go("statistics")
self.assertNotEqual(self.page.url, second_url, "Routes must identify the current page")
self.page.go_back()
expect(self.page).to_have_url(second_url)
expect(self.page.locator("#account-select")).to_have_value(self.second)
expect(self.page.locator('.page-panel[data-page="bag"]:not([hidden])').locator(cell)).to_have_value("47")
self.page.go_back()
expect(self.page).to_have_url(first_url)
expect(self.page.locator("#account-select")).to_have_value(self.first)
expect(self.page.locator('.page-panel[data-page="bag"]:not([hidden])').locator(cell)).to_have_value("31")
self.page.reload(wait_until="networkidle")
expect(self.page).to_have_url(first_url)
expect(self.page.locator("#account-select")).to_have_value(self.first)
expect(self.page.locator('.nav-link[data-page="bag"]')).to_have_attribute("aria-current", "page")
expect(self.page.locator('.page-panel[data-page="bag"]:not([hidden])').locator(cell)).to_have_value("31")
self.assertEqual(self.manager.get_config(self.first)["config"]["policy"]["egg_rules"][species]["priority"], 31)
self.assertEqual(self.manager.get_config(self.second)["config"]["policy"]["egg_rules"][species]["priority"], 47)
self.assertEqual(self.errors, [])
def test_overview_stop_targets_its_row_without_changing_selected_account(self):
self.open()
panel = self.go("bag")
with self.page.expect_response(lambda response: response.request.method == "PUT" and response.url.endswith("/config")):
panel.locator('tbody tr[data-row-id] td[data-column="enabled"] input').first.check()
self.wait_saved()
response = self.manager.set_config(self.second, self.manager.get_config(self.first)["config"])
self.await_job(self.second, response["job_id"])
for identifier in (self.first, self.second):
job = self.manager.submit(identifier, "start")
self.await_job(identifier, job["id"])
self.open()
self.global_page("overview")
actions = []
self.page.on("request", lambda request: actions.append(urlsplit(request.url).path)
if request.method == "POST" and "/actions/" in request.url else None)
row = self.page.locator(f'tr[data-account="{self.second}"]:visible')
expect(row).to_have_count(1)
row.get_by_role("button", name="停止账号二策略", exact=True).click()
expect(row.get_by_role("button", name="开启账号二策略", exact=True)).to_be_visible()
expect(self.page.locator("#account-select")).to_have_value(self.first)
self.assertTrue(self.manager.status(self.first)["running"], "The selected account must keep running")
self.assertFalse(self.manager.status(self.second)["running"])
self.assertEqual(actions, [f"/api/accounts/{self.second}/actions/stop"])
self.assertEqual(self.errors, [])
def test_mobile_sidebar_opens_navigates_closes_and_supports_escape(self):
self.open()
self.go("bag")
sidebar = self.page.locator("#sidebar")
for width in (1280, 1600):
self.page.set_viewport_size({"width": width, "height": 900})
expect(sidebar).to_be_visible()
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
self.page.set_viewport_size({"width": 390, "height": 844})
toggle = self.page.locator('button[aria-controls="sidebar"]')
expect(toggle).to_be_visible()
expect(toggle).to_have_attribute("aria-expanded", "false")
toggle.click()
expect(toggle).to_have_attribute("aria-expanded", "true")
expect(sidebar).to_be_visible()
self.go("ranch")
expect(toggle).to_have_attribute("aria-expanded", "false")
expect(self.page.locator('.nav-link[data-page="ranch"]')).to_have_attribute("aria-current", "page")
expect(self.page.locator("#strategy-toggle")).to_be_visible()
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), 390)
toggle.focus()
self.page.keyboard.press("Enter")
expect(toggle).to_have_attribute("aria-expanded", "true")
self.page.keyboard.press("Escape")
expect(toggle).to_have_attribute("aria-expanded", "false")
self.page.set_viewport_size({"width": 1280, "height": 800})
expect(sidebar).to_be_visible()
self.assertEqual(self.errors, [])
def test_inflight_config_save_keeps_its_account_after_switch(self):
held = []
def delay_first_save(route):
if route.request.method == "PUT":
held.append(route)
else:
route.continue_()
self.page.route(f"**/api/accounts/{self.first}/config", delay_first_save)
self.open()
panel = self.go("bag")
species = panel.locator("tbody tr[data-row-id]").first.get_attribute("data-row-id")
cell = f'tr[data-row-id="{species}"] td[data-column="priority"] input'
panel.locator(cell).fill("29")
self.page.locator("#account-select").select_option(self.second)
expect(self.page.locator("#account-select")).to_have_value(self.second)
expect(self.page.locator("#save-status")).to_have_text("策略已自动保存")
panel = self.go("bag")
self.assertNotEqual(panel.locator(cell).input_value(), "29")
self.edit_and_save(panel.locator(cell), "43")
self.assertEqual(len(held), 1, "Switching accounts must flush the previous account's draft")
self.assertEqual(held[0].request.post_data_json["config"]["policy"]["egg_rules"][species]["priority"], 29)
with self.page.expect_response(lambda response: response.request.method == "PUT" and response.url.endswith(f"/{self.first}/config")) as pending:
held[0].continue_()
saved = pending.value.json()
if saved.get("job_id"):
self.await_job(self.first, saved["job_id"])
expect(self.page.locator("#account-select")).to_have_value(self.second)
expect(panel.locator(cell)).to_have_value("43")
self.assertEqual(self.manager.get_config(self.first)["config"]["policy"]["egg_rules"][species]["priority"], 29)
self.assertEqual(self.manager.get_config(self.second)["config"]["policy"]["egg_rules"][species]["priority"], 43)
self.page.locator("#account-select").select_option(self.first)
expect(self.page.locator("#save-status")).to_have_text("策略已自动保存")
expect(self.go("bag").locator(cell)).to_have_value("29")
self.assertEqual(self.errors, [])
def test_invalid_numeric_draft_blocks_start_and_recovers_after_correction(self):
self.open()
panel = self.go("bag")
with self.page.expect_response(lambda response: response.request.method == "PUT" and response.url.endswith("/config")):
panel.locator('tbody tr[data-row-id] td[data-column="enabled"] input').first.check()
self.wait_saved()
priority = panel.locator('tbody tr[data-row-id] td[data-column="priority"] input').first
writes = []
self.page.on("request", lambda request: writes.append((request.method, request.url))
if request.method in ("PUT", "POST") else None)
with self.page.expect_response(lambda response: "/views/bag?" in response.url, timeout=10000):
priority.fill("-1")
original = priority.element_handle()
expect(priority).to_have_value("-1")
self.assertTrue(priority.evaluate("(node, original) => node === original", original))
self.assertFalse(priority.evaluate("node => node.validity.valid"))
self.page.locator("#strategy-toggle").click()
self.page.wait_for_timeout(750)
self.assertEqual(writes, [], "Invalid input must never be saved or start a strategy")
self.assertFalse(self.manager.status(self.first)["running"])
self.edit_and_save(priority, "19")
self.page.locator("#strategy-toggle").click()
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator('.workspace-meta')).to_contain_text('策略运行中')
self.assertTrue(self.manager.status(self.first)["running"])
self.page.locator("#strategy-toggle").click()
expect(self.page.locator("#strategy-toggle")).to_have_text("开启")
self.assertEqual(self.errors, [])
def test_stop_cancels_start_waiting_for_config_save(self):
held, actions = [], []
def delay_save(route):
if route.request.method == "PUT":
held.append(route)
else:
route.continue_()
self.page.route(f"**/api/accounts/{self.first}/config", delay_save)
self.open()
panel = self.go("bag")
priority = panel.locator('tbody tr[data-row-id] td[data-column="priority"] input').first
self.page.on("request", lambda request: actions.append(urlsplit(request.url).path)
if request.method == "POST" and "/actions/" in request.url else None)
with self.page.expect_request(lambda request: request.method == "PUT" and request.url.endswith(f"/{self.first}/config")):
priority.fill("37")
self.page.locator("#strategy-toggle").click()
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
with self.page.expect_response(f"**/api/accounts/{self.first}/actions/stop") as stopped:
self.page.locator("#strategy-toggle").click()
self.await_job(self.first, stopped.value.json()["id"])
self.assertEqual(len(held), 1, "Stop must complete while the config request remains blocked")
self.assertEqual(actions, [f"/api/accounts/{self.first}/actions/stop"])
with self.page.expect_response(lambda response: response.request.method == "PUT" and response.url.endswith(f"/{self.first}/config")) as saved:
held[0].continue_()
value = saved.value.json()
if value.get("job_id"):
self.await_job(self.first, value["job_id"])
self.page.wait_for_timeout(1200)
self.assertEqual(actions, [f"/api/accounts/{self.first}/actions/stop"], "A cancelled start must not resume after its save")
self.assertFalse(self.manager.status(self.first)["running"])
expect(self.page.locator("#strategy-toggle")).to_have_text("开启")
self.assertEqual(self.errors, [])
def test_thousand_rows_bound_dom_and_preserve_pagination_sort_selection_and_filter(self):
rows = [{"id": str(index), "name": f"离线魔物{index:04d}", "score": 1001 - index,
"priority": (index - 1) % 999 + 1} for index in range(1, 1001)]
writes = []
def fixture(route):
query = json.loads(parse_qs(urlsplit(route.request.url).query)["query"][0])
search = query.get("search", "")
self.fulfill(route, {"loading": False, "data": {
"page": "bag", "title": "背包", "summary": "一千行离线分页回归", "form": [], "actions": [],
"filters": [{"key": "search", "label": "搜索名称", "type": "text", "value": search}],
"columns": [{"key": "name", "label": "名称"}, {"key": "score", "label": "分值"},
{"key": "priority", "label": "优先级", "edit": {
"path": ["policy", "egg_rules", "{id}", "priority"], "type": "integer", "min": 1, "max": 999}}],
"rows": [row for row in rows if search in row["name"]],
}})
self.page.route(f"**/api/accounts/{self.first}/views/bag?*", fixture)
self.open()
self.page.on("request", lambda request: writes.append(request.url) if request.method in ("PUT", "POST", "DELETE") else None)
panel = self.go("bag")
body = panel.locator("tbody tr[data-row-id]")
pager = panel.get_by_role("navigation", name="表格分页", exact=True)
expect(panel.get_by_label("每页条目数", exact=True)).to_have_value("50")
expect(body).to_have_count(50)
expect(panel.locator('tbody input[type="number"]')).to_have_count(50)
expect(body.first).to_have_attribute("data-row-id", "1")
panel.get_by_role("checkbox", name="选择本页全部 50 项", exact=True).check()
expect(panel.locator(".table-selection-summary")).to_contain_text("已选择 50 项")
pager.get_by_role("button", name="下一页", exact=True).click()
expect(body).to_have_count(50)
expect(body.first).to_have_attribute("data-row-id", "51")
body.first.locator(".selection-cell input").check()
expect(panel.locator(".table-selection-summary")).to_contain_text("已选择 51 项")
pager.get_by_role("button", name="上一页", exact=True).click()
expect(body.first.locator(".selection-cell input")).to_be_checked()
pager.get_by_role("button", name="全选筛选结果(1000 项,含其他分页)", exact=True).click()
expect(panel.locator(".table-selection-summary")).to_contain_text("已选择 1000 项")
expect(body).to_have_count(50)
expect(panel.locator('tbody input[type="number"]')).to_have_count(50)
pager.get_by_role("button", name="清除选择", exact=True).click()
expect(panel.locator('tbody tr[aria-selected="true"]')).to_have_count(0)
panel.locator('th[data-column="score"] button').click()
expect(body.first).to_have_attribute("data-row-id", "1000")
expect(body.last).to_have_attribute("data-row-id", "951")
pager.get_by_role("button", name="末页", exact=True).click()
expect(panel.get_by_label("当前页码", exact=True)).to_have_value("20")
expect(body.first).to_have_attribute("data-row-id", "50")
expect(body.last).to_have_attribute("data-row-id", "1")
panel.get_by_label("每页条目数", exact=True).select_option("100")
expect(body).to_have_count(100)
expect(panel.locator('tbody input[type="number"]')).to_have_count(100)
expect(panel.get_by_label("当前页码", exact=True)).to_have_value("10")
expect(body.first).to_have_attribute("data-row-id", "100")
panel.get_by_label("搜索名称", exact=True).fill("离线魔物0001")
expect(body).to_have_count(1)
expect(body.first).to_have_attribute("data-row-id", "1")
expect(panel.get_by_label("当前页码", exact=True)).to_have_value("1")
expect(pager.get_by_role("button", name="下一页", exact=True)).to_be_disabled()
self.assertEqual(writes, [], "Paging, sorting, selecting and filtering must be read only")
self.assertEqual(self.errors, [])
def test_exploration_keeps_partial_drafts_and_saves_only_three_or_auto(self): def test_exploration_keeps_partial_drafts_and_saves_only_three_or_auto(self):
from ranch_web.policies import default_config from ranch_web.policies import default_config
@@ -566,14 +271,12 @@ class WorkbenchBrowserTests(unittest.TestCase):
self.page.route(f"**/api/accounts/{self.first}/logs?*", route_logs) self.page.route(f"**/api/accounts/{self.first}/logs?*", route_logs)
self.page.route(f"**/api/accounts/{self.first}/debug/51", route_detail) self.page.route(f"**/api/accounts/{self.first}/debug/51", route_detail)
self.open() self.open()
self.global_page("activity") self.page.locator("#debug-toggle").click()
self.page.locator("#debug-log").check() self.page.wait_for_selector(".log-entry.inspectable")
self.page.wait_for_selector(".activity-line button.inspectable") expect(self.page.locator('.log-entry.inspectable .log-time')).to_have_text('15:08:09')
entry = self.page.locator('.activity-line:has(button.inspectable)') expect(self.page.locator('.log-entry.inspectable .log-time')).to_have_attribute('title','2026-11-10T07:08:09Z')
expect(entry.locator('.log-time')).to_have_text('15:08:09')
expect(entry.locator('.log-time')).to_have_attribute('title','2026-11-10T07:08:09Z')
self.assertEqual(detail_requests, []) self.assertEqual(detail_requests, [])
entry.locator("button.inspectable").first.click() self.page.locator(".log-entry.inspectable").first.click()
expect(self.page.locator('.debug-json')).to_contain_text('<隐藏>') expect(self.page.locator('.debug-json')).to_contain_text('<隐藏>')
self.assertEqual(len(detail_requests), 1) self.assertEqual(len(detail_requests), 1)
self.assertEqual(self.errors, []) self.assertEqual(self.errors, [])
@@ -600,14 +303,15 @@ class WorkbenchBrowserTests(unittest.TestCase):
from ranch_assistant.model import Catalog from ranch_assistant.model import Catalog
self.open() self.open()
self.page.locator('.menu > summary').nth(2).click()
with self.page.expect_download() as pending: with self.page.expect_download() as pending:
self.system_command("export-config") self.page.locator('[data-command="export-config"]').click()
exported = json.loads(Path(pending.value.path()).read_text(encoding='utf-8')) exported = json.loads(Path(pending.value.path()).read_text(encoding='utf-8'))
self.assertIn('policy', exported) self.assertIn('policy', exported)
self.assertNotIn('password', exported) self.assertNotIn('password', exported)
yields = self.go("yields") self.page.locator('.menu > summary').nth(2).click()
with self.page.expect_download() as pending: with self.page.expect_download() as pending:
yields.locator('button[data-operation="download_yields"]').click() self.page.locator('[data-command="export-yields"]').click()
content = Path(pending.value.path()).read_bytes() content = Path(pending.value.path()).read_bytes()
raw = content.decode('utf-8-sig') raw = content.decode('utf-8-sig')
rows = list(csv.DictReader(raw.splitlines())) rows = list(csv.DictReader(raw.splitlines()))
@@ -696,13 +400,11 @@ class WorkbenchBrowserTests(unittest.TestCase):
second.route(f'**/api/accounts/{self.first}/views/maps?*',map_view) second.route(f'**/api/accounts/{self.first}/views/maps?*',map_view)
self.open(second) self.open(second)
panel_b=self.go('maps',second) panel_b=self.go('maps',second)
second.bring_to_front()
panel_b.locator('td[data-column="level"] select').select_option('2') panel_b.locator('td[data-column="level"] select').select_option('2')
panel_b.locator('td[data-column="limit"] input').fill('5') panel_b.locator('td[data-column="limit"] input').fill('5')
second.wait_for_timeout(1400) second.wait_for_timeout(1400)
expect(second.locator('#save-status')).to_have_text('策略已自动保存') expect(second.locator('#save-status')).to_have_text('策略已自动保存')
self.assertEqual(self.manager.get_config(self.first)['config']['sweep_policy']['rules']['stage1']['limit'],5) self.assertEqual(self.manager.get_config(self.first)['config']['sweep_policy']['rules']['stage1']['limit'],5)
self.page.bring_to_front()
panel_a.locator('td[data-column="enabled"] input').check() panel_a.locator('td[data-column="enabled"] input').check()
expect(self.page.locator('#save-status')).to_have_text('保存失败 · 点击重试',timeout=10000) expect(self.page.locator('#save-status')).to_have_text('保存失败 · 点击重试',timeout=10000)
self.page.locator('#save-status').click() self.page.locator('#save-status').click()
@@ -765,7 +467,8 @@ class WorkbenchBrowserTests(unittest.TestCase):
self.page.route('**/api/system/updates',updates) self.page.route('**/api/system/updates',updates)
self.page.route('**/api/system/updates/apply',apply) self.page.route('**/api/system/updates/apply',apply)
self.open() self.open()
self.system_command("updates") self.page.locator('.menu > summary').nth(3).click()
self.page.locator('[data-command="updates"]').click()
expect(self.page.get_by_text('发现新版本',exact=True).first).to_be_visible() expect(self.page.get_by_text('发现新版本',exact=True).first).to_be_visible()
self.page.once('dialog',lambda prompt:prompt.accept()) self.page.once('dialog',lambda prompt:prompt.accept())
self.page.get_by_role('button',name='提交更新请求…',exact=True).click() self.page.get_by_role('button',name='提交更新请求…',exact=True).click()
+3 -40
View File
@@ -4,7 +4,6 @@ import asyncio
import base64 import base64
from copy import deepcopy from copy import deepcopy
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from html.parser import HTMLParser
import json import json
import os import os
from pathlib import Path from pathlib import Path
@@ -23,29 +22,6 @@ from ranch_web.app import create_app
from ranch_web.config import WebConfig from ranch_web.config import WebConfig
class FrontendAssets(HTMLParser):
"""Read the built entry so tests also exercise hashed asset URLs."""
def __init__(self, content):
super().__init__()
self.scripts, self.stylesheets, self.preloads = [], [], []
self.feed(content)
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "script" and attrs.get("src"):
self.scripts.append((attrs["src"], attrs.get("type")))
if tag == "link" and attrs.get("href"):
if attrs.get("rel") == "stylesheet":
self.stylesheets.append(attrs["href"])
elif attrs.get("rel") == "modulepreload":
self.preloads.append(attrs["href"])
@property
def urls(self):
return [url for url, _ in self.scripts] + self.stylesheets + self.preloads
class FakeUpdates: class FakeUpdates:
def __init__(self): def __init__(self):
self.calls = [] self.calls = []
@@ -537,28 +513,15 @@ class ApiTests(unittest.TestCase):
for url in ("/static/.env", "/static/config.py", "/static/../app.py", "/static/%2e%2e/requirements.txt"): for url in ("/static/.env", "/static/config.py", "/static/../app.py", "/static/%2e%2e/requirements.txt"):
with self.subTest(url=url): with self.subTest(url=url):
self.assertEqual(self.client.get(url).status_code, 404) self.assertEqual(self.client.get(url).status_code, 404)
entry = self.client.get("/") for url in ("/", "/static/index.html", "/static/app.js"):
assets = FrontendAssets(entry.text)
self.assertTrue(assets.scripts, "The console entry must reference its built JavaScript")
self.assertTrue(assets.stylesheets, "The console must load its stylesheet under CSP")
self.assertTrue(all(kind == "module" for _, kind in assets.scripts))
for url in assets.urls:
self.assertTrue(url.startswith("/static/"), url)
for url in ("/", "/static/index.html", *assets.urls):
response = self.client.get(url) response = self.client.get(url)
self.assertEqual(response.status_code, 200, url) self.assertEqual(response.status_code, 200)
if url not in assets.stylesheets: self.assertEqual(response.headers["cache-control"], "no-store")
self.assertEqual(response.headers["cache-control"], "no-store")
self.assertEqual(response.headers["x-content-type-options"], "nosniff") self.assertEqual(response.headers["x-content-type-options"], "nosniff")
self.assertIn("frame-ancestors 'none'", response.headers["content-security-policy"]) self.assertIn("frame-ancestors 'none'", response.headers["content-security-policy"])
if url in [script for script, _ in assets.scripts] or url in assets.preloads:
self.assertIn("javascript", response.headers["content-type"], url)
elif url in assets.stylesheets:
self.assertIn("text/css", response.headers["content-type"], url)
for url in ("/", "/static/index.html"): for url in ("/", "/static/index.html"):
response = self.client.get(url) response = self.client.get(url)
self.assertIn("text/html", response.headers["content-type"]) self.assertIn("text/html", response.headers["content-type"])
self.assertEqual(FrontendAssets(response.text).urls, assets.urls)
response = self.client.get("/login", follow_redirects=False) response = self.client.get("/login", follow_redirects=False)
self.assertEqual(response.status_code, 303) self.assertEqual(response.status_code, 303)
self.assertEqual(response.headers["location"], "/") self.assertEqual(response.headers["location"], "/")
+4 -22
View File
@@ -11,7 +11,7 @@ from fastapi.testclient import TestClient
from ranch_web.app import create_app from ranch_web.app import create_app
from ranch_web.config import COOKIE_NAME, WebConfig from ranch_web.config import COOKIE_NAME, WebConfig
from ranch_web.tests.test_api import FakeManager, FakeUpdates, FrontendAssets from ranch_web.tests.test_api import FakeManager, FakeUpdates
BASE = "/myrzx_bot" BASE = "/myrzx_bot"
@@ -97,9 +97,6 @@ class BasePathTests(unittest.TestCase):
self.assertEqual(response.headers["location"], BASE + "/login") self.assertEqual(response.headers["location"], BASE + "/login")
def test_login_html_assets_and_authenticated_workbench(self): def test_login_html_assets_and_authenticated_workbench(self):
entry = Path(__file__).resolve().parents[1] / "static" / "index.html"
built_assets = FrontendAssets(entry.read_text(encoding="utf-8"))
self.assertTrue(built_assets.scripts)
for strip in (False, True): for strip in (False, True):
with self.subTest(strip=strip): with self.subTest(strip=strip):
client = self.client(strip) client = self.client(strip)
@@ -110,14 +107,12 @@ class BasePathTests(unittest.TestCase):
self.assertEqual(document.prefixes, [BASE]) self.assertEqual(document.prefixes, [BASE])
self.assertIn(("action", BASE + "/api/auth/login"), document.urls) self.assertIn(("action", BASE + "/api/auth/login"), document.urls)
self.assertIn(("src", BASE + "/static/login.js"), document.urls) self.assertIn(("src", BASE + "/static/login.js"), document.urls)
self.assertEqual(FrontendAssets(response.text).scripts,
[(BASE + "/static/login.js", "module")])
for name, url in document.urls: for name, url in document.urls:
self.assertTrue(url.startswith(BASE + "/"), url) self.assertTrue(url.startswith(BASE + "/"), url)
self.assertNotIn(BASE + BASE, url) self.assertNotIn(BASE + BASE, url)
if name != "action": if name != "action":
self.assertEqual(client.get(url).status_code, 200, url) self.assertEqual(client.get(url).status_code, 200, url)
for path in ("/", "/static/index.html", *(url for url, _ in built_assets.scripts)): for path in ("/", "/static/index.html", "/static/app.js"):
response = client.get(BASE + path, follow_redirects=False) response = client.get(BASE + path, follow_redirects=False)
self.assertEqual(response.status_code, 303) self.assertEqual(response.status_code, 303)
self.assertEqual(response.headers["location"], BASE + "/login") self.assertEqual(response.headers["location"], BASE + "/login")
@@ -131,22 +126,9 @@ class BasePathTests(unittest.TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
document = _Document(response.text) document = _Document(response.text)
self.assertEqual(document.prefixes, [BASE]) self.assertEqual(document.prefixes, [BASE])
assets = FrontendAssets(response.text) self.assertIn(("src", BASE + "/static/app.js"), document.urls)
self.assertEqual(assets.scripts, [(BASE + url, kind) for url, kind in built_assets.scripts])
self.assertEqual(assets.urls, [BASE + url for url in built_assets.urls])
self.assertEqual(response.headers["cache-control"], "no-store") self.assertEqual(response.headers["cache-control"], "no-store")
for url in assets.urls: self.assertEqual(client.get(BASE + "/static/app.js").status_code, 200)
self.assertTrue(url.startswith(BASE + "/static/"), url)
self.assertNotIn(BASE + BASE, url)
asset = client.get(url)
self.assertEqual(asset.status_code, 200, url)
if url not in assets.stylesheets:
self.assertEqual(asset.headers["cache-control"], "no-store")
client.cookies.clear()
for url, _ in built_assets.scripts:
response = client.get(BASE + url, follow_redirects=False)
self.assertEqual(response.status_code, 303)
self.assertEqual(response.headers["location"], BASE + "/login")
self.assertEqual(self.manager.calls, []) self.assertEqual(self.manager.calls, [])
def test_secure_cookie_scope_logout_and_revoked_session(self): def test_secure_cookie_scope_logout_and_revoked_session(self):