ui: keep policy controls close to their labels

This commit is contained in:
AttilaNet
2026-11-13 08:08:12 +08:00
parent 1b1fa96984
commit 2cb50839b5
16 changed files with 444 additions and 58 deletions
+8 -4
View File
@@ -1,8 +1,8 @@
# 牧羊人之心牧场助手 · Web 2.0.5
# 牧羊人之心牧场助手 · Web 2.0.6
## 产品约束
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.5`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.6`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。
使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。
@@ -24,9 +24,13 @@
- 数据分析用真实 DTO 绘制 SVG 条形图,保留来源筛选、体力效率、样本和不确定性说明。没有样本时明确说明。
- 策略统一导入导出;收益 CSV/XLSX 导入与可用数据下载。错误展示具体原因,不把不支持的任务伪装成可执行任务。
- 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。
- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.5 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。
- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.6 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。
## 2.0.5 界面精简
## 2.0.6 表单布局
勾选框与右侧文字组成一组;数字、文本与下拉框采用标签在上、控件在下的布局。设置区限定合理宽度,并按可用空间排为多列,每日领取项目在单独分组中排列。界面尺寸变化不改变配置路径、自动保存或策略执行规则。
## 界面精简(2.0.5 起)
删除字段帮助、页面操作说明等重复小字。页面首次读取与刷新使用内容区居中的圆形加载指示,不再在角落显示“正在读取”“已载入”。保留业务数量、资源费用、运行与错误状态,以及必要确认。
+7 -7
View File
@@ -1,6 +1,6 @@
# Web 2.0.5 运行说明
# Web 2.0.6 运行说明
本轮 Web 发布目标 **2.0.5**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。
本轮 Web 发布目标 **2.0.6**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。
Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。
@@ -10,8 +10,8 @@ Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或
- [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,每次成功登录后自动执行已配置且已勾选的功能,可在顶部停止。
- [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。
- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;历史 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测见下文。
- [x] 本轮发布目标为 `2.0.5`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。
- 2.0.5 清理非业务说明小字,页面加载使用居中圆形进度指示;保留必要错误、执行状态和业务数据。详见 [本版发布说明](../analysis/RELEASE_2_0_5.md)。
- [x] 本轮发布目标为 `2.0.6`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。
- 2.0.6 统一策略表单布局,勾选框贴近标签,普通字段标签置于控件上方,每日领取项目分组排列。详见 [本版发布说明](../analysis/RELEASE_2_0_6.md)。
- 2.0.3 修复 2.0.2 日志布局:所有页签复用原有底部日志区,按当前账号与功能筛选,默认收起;操作约定见 [产品说明](PRODUCT.md#203-底部分类日志),验收结果见 [发布说明](../analysis/RELEASE_2_0_3.md#验证)。
## Windows 本地运行
@@ -97,13 +97,13 @@ sh start-web.sh --no-browser
Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。
已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.5 稳定 Release 和正式镜像就绪、宿主机心跳有效后,直接通过“帮助 → 检查版本更新…”升级 **2.0.5**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。
已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.6 稳定 Release 和正式镜像就绪、宿主机心跳有效后,直接通过“帮助 → 检查版本更新…”升级 **2.0.6**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。
## 离线验证
2.0.5 验证结果统一见 [发布说明](../analysis/RELEASE_2_0_5.md#验证),以下历史记录不计入本版验收。
2.0.6 验证结果统一见 [发布说明](../analysis/RELEASE_2_0_6.md#验证),以下历史记录不计入本版验收。
### 历史验证记录(不计入 2.0.5)
### 历史验证记录(不计入 2.0.6)
2.0.2 验证记录见 [历史发布说明](../analysis/RELEASE_2_0_2.md#验证)。
+1 -1
View File
@@ -1,6 +1,6 @@
"""Headless Web workspace for the ranch assistant."""
__version__ = "2.0.5"
__version__ = "2.0.6"
GAME_VERSION = "1.9.68"
__all__ = ["__version__", "GAME_VERSION"]
+2 -2
View File
@@ -415,7 +415,7 @@ async function exportYields(account=current()) {
async function command(name,account=current()) {
try {
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.5'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true});
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.6'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true});
if(name==='updates')return await showUpdates();
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
if(!account)throw new Error('请先新增或选择账号。');
@@ -640,7 +640,7 @@ async function bootstrap() {
$('#app').hidden=false;
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
if(state.redirecting)return;
$('#app-version').textContent=meta.version || '2.0.5';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
$('#app-version').textContent=meta.version || '2.0.6';$('#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})));}
}
+18 -12
View File
@@ -55,10 +55,13 @@ export function control(field, {get, set, onError = () => {}}) {
const items = optionsList(field.options).map(option => {
const check = el('input', {type: 'checkbox', 'aria-label': option.label});
check.addEventListener('change', () => commit(items.filter(item => item.check.checked).map(item => item.option.value)));
root.append(el('label', {}, check, option.label));
root.append(el('label', {class: 'multi-select-option'}, check, el('span', {class: 'field-text', text: option.label})));
return {check, option};
});
sync = () => items.forEach(({check, option}) => { check.checked = (value() || []).includes(option.value); });
sync = () => items.forEach(({check, option}) => {
check.checked = (value() || []).includes(option.value);
check.disabled = Boolean(field.disabled || field.readonly || option.disabled);
});
} 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'});
@@ -152,19 +155,22 @@ export class PolicyForm {
groups.set(group, grid);
}
const entry = control(field, this.context);
entry.root.classList.add('field-input');
const boolean = ['boolean', 'bool', 'checkbox'].includes(field.type);
const wide = ['id_counts', 'counts', 'reserves', 'multiselect'].includes(field.type);
const row = el('label', {class: `field${boolean ? ' checkbox-field' : ''}${wide ? ' field-wide' : ''}`});
if (entry.root.tagName === 'DIV') {
const fieldRow = el('div', {class: `field${wide ? ' field-wide' : ''}`}, el('span', {class: 'field-label', text: field.label}), entry.root);
groups.get(group).append(fieldRow);
entry.row = fieldRow;
const multi = ['multiselect', 'multi_select'].includes(field.type);
const wide = multi || ['id_counts', 'counts', 'reserves'].includes(field.type);
const label = field.label || field.path.at(-1) || '设置';
entry.root.classList.add(boolean ? 'field-checkbox' : 'field-input');
let row;
if (boolean) {
row = el('div', {class: 'field field-boolean checkbox-field'},
el('label', {class: 'field-label'}, entry.root, el('span', {class: 'field-text', text: label})));
} else {
row.append(el('span', {class: 'field-label', text: field.label}), entry.root);
groups.get(group).append(row);
entry.row = row;
row = el(entry.root.tagName === 'DIV' ? 'div' : 'label',
{class: `field field-stacked${multi ? ' field-multiselect' : ''}${wide ? ' field-wide' : ''}`},
el('span', {class: 'field-label', text: label}), entry.root);
}
groups.get(group).append(row);
entry.row = row;
this.controls.push(entry);
});
this.signature = signature;
+1 -1
View File
@@ -26,7 +26,7 @@
</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.5</span></span>
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.6</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>
+16 -4
View File
@@ -4,11 +4,23 @@
.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}.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}
.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;width:100%;max-width:1000px}.form-section legend{font-size:12px;font-weight:600;padding:0 5px;color:#344458}.form-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,280px),310px));gap:10px 20px;align-items:start;justify-content:start;width:100%;max-width:1000px}.field{display:flex;align-items:center;gap:8px;min-width:0;font-size:12px}.field>.field-label{min-width:0;flex:0 1 auto;line-height:1.5;overflow-wrap:anywhere}
.field.field-stacked{flex-direction:column;align-items:flex-start;gap:5px}
.field-stacked>.field-label{flex:none;max-width:100%}
.field-stacked>.field-input{flex:none;min-width:0;width:310px;max-width:100%}
.field-stacked>input[type=number].field-input{width:150px}
.field.field-boolean{align-items:flex-start;min-height:27px}
.field-boolean>.field-label{display:inline-flex;align-items:flex-start;gap:7px;max-width:100%;min-height:27px;padding:4px 0;cursor:pointer}
.field-boolean .field-checkbox,.field-multiselect .multi-select-option>input[type=checkbox]{width:16px;height:16px;min-width:16px;min-height:16px;flex:none;margin:1px 0 0;padding:0}
.field .field-text{min-width:0;line-height:1.5;overflow-wrap:anywhere}
.field-stacked>.counts-editor,.field-stacked>.inline-editor{width:100%;max-width:660px}
.field-stacked .inline-editor{flex-wrap:wrap;max-width:100%}
.field-multiselect>.multi-select{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,180px),210px));gap:6px 12px;justify-items:start;width:100%;max-width:660px;padding:0}
.field-multiselect .multi-select-option{display:inline-flex;align-items:flex-start;gap:7px;min-width:0;max-width:100%;min-height:27px;padding:4px 0;cursor:pointer}.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{flex-direction:column;align-items:flex-start;gap:5px}.login-layout .field>.field-label{flex-basis:auto;min-width:0}.login-layout .field>.field-input,.login-layout .field>select{width:310px;max-width:100%}.login-options{display:flex;gap:14px;flex-wrap:wrap;font-size:12px}.login-actions{display:flex;gap:6px;flex-wrap:wrap}.server-row{display:flex;flex-wrap:wrap;gap:6px;flex:none;min-width:0;max-width:100%}.server-row select{min-width:0;width:310px;flex:0 1 310px}.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(min-width:1450px){.toolbar{gap:22px}.player-line{gap:18px}.page-tab{padding-left:13px;padding-right:13px}.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}.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:minmax(0,310px)}.field-wide{grid-column:1/-1}.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:160px;overflow:auto}.page-panel[data-page=login] .page-content{flex:0 0 auto;min-height:0;overflow:visible}.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}
@@ -228,9 +228,9 @@ class AutoReloginBrowserTests(unittest.TestCase):
panel.get_by_role("button", name="进入选中区服", exact=True).click()
expect(toggle).to_have_text("停止")
expect(toggle).to_have_attribute("aria-pressed", "true")
expect(self.page.locator("#notice")).to_contain_text("已自动开启策略")
expect(self.page.locator("#status-text")).to_contain_text("正在自动执行")
expect(self.page.locator("#data-summary")).to_contain_text("正在自动执行")
expect(self.page.locator("#notice")).to_contain_text("已读取角色,策略运行中")
expect(self.page.locator("#status-text")).to_contain_text("策略运行中")
expect(self.page.locator("#data-summary")).to_contain_text("策略运行中")
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
self.assertEqual(self.configs[self.first], original, "Logging in must preserve every feature selection")
toggle.click()
@@ -429,7 +429,7 @@ class AutoReloginBrowserTests(unittest.TestCase):
running=True, strategy_requested=True, strategy_state="running")
expect(status).to_contain_text("已恢复监控并自动执行已勾选功能")
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator("#data-summary")).to_contain_text("正在自动执行")
expect(self.page.locator("#data-summary")).to_contain_text("策略运行中")
self.assertEqual(self.configs[self.first], original)
self.assertEqual(self.actions, [])
@@ -0,0 +1,339 @@
"""Compact policy forms, using real renderers and disposable demo accounts.
Run: python -B -m unittest ranch_web.tests.browser.test_form_layout_browser -v
No private account files or game APIs are used. Desktop review screenshots are
written to test-artifacts/ui206; table editors keep their existing inline layout.
"""
from __future__ import annotations
import copy
from pathlib import Path
import unittest
from unittest.mock import patch
from . import test_quiet_ui_browser as quiet
from . import test_workbench_browser as fixtures
if fixtures.AVAILABLE:
from playwright.sync_api import expect
VIEWPORTS = ((1920, 900), (1280, 800), (800, 900), (390, 844))
ARTIFACTS = Path(__file__).resolve().parents[3] / "test-artifacts" / "ui206"
DAILY_CHOICES = (
("gift", "每日签到礼包"), ("check", "七日签到"), ("loop", "累计奖励"),
("vip", "VIP日奖"), ("mail", "邮件附件"),
)
def checkbox_pair(checkbox):
"""Measure actual text glyphs, including multiselect's bare text nodes."""
return checkbox.evaluate("""input => {
const label = input.closest('label');
if (!label) return null;
const walker = document.createTreeWalker(label, NodeFilter.SHOW_TEXT);
let text; while ((text = walker.nextNode()) && !text.textContent.trim()) {}
if (!text) return null;
const range = document.createRange(); range.selectNodeContents(text);
return {input: input.getBoundingClientRect().toJSON(),
text: range.getBoundingClientRect().toJSON(), label: label.getBoundingClientRect().toJSON(),
caption: label.textContent.trim(), first: label.firstElementChild === input,
controls: label.querySelectorAll('input, select, button').length,
font: parseFloat(getComputedStyle(text.parentElement).fontSize)};
}""")
def assert_checkbox_pair(test, checkbox, caption):
expect(checkbox).to_be_visible()
pair = checkbox_pair(checkbox)
test.assertIsNotNone(pair, "Each checkbox needs its own wrapping text label")
test.assertTrue(pair["first"], pair)
test.assertEqual(pair["controls"], 1, pair)
test.assertEqual(pair["caption"], caption)
for size in ("width", "height"):
test.assertGreaterEqual(pair["input"][size], 14, pair)
test.assertLessEqual(pair["input"][size], 18, pair)
gap = pair["text"]["left"] - pair["input"]["right"]
test.assertGreaterEqual(gap, 4, pair)
test.assertLessEqual(gap, 12, pair)
test.assertGreaterEqual(pair["font"], 11, pair)
test.assertLessEqual(pair["text"]["right"], pair["label"]["right"] + 1, pair)
test.assertLessEqual(pair["text"]["bottom"], pair["label"]["bottom"] + 1, pair)
test.assertLess(pair["text"]["top"], pair["input"]["bottom"], pair)
test.assertGreater(pair["text"]["bottom"], pair["input"]["top"], pair)
def click_checkbox_text(page, checkbox):
checkbox.scroll_into_view_if_needed()
pair = checkbox_pair(checkbox)
if pair is None:
raise AssertionError("Checkbox text must be in a wrapping label")
text = pair["text"]
page.mouse.click(text["x"] + text["width"] / 2, text["y"] + text["height"] / 2)
@unittest.skipUnless(fixtures.AVAILABLE, "Python Playwright and a system Chromium browser are required")
class PolicyFormLayoutBrowserTests(unittest.TestCase):
# Borrow the shared-renderer harness without inheriting its unrelated tests.
base = quiet.QuietUIBrowserTests.base
setUpClass = classmethod(quiet.QuietUIBrowserTests.setUpClass.__func__)
setUp = quiet.QuietUIBrowserTests.setUp
tearDown = quiet.QuietUIBrowserTests.tearDown
fixture = quiet.QuietUIBrowserTests.fixture
reply = staticmethod(quiet.QuietUIBrowserTests.reply)
open_shell = quiet.QuietUIBrowserTests.open_shell
render_form = quiet.QuietUIBrowserTests.render_form
def test_boolean_aliases_write_exact_paths_and_passive_sync_keeps_nodes_and_focus(self):
fields = [
{"path": ["policy", key], "label": label, "type": kind, "value": True}
for key, label, kind in (("enabled", "启用管理", "boolean"),
("buy", "自动购蛋", "bool"), ("fill", "填充空坑", "checkbox"))
] + [
{"path": ["policy", "buy_batch"], "label": "单抽时每批上限", "type": "integer", "value": 3, "min": 1, "max": 100},
{"path": ["policy", "market_id"], "label": "新增规则默认市场", "type": "select", "value": "first",
"options": {"first": "第一市场", "second": "第二市场"}},
]
self.render_form(fields)
host = self.page.locator("#page-host")
nodes = host.locator("input, select").element_handles()
count = host.get_by_role("spinbutton", name="单抽时每批上限", exact=True)
market = host.get_by_role("combobox", name="新增规则默认市场", exact=True)
count.focus()
latest = copy.deepcopy(fields)
latest[0]["value"], latest[3]["value"], latest[4]["value"] = False, 19, "second"
self.page.evaluate("fields => window.quietForm.update(fields)", latest)
expect(count).to_be_focused()
expect(count).to_have_value("3")
expect(market).to_have_value("second")
expect(host.get_by_role("checkbox", name="启用管理", exact=True)).not_to_be_checked()
market.focus()
latest[4]["value"] = "first"
self.page.evaluate("fields => window.quietForm.update(fields)", latest)
expect(market).to_be_focused()
expect(market).to_have_value("second")
expect(count).to_have_value("19")
self.page.locator("#log-toggle").focus()
self.page.evaluate("fields => window.quietForm.update(fields)", latest)
expect(self.page.locator("#log-toggle")).to_be_focused()
for index, original in enumerate(nodes):
self.assertTrue(host.locator("input, select").nth(index).evaluate("(node, old) => node === old", original))
self.assertEqual(self.page.evaluate("window.writes"), [], "Passive sync must never commit edits")
for index, field in enumerate(fields[:3]):
checkbox = host.get_by_role("checkbox", name=field["label"], exact=True)
assert_checkbox_pair(self, checkbox, field["label"])
peers = host.locator('input[type="checkbox"]').evaluate_all("nodes => nodes.map(node => node.checked)")
click_checkbox_text(self.page, checkbox)
peers[index] = not peers[index]
self.assertEqual(host.locator('input[type="checkbox"]').evaluate_all("nodes => nodes.map(node => node.checked)"), peers)
writes = self.page.evaluate("window.writes")
self.assertEqual(writes[-1], {"path": field["path"], "value": peers[index]})
self.assertEqual(len(writes), index + 1)
@unittest.skipUnless(fixtures.AVAILABLE, "Python Playwright and a system Chromium browser are required")
class DemoFormLayoutBrowserTests(unittest.TestCase):
setUpClass = classmethod(fixtures.WorkbenchBrowserTests.setUpClass.__func__)
tearDownClass = classmethod(fixtures.WorkbenchBrowserTests.tearDownClass.__func__)
await_job = fixtures.WorkbenchBrowserTests.await_job
open = fixtures.WorkbenchBrowserTests.open
go = fixtures.WorkbenchBrowserTests.go
field = staticmethod(fixtures.WorkbenchBrowserTests.field)
wait_saved = fixtures.WorkbenchBrowserTests.wait_saved
def setUp(self):
guard = patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP is forbidden"))
guard.start()
self.addCleanup(guard.stop)
fixtures.WorkbenchBrowserTests.setUp(self)
self.context.set_default_timeout(5000)
self.escapes, self.writes = [], []
def local_only(route):
if route.request.url.startswith(self.base + "/"):
route.continue_()
else:
self.escapes.append(route.request.url)
route.abort()
self.context.route("**/*", local_only)
self.page.on("request", lambda request: self.writes.append(request)
if request.method in ("POST", "PUT", "DELETE", "PATCH") else None)
self.other_config = self.manager.get_config(self.second)["config"]
def tearDown(self):
try:
self.assertEqual(self.escapes, [], "Browser requests must stay on the disposable local server")
self.assertEqual(self.errors, [], "No browser console or JavaScript errors")
for request in self.writes:
self.assertEqual((request.method, request.url), ("PUT", f"{self.base}/api/accounts/{self.first}/config"))
self.assertEqual(self.manager.get_config(self.second)["config"], self.other_config)
self.assertFalse(self.manager.status(self.first)["running"])
finally:
fixtures.WorkbenchBrowserTests.tearDown(self)
def screenshot(self, key, width):
if width in (1920, 1280):
ARTIFACTS.mkdir(parents=True, exist_ok=True)
self.page.screenshot(path=str(ARTIFACTS / f"{key}-{width}.png"))
def assert_grid(self, panel):
for grid in panel.locator(".policy-form .form-grid").all():
self.assertLessEqual(grid.bounding_box()["width"], 1024, "Settings should remain near 1000px on wide screens")
self.assertLessEqual(grid.evaluate("node => node.scrollWidth - node.clientWidth"), 1)
def toggle_and_save(self, checkbox, expected):
before = len(self.writes)
click_checkbox_text(self.page, checkbox)
expect(self.page.locator("#save-status")).to_have_text("修改待保存…")
self.wait_saved()
self.assertEqual(len(self.writes), before + 1, "One text click must produce one autosave")
self.assertEqual(self.writes[-1].post_data_json["config"], expected)
self.assertEqual(self.manager.get_config(self.first)["config"], expected)
def test_daily_choices_are_a_readable_group_below_enable_and_save_independently(self):
self.open()
panel = self.go("daily")
form = panel.locator(".policy-form")
enabled = self.field(form, ["daily_policy", "enabled"])
group = form.get_by_role("group", name="领取项目", exact=True)
for width, height in VIEWPORTS:
with self.subTest(width=width):
self.page.set_viewport_size({"width": width, "height": height})
self.screenshot("daily", width)
self.assert_grid(panel)
assert_checkbox_pair(self, enabled, "启用每日奖励领取")
expect(group.get_by_role("checkbox")).to_have_count(5)
self.assertEqual(group.locator("xpath=ancestor::label").count(), 0, "The options group must be separate from the enable label")
self.assertGreaterEqual(group.bounding_box()["y"], enabled.locator("xpath=ancestor::label").bounding_box()["y"]
+ enabled.locator("xpath=ancestor::label").bounding_box()["height"])
for _, label in DAILY_CHOICES:
assert_checkbox_pair(self, group.get_by_role("checkbox", name=label, exact=True), label)
self.page.set_viewport_size({"width": 1280, "height": 800})
expected = self.manager.get_config(self.first)["config"]
expected["daily_policy"]["enabled"] = not expected["daily_policy"]["enabled"]
self.toggle_and_save(enabled, expected)
for value, label in DAILY_CHOICES:
with self.subTest(choice=value):
selected = expected["daily_policy"]["selected"]
selected.remove(value)
self.toggle_and_save(group.get_by_role("checkbox", name=label, exact=True), expected)
self.assertEqual(enabled.is_checked(), expected["daily_policy"]["enabled"])
for peer, peer_label in DAILY_CHOICES:
self.assertEqual(group.get_by_role("checkbox", name=peer_label, exact=True).is_checked(), peer in selected)
self.assertEqual(expected["daily_policy"]["selected"], [])
def test_hatching_pairs_and_complete_stacked_labels_across_all_subtabs(self):
self.open()
panel = self.go("hatching")
form = panel.locator(".policy-form")
fields = self.manager.view(self.first, "hatching", {})["data"]["form"]
for width, height in VIEWPORTS:
self.page.set_viewport_size({"width": width, "height": height})
for tab in ("孵蛋策略", "牧场策略", "喂养策略"):
with self.subTest(width=width, tab=tab):
panel.locator(f'.subtab[data-key="{tab}"]').click()
if tab == "孵蛋策略":
self.screenshot("hatching", width)
self.assert_grid(panel)
for field in (field for field in fields if field.get("group") == tab):
control = self.field(form, field["path"])
if field["type"] == "boolean":
assert_checkbox_pair(self, control, field["label"])
elif field["type"] in ("integer", "select"):
expect(control).to_have_attribute("aria-label", field["label"])
geometry = control.evaluate("""node => {
const label = node.closest('.field').querySelector('.field-label');
const range = document.createRange(); range.selectNodeContents(label);
return {caption: label.textContent, label: label.getBoundingClientRect().toJSON(),
text: range.getBoundingClientRect().toJSON(), input: node.getBoundingClientRect().toJSON()};
}""")
self.assertEqual(geometry["caption"], field["label"])
self.assertLessEqual(geometry["label"]["bottom"], geometry["input"]["top"] + 1, geometry)
self.assertLessEqual(geometry["text"]["right"], geometry["label"]["right"] + 1, geometry)
self.assertLessEqual(geometry["text"]["bottom"], geometry["label"]["bottom"] + 1, geometry)
self.page.set_viewport_size({"width": 1280, "height": 800})
panel.locator('.subtab[data-key="孵蛋策略"]').click()
expected = self.manager.get_config(self.first)["config"]
for key in ("enabled", "buy", "fill", "dispatch", "collect"):
with self.subTest(toggle=key):
expected["policy"][key] = not expected["policy"][key]
self.toggle_and_save(self.field(form, ["policy", key]), expected)
for field in (field for field in fields if field.get("group") == "孵蛋策略" and field["type"] == "boolean"):
self.assertEqual(self.field(form, field["path"]).is_checked(), expected["policy"][field["path"][1]])
def test_remote_config_sync_preserves_focused_draft_and_control_identity(self):
self.open()
panel = self.go("hatching")
form = panel.locator(".policy-form")
count = self.field(form, ["policy", "buy_batch"])
peer = self.field(form, ["policy", "keep_money"])
original = count.element_handle()
count.fill("17")
self.wait_saved()
expect(count).to_be_focused()
self.assertEqual(self.manager.get_config(self.first)["config"]["policy"]["buy_batch"], 17)
count.fill("") # An incomplete numeric draft must survive a passive refresh.
before = len(self.writes)
remote = self.manager.get_config(self.first)["config"]
remote["policy"].update(buy_batch=19, keep_money=43210)
response = self.manager.set_config(self.first, remote)
self.await_job(self.first, response["job_id"])
expect(peer).to_have_value("43210", timeout=10000)
expect(count).to_have_value("")
expect(count).to_be_focused()
self.assertTrue(count.evaluate("(node, old) => node === old", original))
self.assertEqual(len(self.writes), before, "Passive server updates must not autosave a draft")
self.assertEqual(self.manager.get_config(self.first)["config"], remote)
def test_open_logs_leave_controls_in_bounds_and_bag_editors_inline(self):
self.open()
self.page.locator("#log-toggle").click()
expect(self.page.locator("#log-panel")).to_be_visible()
for width, height in VIEWPORTS:
self.page.set_viewport_size({"width": width, "height": height})
for key in ("daily", "hatching"):
with self.subTest(width=width, page=key):
panel = self.go(key)
geometry = panel.evaluate("""panel => {
const surface = panel.querySelector('.page-surface').getBoundingClientRect();
const log = document.querySelector('#log-panel').getBoundingClientRect();
const controls = [...panel.querySelectorAll('.policy-form input, .policy-form select, .page-toolbar button'),
...document.querySelectorAll('.run-controls button, .run-controls select')];
return {overflow: document.documentElement.scrollWidth - innerWidth,
overlap: document.querySelector('#workspace').getBoundingClientRect().bottom - log.top,
surfaceOverlap: surface.bottom - log.top,
outside: controls.filter(node => {const box = node.getBoundingClientRect();
return box.width && (box.left < 0 || box.right > innerWidth + 1);}).map(node => node.outerHTML)};
}""")
self.assertLessEqual(geometry["overflow"], 1, geometry)
self.assertLessEqual(geometry["overlap"], 1, geometry)
self.assertLessEqual(geometry["surfaceOverlap"], 1, geometry)
self.assertEqual(geometry["outside"], [], geometry)
for control in panel.locator(".policy-form input, .policy-form select, .page-toolbar button").all():
control.scroll_into_view_if_needed()
self.assertTrue(control.evaluate("""node => {
const box = node.getBoundingClientRect(), log = document.querySelector('#log-panel').getBoundingClientRect();
return box.bottom <= log.top + 1 && node.contains(document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2));
}"""), "Every main control must scroll into view without being covered by logs")
self.page.set_viewport_size({"width": 1280, "height": 800})
panel = self.go("bag")
row = panel.locator("tbody tr").first
species = row.get_attribute("data-row-id")
priority = row.locator('td[data-column="priority"] input')
action = row.locator('td[data-column="action"] select')
enabled = row.locator('td[data-column="enabled"] input')
self.assertEqual(row.locator(".field, .field-label").count(), 0)
for control in (priority, action, enabled):
self.assertLessEqual(control.bounding_box()["height"], 32)
self.assertLessEqual(priority.bounding_box()["width"], 130)
priority.fill("23")
action.select_option("keep")
enabled.check()
self.wait_saved()
rule = self.manager.get_config(self.first)["config"]["policy"]["egg_rules"][species]
self.assertEqual((rule["priority"], rule["action"], rule["enabled"]), (23, "keep", True))
if __name__ == "__main__":
unittest.main()
@@ -13,6 +13,7 @@ import time
import unittest
from urllib.parse import urlsplit
from ranch_web import __version__
from .test_workbench_browser import AVAILABLE, EDGE
if AVAILABLE:
@@ -315,7 +316,7 @@ class QuietUIBrowserTests(unittest.TestCase):
expect(spinner).to_have_attribute("aria-label", "加载中")
expect(spinner).to_have_text("")
expect(spinner.locator(".loading-spinner")).to_have_attribute("aria-hidden", "true")
expect(self.page.locator("#app-version")).to_have_text("2.0.5")
expect(self.page.locator("#app-version")).to_have_text(__version__)
expect(self.page.locator("#access-mode")).to_have_text("")
expect(self.page.locator("#log-panel")).to_have_count(1)
expect(self.page.locator('[role="log"]')).to_have_count(1)