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