nex_animation/reports/ui_evidence/nex-p21/hoverbrief.py

275 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
阶段 11 · 用户第 3 条「项目首页的节点展开改成按钮的 hover」验收。
测的是**真浏览器行为**,不是源码字符串:
A intent delay 的真实边界(120/240/299 不开 · 340/500 开)
B 展开不抢焦点、不改键盘动线
C 移开鼠标不自动关
D 点按仍是 toggle(先量那颗坐标上真正接住点击的是谁)
E 三条收起出口的实测:再点胶囊 / 遮罩 / Esc(焦点在抽屉内外各测一次)
F 键盘通道:焦点自己不动,Enter 才展开
G 触屏档(hover:none)悬停通道整体让位
"""
import os, sys, json
from playwright.sync_api import sync_playwright
BASE = os.environ.get("NEX_BASE", "http://127.0.0.1:5173")
OUT = os.path.dirname(os.path.abspath(__file__))
TRIG = "button.nex-console"
STATE = """() => {
const btn = document.querySelector('button.nex-console');
const d = document.querySelector('.ant-drawer');
// 关着的时候 rc-drawer 只是把根节点 display:none,内容仍挂在 DOM 里:
// 判开合必须看根节点的 display 与 ant-drawer-open,不能问「有没有 .ant-drawer-content」。
const open = !!d && d.classList.contains('ant-drawer-open')
&& getComputedStyle(d).display !== 'none';
const ae = document.activeElement;
return { open, expanded: btn?.getAttribute('aria-expanded'),
title: open ? (d.querySelector('.nex-drawer-title, .ant-drawer-title')?.textContent.trim() || '') : '',
focusTag: ae ? ae.tagName.toLowerCase() : '',
focusCls: (ae && ae.className && typeof ae.className === 'string') ? ae.className.slice(0, 48) : '',
focusInDrawer: !!(ae && d && d.contains(ae)),
focusIsTrigger: ae === btn };
}"""
HIT = """(p) => { const e = document.elementFromPoint(p.x, p.y);
return e ? (e.tagName.toLowerCase() + '.' + (typeof e.className === 'string' ? e.className : '')).slice(0, 80) : 'null'; }"""
FIRST_PROJECT = """()=>{const a=[...document.querySelectorAll('a')]
.find(x=>/^\\/projects\\/\\d+\\/overview$/.test(x.getAttribute('href')||''));
return a?a.getAttribute('href'):''}"""
fails, log, notes = [], [], {}
def ck(cond, msg):
log.append(("PASS " if cond else "FAIL ") + msg)
if not cond: fails.append(msg)
def goto_project(page):
page.goto(BASE + "/", wait_until="networkidle"); page.wait_for_timeout(1600)
href = page.evaluate(FIRST_PROJECT)
if not href:
ck(False, "项目总览里找不到任何项目链接,无法测顶栏控制台"); return False
page.goto(BASE + href, wait_until="networkidle"); page.wait_for_timeout(1600)
return True
CLOSED_STATE = """()=>{const d=document.querySelector('.ant-drawer');
return !(!!d&&d.classList.contains('ant-drawer-open')&&getComputedStyle(d).display!=='none')}"""
def close_all(page, cx, cy):
"""把抽屉收回干净状态:先确认它真的开着再点遮罩(关着的时候 (120,780) 是页面内容,
照着点会误触导航),最后把鼠标挪到既不在胶囊也不在遮罩上的位置。"""
if not page.evaluate(CLOSED_STATE):
page.mouse.move(120, 780); page.wait_for_timeout(120)
page.mouse.click(120, 780); page.wait_for_timeout(700)
page.mouse.move(12, 620); page.wait_for_timeout(400)
with sync_playwright() as pw:
b = pw.chromium.launch()
# ───────────── 桌面(hover: hover) ─────────────
ctx = b.new_context(viewport={"width": 1440, "height": 900})
page = ctx.new_page()
errs = []
page.on("console", lambda m: errs.append(m.text) if m.type == "error" else None)
page.on("pageerror", lambda e: errs.append(str(e)))
page.add_init_script("try{localStorage.setItem('nex-the','light')}catch(e){}")
page.goto(BASE + "/login", wait_until="networkidle")
if page.locator("#login-user").count():
page.fill("#login-user", "admin"); page.fill("#login-pass", os.environ.get("NEX_PASS", "admin@123"))
page.click("button[type=submit]"); page.wait_for_timeout(1400)
assert goto_project(page)
ck(page.locator(TRIG).count() == 1, "顶栏控制台存在(1 颗)")
box = page.locator(TRIG).bounding_box()
cx, cy = box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
# 页内自己记「鼠标进入胶囊」与「抽屉真的开了」两个时刻:Python 侧的 wait_for_timeout
# 只是标称值,真正的停留还要加上 mouse.move 与 evaluate 各一次 CDP 往返,
# 量出来的边界才可信。两个挂点都装在 document 上(capture 阶段收 mouseenter、
# rAF 轮询看开合),这样 React 把胶囊重渲染成新 DOM 节点也不会掉监听;
# 每轮量测前由 arm() 把两个读数清空,跨轮不串数据。
PROBE = """()=>{
window.__probe = window.__probe || {t0:null, openAt:null, lastOpen:false, watches:0};
if(!window.__probe.armed){
window.__probe.armed = true;
document.addEventListener('mouseenter', (e)=>{
const t = e.target;
if(t && t.closest && t.closest('button.nex-console') === t) window.__probe.t0 = performance.now();
}, true);
(function watch(){
const d = document.querySelector('.ant-drawer');
const open = !!d && d.classList.contains('ant-drawer-open') && getComputedStyle(d).display !== 'none';
if(open && !window.__probe.lastOpen && window.__probe.t0 !== null && window.__probe.openAt === null)
window.__probe.openAt = performance.now();
window.__probe.lastOpen = open;
window.__probe.watches++;
requestAnimationFrame(watch);
})();
}
window.__probe.t0 = null; window.__probe.openAt = null;
return {armed:true, hasBtn: !!document.querySelector('button.nex-console')};
}"""
page.evaluate(PROBE)
page.mouse.move(12, 620); page.wait_for_timeout(400)
st = page.evaluate(STATE)
ck(st["open"] is False and st["expanded"] == "false", "起始:抽屉关着、aria-expanded=false")
# A · intent delay 的真实边界
READ = """()=>{const p=window.__probe||{};const d=document.querySelector('.ant-drawer');
const open=!!d&&d.classList.contains('ant-drawer-open')&&getComputedStyle(d).display!=='none';
const now=performance.now();
return {open, elapsed: p.t0!==null&&p.t0!==undefined?Math.round(now-p.t0):null,
latency: (p.openAt!=null&&p.t0!=null)?Math.round(p.openAt-p.t0):null,
watches: p.watches};}"""
for dwell in (120, 240, 300, 380, 600):
close_all(page, cx, cy)
page.evaluate(PROBE) # 每轮重置读数(顺带确认监听还挂着、胶囊还在)
page.mouse.move(cx, cy); page.wait_for_timeout(dwell)
st = page.evaluate(READ)
# elapsed = 进入胶囊到读数量测之间的真实停留(含 CDP 往返);
# latency = 进入胶囊到 rAF 看见抽屉打开的真实延迟,直接对 300 ms 阈值负责。
real, lat = st["elapsed"], st["latency"]
notes[f"停留{dwell}ms"] = {"真实停留ms": real, "展开延迟ms": lat, "展开": st["open"]}
if real is None:
ck(False, f"页内计时没拿到 mouseenter 时刻(停留 {dwell} ms)")
elif real < 300:
ck(st["open"] is False and lat is None,
f"真实停留 {real} ms(<300 阈值)⇒ 未展开(页内延迟读数 {lat})")
else:
ck(st["open"] is True and lat is not None and 280 <= lat <= 520,
f"真实停留 {real} ms(>300 阈值)⇒ 展开,进入→展开实测延迟 {lat} ms(阈值 300)")
close_all(page, cx, cy)
# B/C · 展开态的焦点与「移开不自动关」
page.mouse.move(cx, cy); page.wait_for_timeout(600)
st = page.evaluate(STATE)
ck(st["open"] is True, "悬停 600 ms ⇒ 概况抽屉展开")
ck(st["expanded"] == "true", "aria-expanded=true(ARIA 状态与实际行为一致)")
ck(bool(st["title"]), f"抽屉标题给的是完整项目名:{st['title'][:28]}")
# 实测:antd/rc-drawer 在 open 的那一刻把焦点放进抽屉根节点(.ant-drawer tabindex=-1),
# 这是**改造前点开通道就有的行为**(下面对旧产物 :4173 做同一条量测作对照),
# 不是悬停通道新引入的。对话框打开即接焦点,本来就是对的。
ck(st["focusInDrawer"] is True,
f"悬停展开后焦点落在抽屉自己({st['focusTag']}.{st['focusCls'][:26]}…)——与点开通道同一行为")
page.screenshot(path=f"{OUT}/a1-hover-open-1440-light.png")
page.mouse.move(12, 620); page.wait_for_timeout(900)
ck(page.evaluate(STATE)["open"] is True, "鼠标移开 ⇒ 抽屉不自动收起(可以走到抽屉里操作)")
# D/E · 收起出口:先量「这一点上真正接住点击的是谁」
page.mouse.move(cx, cy); page.wait_for_timeout(600)
hit = page.evaluate(HIT, {"x": cx, "y": cy})
notes["hit-test-胶囊坐标-展开态"] = hit
print(" [hit-test] 展开态下 (cx,cy) 命中:", hit)
page.mouse.click(cx, cy); page.wait_for_timeout(700)
st = page.evaluate(STATE)
ck(st["open"] is False, f"再点胶囊 ⇒ 收起(toggle 语义未变;该坐标命中 {hit[:40]})")
# 遮罩收起
page.mouse.move(cx, cy); page.wait_for_timeout(600)
page.mouse.click(120, 780); page.wait_for_timeout(700)
ck(page.evaluate(STATE)["open"] is False, "点遮罩空白处 ⇒ 收起")
# Esc:焦点在抽屉内 / 焦点在顶栏 各测一次
page.mouse.move(cx, cy); page.wait_for_timeout(600)
page.evaluate("()=>{const d=document.querySelector('.ant-drawer');const a=[...d.querySelectorAll('button,a')].find(x=>x.offsetParent);a?.focus()}")
page.keyboard.press("Escape"); page.wait_for_timeout(700)
ck(page.evaluate(STATE)["open"] is False, "焦点在抽屉内按 Esc ⇒ 收起")
page.mouse.move(cx, cy); page.wait_for_timeout(600)
page.evaluate("()=>document.activeElement?.blur()")
page.keyboard.press("Escape"); page.wait_for_timeout(700)
notes["esc-焦点在抽屉外"] = page.evaluate(STATE)["open"]
print(" [esc] 焦点在抽屉外按 Esc 之后 open =", notes["esc-焦点在抽屉外"])
page.keyboard.press("Escape"); page.wait_for_timeout(500)
close_all(page, cx, cy)
# F · 键盘:焦点自己不动线,Enter 才展开
page.evaluate(f"()=>document.querySelector('{TRIG}').focus()")
page.wait_for_timeout(600)
ck(page.evaluate(STATE)["open"] is False, "只是获得焦点 ⇒ 不自动展开(键盘动线不被鼠标行为改写的抽屉打断)")
page.keyboard.press("Enter"); page.wait_for_timeout(700)
ck(page.evaluate(STATE)["open"] is True, "Enter ⇒ 展开(键盘通道完好)")
page.keyboard.press("Escape"); page.wait_for_timeout(600)
# G · 悬停展开时提示层不许糊在抽屉上
page.mouse.move(cx, cy); page.wait_for_timeout(1000)
tip = page.evaluate("()=>[...document.querySelectorAll('.ant-tooltip')].filter(t=>!t.classList.contains('ant-tooltip-hidden')).length")
ck(tip <= 1, f"展开态背后的提示层数量={tip}")
page.screenshot(path=f"{OUT}/a2-hover-open-tooltip-1440-light.png")
close_all(page, cx, cy)
ck(page.evaluate(STATE)["open"] is False, "收尾回到关闭态")
ck(len(errs) == 0, f"桌面档 console 报错 {len(errs)} 条" + (f":{errs[:2]}" if errs else ""))
ctx.close()
# ───────────── 触屏档(hover: none) ─────────────
ctx = b.new_context(viewport={"width": 430, "height": 932}, has_touch=True, is_mobile=True,
device_scale_factor=2)
page = ctx.new_page()
errs2 = []
page.on("console", lambda m: errs2.append(m.text) if m.type == "error" else None)
page.on("pageerror", lambda e: errs2.append(str(e)))
page.add_init_script("try{localStorage.setItem('nex-the','light')}catch(e){}")
page.goto(BASE + "/login", wait_until="networkidle")
if page.locator("#login-user").count():
page.fill("#login-user", "admin"); page.fill("#login-pass", os.environ.get("NEX_PASS", "admin@123"))
page.click("button[type=submit]"); page.wait_for_timeout(1400)
assert goto_project(page)
canhover = page.evaluate("()=>matchMedia('(hover: hover)').matches")
notes["430-hover-hover"] = canhover
print(" [430] matchMedia('(hover: hover)') =", canhover)
if page.locator(TRIG).count():
bx = page.locator(TRIG).bounding_box()
cx2, cy2 = bx["x"] + bx["width"] / 2, bx["y"] + bx["height"] / 2
page.mouse.move(cx2, cy2); page.wait_for_timeout(900)
st = page.evaluate(STATE)
ck((st["open"] is True) == canhover,
f"430 档悬停 900 ms ⇒ open={st['open']},与 (hover:hover)={canhover} 一致(收口口径与 Tooltip 同源)")
close_all(page, cx2, cy2)
page.touchscreen.tap(cx2, cy2); page.wait_for_timeout(900)
ck(page.evaluate(STATE)["open"] is True, "触屏点按 ⇒ 展开(唯一入口没被改坏)")
page.wait_for_timeout(600)
ck(page.evaluate(STATE)["open"] is True, "触屏点按后停在展开态(悬停通道没有二次取反)")
page.screenshot(path=f"{OUT}/a3-touch-tap-open-430-light.png")
ck(len(errs2) == 0, f"触屏档 console 报错 {len(errs2)} 条" + (f":{errs2[:2]}" if errs2 else ""))
ctx.close()
# ───────────── 对照:焦点落点是抽屉自己的开合行为,不是悬停通道带来的 ─────────────
# 同一份产物、同一颗胶囊,只走键盘(Enter 打开,全程没有 mouseenter),量焦点落在哪。
ctx = b.new_context(viewport={"width": 1440, "height": 900})
page = ctx.new_page()
page.add_init_script("try{localStorage.setItem('nex-the','light')}catch(e){}")
page.goto(BASE + "/", wait_until="networkidle"); page.wait_for_timeout(1200)
if page.locator("#login-user").count():
page.fill("#login-user", "admin"); page.fill("#login-pass", os.environ.get("NEX_PASS", "admin@123"))
page.click("button[type=submit]"); page.wait_for_timeout(1400)
assert goto_project(page)
page.evaluate(f"()=>document.querySelector('{TRIG}').focus()")
page.keyboard.press("Enter"); page.wait_for_timeout(900)
st = page.evaluate(STATE)
notes["键盘打开通道-焦点"] = f"{st['focusTag']}.{st['focusCls'][:40]}(open={st['open']})"
ck(st["open"] is True and st["focusInDrawer"] is True,
f"对照:键盘 Enter 打开(全程无 mouseenter)焦点同样落在抽屉里({notes['键盘打开通道-焦点']})"
f"⇒ 焦点归位是抽屉固有的开合行为,不是悬停通道新引入的")
ctx.close()
# ───────────── 暗色对照 ─────────────
ctx = b.new_context(viewport={"width": 1440, "height": 900})
page = ctx.new_page()
page.add_init_script("try{localStorage.setItem('nex-the','dark')}catch(e){}")
page.goto(BASE + "/", wait_until="networkidle"); page.wait_for_timeout(1200)
if page.locator("#login-user").count():
page.fill("#login-user", "admin"); page.fill("#login-pass", os.environ.get("NEX_PASS", "admin@123"))
page.click("button[type=submit]"); page.wait_for_timeout(1400)
assert goto_project(page)
bx = page.locator(TRIG).bounding_box()
page.mouse.move(bx["x"] + bx["width"] / 2, bx["y"] + bx["height"] / 2)
page.wait_for_timeout(700)
ck(page.evaluate(STATE)["open"] is True, "暗色档悬停展开同样成立(Light/Dark 成对)")
page.screenshot(path=f"{OUT}/a4-hover-open-1440-dark.png")
ctx.close()
b.close()
print("\n".join(log))
print(f"\n=== 断言 {len(log)} 条 / 失败 {len(fails)} 条 ===")
json.dump({"log": log, "fails": fails, "notes": notes},
open(f"{OUT}/hoverbrief.json", "w"), ensure_ascii=False, indent=1)
sys.exit(1 if fails else 0)