"""Offline native sidebar geometry and navigation; requires the prebuilt loopback static server.""" import argparse import json import re from pathlib import Path from urllib.parse import parse_qs, urlsplit from playwright.sync_api import expect, sync_playwright from browser_contract import ACCOUNT, BRAND, LOGIN, PASS, SELF, USER, Fixture, loopback, menu ROOT = "数据统计" NESTED = "自录数据统计与跨部门综合分析报表导航" LEAF = "账户消耗录入与跨部门财务对账明细" OTHER = "运营管理与跨部门协作流程工作中心" TOP_LEAF = "独立账户消耗录入" HOME = "自录转化统计" DETAIL = "运营明细" HIDDEN = "仅后台可见明细" HIDDEN_ROOT = "隐藏目录" NAMES = "业务报表" SIMILAR = ("全院财务结算与跨部门对账月报表", "全院财务退款与跨部门对账月报表") DUPLICATE = "回访明细" TITLE = ".el-sub-menu__title" def setup_menu(fixture): roots = fixture.reads[SELF]["menu"] root, = roots nested, = root["children"] root["icon"] = "el-icon-Setting" nested.update(name=NESTED, icon="el-icon-Folder") # A real index child has an empty path. Its defaults must not disappear # when normalizing the trailing slash or when restoring a work tab. nested["children"][0]["params"] = '{"via":"index","dept":"QA 组"}' nested["children"][1].update(name=LEAF, icon="el-icon-Document") hidden = dict(menu(412, HIDDEN, "hidden", component="stats/self_input/account_cost"), is_show=0) roots.append(menu(410, OTHER, "operations", children=[ hidden, menu(411, DETAIL, "details?team=ops", component="stats/self_input/account_cost")])) roots.append(dict(menu(420, TOP_LEAF, "solo", component="stats/self_input/account_cost"), icon="local-icon-dingdan")) roots.append(dict(menu(430, HIDDEN_ROOT, "hidden-root", children=[ menu(431, "隐藏目录的明细", "not-listed", component="stats/self_input/account_cost")]), is_show=0)) roots.append(menu(440, NAMES, "reports", children=[ menu(i, name, f"r{i}", component="stats/self_input/account_cost") for i, name in enumerate([*SIMILAR, DUPLICATE, DUPLICATE], start=441) ])) # The source of visibility is the returned menu tree, not the table's business-button permissions. fixture.reads[SELF]["permissions"].remove("stats.personal_account_cost/add") def settle(element): # Vue starts CSS transitions on the next animation frames. Don't measure halfway through. element.evaluate("""async el => { const frame = () => new Promise(resolve => requestAnimationFrame(resolve)); await frame(); await frame(); const anims = el.getAnimations({subtree: true}).filter(a => a.effect?.getComputedTiming().endTime < Infinity); await Promise.allSettled(anims.map(a => a.finished)); await frame(); }""") def title(parent, name): return parent.locator(TITLE).filter(has=parent.page.get_by_text(name, exact=True)) def toggle(group_title, opened): item = group_title.locator("..") if item.get_attribute("aria-expanded") != str(opened).lower(): group_title.click() expect(item).to_have_attribute("aria-expanded", str(opened).lower()) settle(item) def label_metrics(row, name): return row.get_by_text(name, exact=True).evaluate("""el => { const range = document.createRange(); range.selectNodeContents(el); const text = range.getBoundingClientRect(), box = el.getBoundingClientRect(); // Text can extend beyond its range of painted pixels when an ancestor clips it. let right = text.right, ellipsis = false; const row = el.closest('.el-menu-item,.el-sub-menu__title'); for (let p = el; p && p !== row; p = p.parentElement) { const s = getComputedStyle(p); if (s.overflowX !== 'visible') { right = Math.min(right, p.getBoundingClientRect().right); ellipsis ||= s.textOverflow === 'ellipsis'; } } return {left: text.left, right, textRight: text.right, ellipsis, height: box.height} }""") def arrow_metrics(row, name): label = label_metrics(row, name) arrow = row.locator(".el-sub-menu__icon-arrow svg") expect(arrow).to_be_visible() result = arrow.evaluate(r"""svg => { const r = svg.getBoundingClientRect(); const row = svg.closest('.el-sub-menu__title'), b = row.getBoundingClientRect(); const x = r.x + r.width / 2, y = r.y + r.height / 2; // A zero-sized path, transparent paint, clipped SVG or covered row isn't a visible arrow. const painted = Array.from(svg.querySelectorAll('path,polygon,polyline,line,use')).some(p => { const ink = getComputedStyle(p), bounds = p.getBoundingClientRect(); return bounds.width > 1 && bounds.height > 1 && ink.visibility === 'visible' && ink.display !== 'none' && [ink.fill, ink.stroke].some(c => c && c !== 'none' && c !== 'transparent' && !/rgba\(.*?,\s*0\)$/.test(c)); }); let opacity = 1; for (let p = svg; p; p = p.parentElement) opacity *= +getComputedStyle(p).opacity; return {left:r.left, right:r.right, end:b.right, width:r.width, painted, opacity, hit:row.contains(document.elementFromPoint(x,y))}; }""") assert result["painted"] and result["hit"] and result["opacity"] > .5, (name, result) assert result["width"] >= 8 and -1 <= result["end"] - result["right"] <= 28, (name, result) assert label["height"] > 0 and label["left"] < label["right"] <= result["left"] - 1, (name, label, result) assert label["textRight"] <= label["right"] + 1 or label["ellipsis"], (name, label) return result["right"] def expanded(menu_el): r, n, o = (title(menu_el, name) for name in (ROOT, NESTED, OTHER)) toggle(r, True) toggle(n, True) leaf = menu_el.get_by_role("menuitem", name=LEAF, exact=True) expect(leaf).to_be_visible() rights = [arrow_metrics(row, name) for row, name in [(r, ROOT), (n, NESTED), (o, OTHER)]] assert max(rights) - min(rights) <= 1.5, ("arrow right track", rights) levels = [label_metrics(row, name)["left"] for row, name in [(r, ROOT), (n, NESTED), (leaf, LEAF)]] assert levels[0] + 4 < levels[1] and levels[1] + 4 < levels[2], ("label indentation", levels) return dict(arrow_right=rights, label_left=levels) def center(rail, target, name): expect(target).to_be_visible() a, b = rail.bounding_box(), target.bounding_box() expected, actual = a["x"] + a["width"] / 2, b["x"] + b["width"] / 2 assert abs(expected - actual) <= 1.5, (name, "rail center", expected, "element center", actual) return round(actual, 2) def screenshot(page, out, name): if out: page.screenshot(path=str(out / f"sidebar-{name}.png"), animations="disabled") def settings(page): page.locator(".app-header .setting").click() drawer = page.get_by_role("dialog", name="主题设置") expect(drawer.get_by_text("菜单栏宽度", exact=True)).to_be_visible() return drawer def close_settings(page, drawer): page.keyboard.press("Escape") expect(drawer).to_be_hidden() def route_at(page, path, query=None, *, trailing=False): # Require the actual browser address (and all its parameters), not only a Vue component. expected = "/admin/" + path expect(page).to_have_url(re.compile(re.escape(expected) + ("" if trailing else "/?") + r"(?:\?.*)?$")) parts = urlsplit(page.url) if query is not None: assert parse_qs(parts.query) == query, (path, query, parts.query) def layout(page, rail, panel=None, *, expected_width=None): settle(page.locator(".layout-default")) rb = rail.bounding_box() pb = panel.bounding_box() if panel is not None else None edge = rb["x"] + rb["width"] if pb: assert abs(pb["x"] - edge) <= 2, ("gap/overlap between rails", rb, pb) assert abs(pb["width"] - expected_width) <= 1, ("fixed second panel", pb, expected_width) edge = pb["x"] + pb["width"] main = page.locator("main").bounding_box() header = page.locator(".app-header").bounding_box() for el in (main, header): assert abs(el["x"] - edge) <= 2, ("content overlaps or leaves blank space", edge, el) assert abs(el["x"] + el["width"] - page.viewport_size["width"]) <= 2, el return {k: round(v, 1) for k, v in { "rail": rb["width"], "panel": pb["width"] if pb else 0, "main_x": main["x"]}.items()} def compact_layout(page, rail, panel, fold, baseline=None): expect(rail).to_be_visible() expect(fold).to_have_attribute("aria-expanded", "false") expect(panel).to_be_hidden() metrics = layout(page, rail) assert abs(metrics["rail"] - 64) <= 1, ("compact rail", metrics) assert abs(metrics["main_x"] - 64) <= 2, ("main should start next to the rail", metrics) if baseline is not None: assert metrics == baseline, ("drilling or resizing moved the content", metrics, baseline) # Measuring width alone would pass even with an absolutely positioned flyout over the page. expect(page.locator(".el-menu--popup:visible, .el-popover:visible, .el-drawer:visible")).to_have_count(0) assert rail.evaluate("""nav => { const b = nav.getBoundingClientRect(); return [...nav.querySelectorAll('a,button')].every(item => { const r = item.getBoundingClientRect(); return !r.width || (r.left >= b.left - 1 && r.right <= b.right + 1); }); }"""), "menu controls extend outside the compact rail" assert page.locator("main").evaluate("""main => { const b = main.getBoundingClientRect(); return [4, 64, 160].every(dx => [8, 64, 144].every(dy => main.contains(document.elementFromPoint(b.left + dx, b.top + dy)))); }"""), "sidebar flyout or backdrop intercepts the content" return metrics def compact_label(row): # A full title can be shortened on screen, but it may not collapse to a single glyph # or become tooltip-only. The full title remains the control's accessible name. label = row.locator(".compact-label") expect(label).to_be_visible() text = label.inner_text().strip() assert len(text) > 1 and row.get_attribute("title"), ("missing visible or full label", text) box, ink = row.bounding_box(), label.bounding_box() assert box["x"] - 1 <= ink["x"] and ink["x"] + ink["width"] <= box["x"] + box["width"] + 1 return text def clipped(row, selector, label): el = row.locator(selector) expect(row).to_have_accessible_name(label) expect(row).to_have_attribute("title", label) m = el.evaluate("""e => { const r = e.getBoundingClientRect(), row = e.closest('button,a').getBoundingClientRect(); return {w:e.clientWidth, full:e.scrollWidth, style:getComputedStyle(e).textOverflow, inside:r.left >= row.left && r.right <= row.right + 1}; }""") assert 0 < m["w"] < m["full"] and m["style"] == "ellipsis" and m["inside"], (label, m) return m def painted_bg(box): return box.evaluate("""el => { for (let p = el; p; p = p.parentElement) { const c = getComputedStyle(p).backgroundColor.match(/[0-9.]+/g)?.map(Number); if(c && (c.length === 3 || c[3] >= 0.99)) return c.slice(0,3); } return [255,255,255]; }""") def check(page, fixture, out): page.goto(fixture.base + "/admin/login") page.get_by_placeholder("请输入账号").fill(ACCOUNT) page.get_by_placeholder("请输入密码").fill(PASS) page.get_by_role("button", name="登录", exact=True).click() expect(page.locator(".app-header").get_by_text(USER, exact=True)).to_be_visible(timeout=15000) expect(page.locator("html")).to_have_attribute("data-admin-ui", "v2") rail = page.get_by_role("navigation", name="一级菜单", exact=True) compact = page.get_by_role("navigation", name="折叠菜单", exact=True) panel = page.get_by_role("navigation", name="二级菜单", exact=True) root = rail.get_by_role("button", name=ROOT, exact=True) other = rail.get_by_role("button", name=OTHER, exact=True) solo = rail.get_by_role("link", name=TOP_LEAF, exact=True) branch = panel.get_by_role("button", name=NESTED, exact=True) home = panel.get_by_role("link", name=HOME, exact=True) cost = panel.get_by_role("link", name=LEAF, exact=True) detail = panel.get_by_role("link", name=DETAIL, exact=True) fold = page.locator(".app-header .fold") tab = lambda name: page.locator(".app-tabs").get_by_role("tab", name=name, exact=True) h_path, h_query = "stats/self_input", {"via": ["index"], "dept": ["QA 组"]} c_path, c_query = "stats/self_input/account_cost", {"via": ["sidebar"]} d_path, d_query = "operations/details", {"team": ["ops"]} def selected(group, leaf): expect(rail.locator(".is-active")).to_have_count(1) expect(group).to_have_class(re.compile(r"\bis-active\b")) expect(leaf).to_have_attribute("aria-current", "page") route_at(page, h_path + "/", trailing=True) expect(tab(HOME)).to_have_count(1) expect(home).to_be_visible() selected(root, home) expect(rail.get_by_text(HIDDEN_ROOT, exact=True)).to_have_count(0) report = {"expanded": layout(page, rail, panel, expected_width=230)} for width in (1216, 1440): page.set_viewport_size({"width": width, "height": 960}) assert layout(page, rail, panel, expected_width=230) == report["expanded"] logo = rail.locator(".logo img") expect(logo).to_have_attribute("src", BRAND) assert logo.evaluate("img => img.complete && img.naturalWidth > 0") center(rail, logo, "logo") report["long_labels"] = [clipped(other, ".dual-root-label", OTHER), clipped(branch, ".dual-label", NESTED), clipped(cost, ".dual-label", LEAF)] tag = branch.locator(".dual-label").bounding_box() arrow = branch.locator(".dual-chevron") expect(arrow).to_be_visible() assert tag["x"] + tag["width"] < arrow.bounding_box()["x"] assert cost.locator(".dual-label").bounding_box()["x"] > tag["x"] + 4 screenshot(page, out, "expanded") # Mouse movements must not navigate, replace a selected root, or close the persistent panel. other.hover() page.locator("main").hover() page.wait_for_timeout(650) # Longer than Element Plus's legacy hover/flyout close delay. expect(home).to_be_visible() selected(root, home) expect(page.locator(".el-menu--popup:visible")).to_have_count(0) # Traverse the actual second/third level from the button, not simulated router pushes. branch.focus() orientation = "el => getComputedStyle(el).transform" opened_angle = arrow.evaluate(orientation) page.keyboard.press("Enter") expect(branch).to_have_attribute("aria-expanded", "false") expect(cost).to_be_hidden() settle(branch) assert opened_angle != arrow.evaluate(orientation), "directory chevron did not change direction" page.keyboard.press("Space") expect(branch).to_have_attribute("aria-expanded", "true") page.keyboard.press("Tab") expect(home).to_be_focused() page.keyboard.press("Tab") expect(cost).to_be_focused() page.keyboard.press("Enter") route_at(page, c_path, c_query) selected(root, cost) cost_page = page.locator("main .personal-account-cost-page") expect(cost_page).to_be_visible() expect(cost_page.get_by_role("button", name="新增", exact=True)).to_have_count(0) # The startup redirect includes a final slash; the clicked index child omits it. # Only one work tab survives this normalization, keeping its latest query intact. home.click() route_at(page, h_path, h_query, trailing=True) expect(tab(HOME)).to_have_count(1) expect(tab(HOME)).to_have_attribute("aria-selected", "true") selected(root, home) other.click() route_at(page, d_path, d_query) selected(other, detail) expect(panel.get_by_text(HIDDEN, exact=True)).to_have_count(0) expect(branch).to_have_count(0) expect(cost_page).to_be_visible() expect(detail).to_be_visible() page.go_back() route_at(page, h_path, h_query) selected(root, home) page.go_forward() route_at(page, d_path, d_query) selected(other, detail) tab(HOME).click() route_at(page, h_path, h_query) selected(root, home) tab(DETAIL).click() route_at(page, d_path, d_query) selected(other, detail) page.reload() route_at(page, d_path, d_query) selected(other, detail) expect(cost_page).to_be_visible() assert layout(page, rail, panel, expected_width=230) == report["expanded"] solo.click() route_at(page, "solo", {}) expect(solo).to_have_attribute("aria-current", "page") expect(cost_page).to_be_visible() expect(panel).to_be_hidden() report["direct_leaf"] = layout(page, rail) root.click() route_at(page, h_path, h_query) selected(root, home) expect(fold).to_have_attribute("aria-expanded", "true") fold.press("Enter") report["collapsed"] = compact_layout(page, compact, panel, fold) def unchanged(): return compact_layout(page, compact, panel, fold, report["collapsed"]) group = lambda name: compact.get_by_role("button", name=name, exact=True) entry = lambda name: compact.get_by_role("link", name=name, exact=True) back = group("返回上一级") page.set_viewport_size({"width": 1350, "height": 960}) unchanged() expect(back).to_be_hidden() expect(group(HIDDEN_ROOT)).to_have_count(0) report["collapsed_centers"] = {"logo": center(compact, compact.locator(".logo img"), "brand image")} for name, row in ((ROOT, group(ROOT)), (OTHER, group(OTHER)), (TOP_LEAF, entry(TOP_LEAF))): compact_label(row) expect(row).to_have_attribute("title", name) report["collapsed_centers"][name] = center(compact, row.locator(".compact-icon svg"), name) screenshot(page, out, "collapsed") # Similar and identical sibling names must be distinguishable without hovering. group(NAMES).click() assert compact_label(entry(SIMILAR[0])) != compact_label(entry(SIMILAR[1])) twins = compact.get_by_role("link", name=re.compile("^" + DUPLICATE)) expect(twins).to_have_count(2) assert twins.nth(0).inner_text() != twins.nth(1).inner_text() assert twins.nth(0).get_attribute("aria-label") != twins.nth(1).get_attribute("aria-label") route_at(page, h_path, h_query) unchanged() back.click() expect(group(NAMES)).to_be_focused() # Browsing directories (including one with only one permitted child) never chooses a route. group(OTHER).hover() page.wait_for_timeout(650) # Exercise the legacy Element Plus hover-to-open delay. unchanged() expect(entry(DETAIL)).to_be_hidden() group(OTHER).press("Enter") expect(entry(DETAIL)).to_be_focused() expect(entry(HIDDEN)).to_have_count(0) route_at(page, h_path, h_query) unchanged() back.press("Space") expect(group(OTHER)).to_be_focused() route_at(page, h_path, h_query) unchanged() group(ROOT).click() expect(group(NESTED)).to_be_focused() expect(entry(LEAF)).to_be_hidden() route_at(page, h_path, h_query) unchanged() group(NESTED).press("Space") expect(entry(HOME)).to_be_focused() compact_label(entry(LEAF)) expect(group(ROOT)).to_be_hidden() route_at(page, h_path, h_query) unchanged() screenshot(page, out, "collapsed-third-level") page.keyboard.press("Tab") expect(entry(LEAF)).to_be_focused() page.keyboard.press("Enter") route_at(page, c_path, c_query) expect(cost_page).to_be_visible() expect(entry(LEAF)).to_have_attribute("aria-current", "page") unchanged() back.click() expect(group(NESTED)).to_be_focused() back.press("Enter") expect(group(ROOT)).to_be_focused() expect(back).to_be_hidden() route_at(page, c_path, c_query) unchanged() entry(TOP_LEAF).click() route_at(page, "solo", {}) expect(entry(TOP_LEAF)).to_have_attribute("aria-current", "page") unchanged() group(OTHER).click() route_at(page, "solo", {}) entry(DETAIL).click() route_at(page, d_path, d_query) expect(entry(DETAIL)).to_have_attribute("aria-current", "page") unchanged() page.reload() route_at(page, d_path, d_query) expect(cost_page).to_be_visible() unchanged() # The mobile drawer starts closed, performs real link navigation, then closes. Neither # opening it nor choosing a link changes the desktop preference saved by the fold button. page.set_viewport_size({"width": 390, "height": 844}) expect(compact).to_be_hidden() expect(rail).to_be_hidden() expect(panel).to_be_hidden() mobile = page.locator(".el-drawer:visible .side") expect(mobile).to_be_hidden() fold.click() expect(mobile).to_be_visible() settle(mobile.locator("xpath=ancestor::*[contains(@class, 'el-overlay')][1]")) report["mobile_drawer"] = expanded(mobile.locator(".menu")) screenshot(page, out, "mobile") mobile.get_by_role("link", name=LEAF, exact=True).click() expect(mobile).to_be_hidden() route_at(page, c_path, c_query) expect(cost_page).to_be_visible() page.set_viewport_size({"width": 1440, "height": 960}) unchanged() # Only the explicit header control restores the wide, fixed second column. fold.press("Enter") expect(fold).to_have_attribute("aria-expanded", "true") expect(compact).to_be_hidden() selected(root, cost) route_at(page, c_path, c_query) assert layout(page, rail, panel, expected_width=230) == report["expanded"] page.reload() selected(root, cost) expect(fold).to_have_attribute("aria-expanded", "true") assert layout(page, rail, panel, expected_width=230) == report["expanded"] drawer = settings(page) logo_item = drawer.locator(".setting-item").filter(has_text="显示LOGO") logo_item.locator(".el-switch__core").click() expect(logo_item.get_by_role("switch")).not_to_be_checked() drawer.get_by_role("button", name="深色菜单").click() width = drawer.get_by_role("spinbutton") width.fill("180") width.press("Enter") close_settings(page, drawer) root.click() selected(root, home) expect(logo).to_be_hidden() fallback = rail.locator(".admin-nav-heading svg") center(rail, fallback, "no-logo icon") report["dark_180px"] = layout(page, rail, panel, expected_width=180) report["dark_rgb"] = [painted_bg(rail), painted_bg(panel)] assert all(max(rgb) < 145 for rgb in report["dark_rgb"]), report["dark_rgb"] screenshot(page, out, "dark-180") # Resize with the drawer *open*: Element Plus emits update:modelValue(false) # after its leave animation, by which time the desktop sidebar is visible again. page.set_viewport_size({"width": 390, "height": 844}) expect(rail).to_be_hidden() expect(mobile).to_be_hidden() fold.click() expect(mobile).to_be_visible() settle(mobile.locator("xpath=ancestor::*[contains(@class, 'el-overlay')][1]")) page.set_viewport_size({"width": 1440, "height": 960}) expect(mobile).to_be_hidden() settle(page.locator(".layout-default")) expect(fold).to_have_attribute("aria-expanded", "true") selected(root, home) assert layout(page, rail, panel, expected_width=180) == report["dark_180px"] # Switch through the user's settings, not injected CSS/localStorage. cost.click() route_at(page, c_path, c_query) drawer = settings(page) drawer.get_by_text("经典", exact=True).click() close_settings(page, drawer) expect(page.locator("html")).to_have_attribute("data-admin-ui", "legacy") expect(rail).to_be_hidden() expect(panel).to_be_hidden() tree = page.locator(".app-aside .menu--classic:visible") toggle(title(tree, ROOT), True) toggle(title(tree, NESTED), True) tree.get_by_role("link", name=HOME, exact=True).click() route_at(page, h_path, h_query) expect(page.locator("main .self-input-stats-page")).to_be_visible() screenshot(page, out, "classic") return report def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--host", type=loopback, default="127.0.0.1:5179") parser.add_argument("--out", type=Path, help="Optional local screenshots directory") args = parser.parse_args() if args.out: args.out.mkdir(parents=True, exist_ok=True) fixture = Fixture(args.host, False, False) setup_menu(fixture) with sync_playwright() as pw, pw.chromium.launch(headless=True, args=[ "--disable-background-networking", "--disable-quic", "--no-proxy-server", "--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"]) as browser: with browser.new_context(service_workers="block", viewport={"width": 1440, "height": 960}, color_scheme="light") as ctx: ctx.set_default_timeout(8000) ctx.route("**/*", fixture.route) ctx.route_web_socket("**/*", lambda ws: (fixture.errors.append("unexpected WebSocket"), ws.close())) ctx.on("page", lambda p: p.on("pageerror", lambda e: fixture.errors.append(str(e)))) page = ctx.new_page() try: report = check(page, fixture, args.out) assert [p for method, p in fixture.calls if method == "POST"] == [LOGIN], fixture.calls assert not fixture.errors, fixture.errors except Exception: screenshot(page, args.out, "failure") print("mocked:", fixture.calls, "errors:", fixture.errors, flush=True) raise print(json.dumps({"sidebar": "PASS", "real_api_calls": 0, **report}, ensure_ascii=False)) if __name__ == "__main__": main()