feat(admin): 增加启动与导航反馈并保护工作标签状态
This commit is contained in:
@@ -66,7 +66,7 @@ class Fixture:
|
||||
if (url.scheme, url.netloc) == ("http", self.host):
|
||||
if req.method == "GET" and (url.path.startswith("/admin/assets/") or
|
||||
(req.resource_type == "document" and url.path.startswith("/admin/")) or
|
||||
url.path in ("/favicon.ico", "/admin/favicon.ico")):
|
||||
url.path in ("/favicon.ico", "/admin/favicon.ico", "/admin/admin-loading.css", "/admin/admin-boot.js")):
|
||||
return route.continue_()
|
||||
return deny("unexpected local request")
|
||||
if f"{url.scheme}://{url.netloc}" != OFFICIAL:
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Cold startup, slow navigation, tab lifetime, recovery and reduced motion. Offline only."""
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
|
||||
from browser_contract import ACCOUNT, PASS, USER, SELF, OVERVIEW, LOGIN, TOKEN, Fixture, desktop_entry, loopback, menu
|
||||
|
||||
CHROME_ARGS = ["--disable-background-networking","--disable-quic","--no-proxy-server",
|
||||
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"]
|
||||
|
||||
|
||||
def snapshot(page, out, name):
|
||||
if out:
|
||||
page.screenshot(path=str(out / (name + ".png")), animations="disabled")
|
||||
|
||||
|
||||
def setup(browser, host, *, dark=False, reduce=False):
|
||||
fx = Fixture(host, False, False)
|
||||
pages = fx.reads[SELF]["menu"][0]["children"][0]["children"]
|
||||
pages.append(menu(409, "复核记录", "review", component="stats/self_input/index"))
|
||||
for leaf in pages:
|
||||
leaf["is_cache"] = 1
|
||||
ctx = browser.new_context(service_workers="block", viewport={"width":1400,"height":900},
|
||||
color_scheme="dark" if dark else "light", reduced_motion="reduce" if reduce else "no-preference")
|
||||
ctx.route("**/*", fx.route)
|
||||
ctx.route_web_socket("**/*", lambda ws: (fx.errors.append("unexpected websocket"),ws.close()))
|
||||
return ctx,fx,ctx.new_page()
|
||||
|
||||
|
||||
def wait_for_request(page, held):
|
||||
for _ in range(150):
|
||||
if held: return
|
||||
page.wait_for_timeout(25)
|
||||
raise AssertionError("expected lazy asset was not requested")
|
||||
|
||||
|
||||
def boot(browser, host, out, reduce, fail=False):
|
||||
ctx, fx, page = setup(browser,host,dark=reduce,reduce=reduce)
|
||||
held=[]
|
||||
# Keep the entry pending to allow the first HTML paint; release only to verified loopback assets.
|
||||
def hold(route):
|
||||
if (route.request.url.startswith(fx.base+"/admin/assets/") and route.request.resource_type=="script"
|
||||
and page.url.startswith(fx.base) and not held):
|
||||
held.append(route)
|
||||
else: route.fallback()
|
||||
page.route("**/assets/**",hold)
|
||||
page.goto(fx.base+"/admin/login",wait_until="commit")
|
||||
mark=page.locator("#admin-boot")
|
||||
expect(mark).to_be_visible()
|
||||
expect(mark.get_by_role("status")).to_contain_text("正在打开")
|
||||
wait_for_request(page,held)
|
||||
page.wait_for_function("() => !!document.querySelector('link[href*=\u0022admin-loading.css\u0022]')?.sheet")
|
||||
motion=mark.locator(".boot-mark").evaluate("e => getComputedStyle(e).animationName")
|
||||
assert (motion=="none") == reduce,(motion,reduce)
|
||||
snapshot(page,out,"boot-dark-reduced" if reduce else "boot-light")
|
||||
if fail:
|
||||
held[0].abort("failed")
|
||||
expect(mark).to_have_attribute("data-state","error",timeout=6500)
|
||||
snapshot(page,out,"boot-error")
|
||||
page.unroute("**/assets/**",hold)
|
||||
mark.get_by_role("link",name="重新加载").click()
|
||||
else:
|
||||
held[0].continue_()
|
||||
expect(mark).to_have_count(0,timeout=15000)
|
||||
expect(page.get_by_placeholder("请输入账号")).to_be_visible()
|
||||
assert not fx.errors,fx.errors
|
||||
ctx.close()
|
||||
return {"motion":motion,"manual_recovery":fail}
|
||||
|
||||
|
||||
def journey(browser,host,out):
|
||||
ctx,fx,page=setup(browser,host)
|
||||
page.goto(fx.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")).to_contain_text(USER)
|
||||
stats=page.locator("main .self-input-stats-page");expect(stats.get_by_text("OFFLINE-today",exact=True)).to_be_visible()
|
||||
bar=page.locator("#admin-route-progress")
|
||||
cost="账户消耗录入"; home="自录转化统计"; other="复核记录"
|
||||
tab=lambda name:page.locator(".app-tabs").get_by_role("tab",name=name,exact=True)
|
||||
def visit(name):
|
||||
desktop_entry(page,name).click()
|
||||
expect(tab(name)).to_have_attribute("aria-selected","true")
|
||||
def row(period):
|
||||
expect(stats.get_by_text("OFFLINE-"+period,exact=True)).to_be_visible()
|
||||
# A real lazy import is held. Existing content and controls must not be covered.
|
||||
held=[]
|
||||
def hold_cost(route):
|
||||
if urlsplit(route.request.url).netloc==host and route.request.resource_type=="script" and not held:
|
||||
held.append(route)
|
||||
else:route.fallback()
|
||||
page.route("**/assets/account_cost-*.js",hold_cost)
|
||||
desktop_entry(page,cost).click()
|
||||
wait_for_request(page,held)
|
||||
expect(bar).to_be_visible();expect(bar).to_have_attribute("role","progressbar")
|
||||
assert bar.evaluate("e=>getComputedStyle(e).pointerEvents")=="none"
|
||||
expect(stats).to_be_visible()
|
||||
snapshot(page,out,"route-loading")
|
||||
held[0].continue_()
|
||||
expect(page.locator("main .personal-account-cost-page")).to_be_visible()
|
||||
expect(bar).to_have_count(0);page.unroute("**/assets/account_cost-*.js",hold_cost)
|
||||
visit(other);row("today");stats.get_by_text("最近7天",exact=True).click();row("week")
|
||||
# Normalize index path by re-entering it from the sidebar.
|
||||
visit(home);row("today");stats.get_by_text("最近7天",exact=True).click();row("week")
|
||||
reads=lambda:sum(path==OVERVIEW and method=="GET" for method,path in fx.calls)
|
||||
before=reads()
|
||||
tab(other).locator(".is-icon-close").click();expect(tab(other)).to_have_count(0)
|
||||
tab(cost).click();expect(page.locator("main .personal-account-cost-page")).to_be_visible()
|
||||
refresh=page.get_by_role("button",name="刷新当前页面")
|
||||
refresh.press("Enter");expect(page.locator("main .personal-account-cost-page")).to_be_visible()
|
||||
tab(home).click();row("week")
|
||||
assert reads()==before,("unrelated tab close or refresh refetched the current filter",before,reads())
|
||||
# A closed tab using the same Vue page must start a new instance when reopened.
|
||||
visit(other);row("today");assert reads()==before+1
|
||||
tab(home).click();row("week")
|
||||
page.evaluate("""() => {window.__bars=0;new MutationObserver(rs=>{for(const r of rs)for(const n of r.addedNodes)
|
||||
if(n.id==='admin-route-progress')window.__bars++}).observe(document.body,{childList:true})}""")
|
||||
tab(other).click();row("today");tab(home).click();row("week")
|
||||
page.wait_for_timeout(300)
|
||||
assert page.evaluate("window.__bars")==0,"fast cached navigation flashed a loader"
|
||||
refresh.press("Enter");row("today")
|
||||
assert not fx.errors,fx.errors
|
||||
assert [path for method,path in fx.calls if method=="POST"]==[LOGIN]
|
||||
ctx.close()
|
||||
return {"slow_route_nonblocking":True,"fast_route_bars":0,"unrelated_refetches":0,"closed_tab_reinitialized":True,"manual_refresh_reinitialized":True}
|
||||
|
||||
|
||||
def failed_page(browser,host,out):
|
||||
ctx,fx,page=setup(browser,host,dark=True,reduce=True)
|
||||
page.goto(fx.base+"/admin/login")
|
||||
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
|
||||
page.get_by_placeholder("请输入密码").fill(PASS)
|
||||
page.get_by_role("button",name="登录",exact=True).click()
|
||||
stats=page.locator("main .self-input-stats-page")
|
||||
expect(stats.get_by_text("OFFLINE-today",exact=True)).to_be_visible()
|
||||
stats.get_by_text("最近7天",exact=True).click()
|
||||
expect(stats.get_by_text("OFFLINE-week",exact=True)).to_be_visible()
|
||||
original=page.url
|
||||
held=[]
|
||||
def deny(route):
|
||||
if urlsplit(route.request.url).netloc==host and route.request.resource_type=="script":
|
||||
held.append(route)
|
||||
else:route.fallback()
|
||||
page.route("**/assets/account_cost-*.js",deny)
|
||||
desktop_entry(page,"账户消耗录入").click()
|
||||
wait_for_request(page,held)
|
||||
bar=page.get_by_role("progressbar",name="正在打开页面")
|
||||
expect(bar).to_be_visible()
|
||||
assert bar.evaluate("e=>getComputedStyle(e).animationName")=="none"
|
||||
held[0].abort("failed")
|
||||
notice=page.get_by_role("complementary",name="页面加载提示")
|
||||
expect(notice.get_by_text("页面未能打开",exact=True)).to_be_visible()
|
||||
expect(bar).to_have_count(0)
|
||||
expect(stats.get_by_text("OFFLINE-week",exact=True)).to_be_visible()
|
||||
assert page.url==original
|
||||
snapshot(page,out,"page-error")
|
||||
notice.get_by_role("button",name="关闭提示").press("Enter")
|
||||
expect(notice).to_have_count(0)
|
||||
desktop_entry(page,"复核记录").click()
|
||||
expect(page.locator(".app-tabs").get_by_role("tab",name="复核记录")).to_have_attribute("aria-selected","true")
|
||||
assert not fx.errors,fx.errors
|
||||
ctx.close()
|
||||
return {"old_filter_retained":True,"reduced_progress_static":True,"can_continue_without_reload":True}
|
||||
|
||||
|
||||
def protected_startup(browser,host):
|
||||
found=[]
|
||||
for mode,target in [("signed_out","login"),("no_menu","403"),("initial_password","change-password"),("binding","bind-work-wechat")]:
|
||||
ctx,fx,page=setup(browser,host)
|
||||
if mode!="signed_out":
|
||||
ctx.add_init_script("if (location.origin==="+json.dumps(fx.base)+")localStorage.setItem('like_admin_token',"+json.dumps(json.dumps({"value":TOKEN,"expire":""}))+")")
|
||||
if mode=="no_menu": fx.reads[SELF]["menu"]=[]
|
||||
if mode=="initial_password": fx.reads[SELF]["user"]["is_paw"]=0
|
||||
if mode=="binding": fx.reads[SELF]["user"]["need_bind_work_wechat"]=True
|
||||
page.goto(fx.base+"/admin/stats/self_input")
|
||||
expect(page).to_have_url(re.compile("/admin/"+target+r"(?:\?|$)"),timeout=15000)
|
||||
expect(page.locator("#admin-boot")).to_have_count(0)
|
||||
expect(page.locator("main .self-input-stats-page")).to_have_count(0)
|
||||
assert not fx.errors and not [p for m,p in fx.calls if m=="POST" or p==OVERVIEW],fx.errors
|
||||
found.append(target);ctx.close()
|
||||
return found
|
||||
|
||||
|
||||
if __name__=="__main__":
|
||||
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument("--host",type=loopback,default="127.0.0.1:5179")
|
||||
ap.add_argument("--chrome",required=True);ap.add_argument("--out",type=Path)
|
||||
a=ap.parse_args()
|
||||
if a.out: a.out.mkdir(parents=True,exist_ok=True)
|
||||
with sync_playwright() as pw,pw.chromium.launch(executable_path=a.chrome,headless=True,args=CHROME_ARGS) as browser:
|
||||
report={"light":boot(browser,a.host,a.out,False),"dark_reduced":boot(browser,a.host,a.out,True,True),
|
||||
"journey":journey(browser,a.host,a.out),"asset_failure":failed_page(browser,a.host,a.out),"startup_guards":protected_startup(browser,a.host),"real_api_calls":0,"status":"PASS"}
|
||||
print(json.dumps(report,ensure_ascii=False))
|
||||
@@ -0,0 +1,147 @@
|
||||
"""Offline component test: real shared pagination SFC + installed Element Plus, no server or API."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
|
||||
ADMIN = Path(__file__).resolve().parents[1]
|
||||
BUILD = """
|
||||
import { build } from 'vite'; import vue from '@vitejs/plugin-vue';
|
||||
import AutoImport from 'unplugin-auto-import/vite';
|
||||
await build({root:process.cwd(),configFile:false,envFile:false,publicDir:false,
|
||||
plugins:[vue(),AutoImport({imports:['vue'],dts:false})],
|
||||
build:{reportCompressedSize:false,lib:{entry:'fixture.js',name:'Fixture',formats:['iife']}}});
|
||||
"""
|
||||
FIXTURE = """
|
||||
import {createApp,reactive,h} from 'vue';
|
||||
import {ElPagination,ElConfigProvider} from 'element-plus'; import zh from 'element-plus/es/locale/lang/zh-cn';
|
||||
import Pager from 'ADMIN_PATH/src/components/pagination/index.vue';
|
||||
import 'element-plus/theme-chalk/index.css';
|
||||
import 'ADMIN_PATH/src/styles/element.scss'; import 'ADMIN_PATH/src/styles/admin-v2.scss';
|
||||
const s=window.fixture=reactive({pager:{page:10,size:15,count:150}, props:{}, calls:[]});
|
||||
createApp({render:()=>h(ElConfigProvider,{locale:zh},()=>h(Pager,{modelValue:s.pager,...s.props,
|
||||
onChange:()=>s.calls.push([s.pager.page,s.pager.size])}))}).component('ElPagination',ElPagination).mount('#app');
|
||||
"""
|
||||
|
||||
|
||||
def geometry(page):
|
||||
return page.locator('.pagination').evaluate("""n => {
|
||||
const outer=document.getElementById('app').getBoundingClientRect(), nodes=[...n.querySelectorAll(
|
||||
'.el-pagination__total,.el-pagination__sizes,.btn-prev,.el-pager>li,.btn-next,.el-pagination__jump')];
|
||||
return {available:outer.width, width:n.getBoundingClientRect().width,
|
||||
hidden:nodes.filter(e=>!e.getClientRects().length).map(e=>e.className),
|
||||
clipped:nodes.filter(e=>{let r=e.getBoundingClientRect();return r.width &&
|
||||
(r.left<outer.left-.51 || r.right>outer.right+.51)}).map(e=>e.className)};
|
||||
}""")
|
||||
|
||||
|
||||
def run(page, out, baseline):
|
||||
calls = lambda: page.evaluate('fixture.calls.map(x=>[...x])')
|
||||
sizes = page.locator('.el-pagination__sizes')
|
||||
jump = page.locator('.el-pagination__jump input')
|
||||
prev = page.get_by_role('button', name='上一页')
|
||||
nxt = page.get_by_role('button', name='下一页')
|
||||
expect(nxt).to_be_disabled()
|
||||
assert not calls()
|
||||
sizes.click()
|
||||
page.get_by_role('option').filter(has_text='40').click()
|
||||
expect(page.locator('.el-pager .is-active')).to_have_text('1')
|
||||
assert calls() == [[1,40]], calls() # Changing size on the last page must not fetch twice.
|
||||
nxt.press('Enter')
|
||||
expect(page.locator('.el-pager .is-active')).to_have_text('2')
|
||||
prev.click()
|
||||
expect(prev).to_be_disabled()
|
||||
jump.fill('4')
|
||||
jump.press('Enter')
|
||||
expect(nxt).to_be_disabled()
|
||||
assert calls() == [[1,40],[2,40],[1,40],[4,40]],calls()
|
||||
|
||||
page.evaluate('fixture.pager.count=925000;fixture.pager.page=142')
|
||||
report={}
|
||||
for name,viewport,width in [('mobile',390,320),('narrow-panel',1120,210),('wide',1300,1000)]:
|
||||
page.set_viewport_size({'width':viewport,'height':720})
|
||||
page.locator('#app').evaluate('(n,w)=>n.style.width=w+"px"',width)
|
||||
page.evaluate('() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))')
|
||||
report[name]=geometry(page)
|
||||
if out:
|
||||
page.locator('#app').screenshot(path=str(out/(name+'.png')))
|
||||
if not baseline:
|
||||
assert not report[name]['hidden'] and not report[name]['clipped'],report[name]
|
||||
expect(prev).to_be_visible()
|
||||
expect(nxt).to_be_visible()
|
||||
expect(jump).to_be_visible()
|
||||
|
||||
if not baseline:
|
||||
page.set_viewport_size({'width':390,'height':720})
|
||||
page.locator('#app').evaluate("n=>n.style.width='210px'")
|
||||
nxt.press('Enter')
|
||||
expect(page.locator('.el-pager .is-active')).to_have_text('143')
|
||||
jump.fill('1')
|
||||
jump.press('Enter')
|
||||
expect(prev).to_be_disabled()
|
||||
assert calls()[-2:]==[[143,40],[1,40]]
|
||||
# Scoped styling does not override the classic mobile rule.
|
||||
page.evaluate("document.documentElement.dataset.adminUi='legacy'")
|
||||
expect(sizes).to_be_hidden()
|
||||
expect(jump).to_be_hidden()
|
||||
page.evaluate("document.documentElement.dataset.adminUi='v2'")
|
||||
|
||||
# Omitted controls must stay omitted; caller's custom option list/order is authoritative.
|
||||
page.evaluate("fixture.props={layout:'next, prev, sizes',pageSizes:[40,60]}")
|
||||
expect(page.locator('.el-pager')).to_have_count(0)
|
||||
expect(jump).to_have_count(0)
|
||||
tags=page.locator('.el-pagination').evaluate("n=>[...n.children].map(e=>e.className)")
|
||||
assert 'btn-next' in tags[0] and 'btn-prev' in tags[1] and '__sizes' in tags[2],tags
|
||||
custom=geometry(page)
|
||||
assert not custom['clipped'] and not custom['hidden'],custom
|
||||
before=calls()
|
||||
sizes.click()
|
||||
options=page.get_by_role('option')
|
||||
assert options.count()==2
|
||||
assert [re.match(r'\d+', t.strip()).group() for t in options.all_text_contents()]==['40','60']
|
||||
options.nth(1).click()
|
||||
expect(prev).to_be_disabled()
|
||||
assert calls()==before+[[1,60]],calls()
|
||||
return dict(layout=report,calls=calls())
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument('--baseline',action='store_true',help='record pre-change geometry without enforcing a pass')
|
||||
ap.add_argument('--out',type=Path)
|
||||
args=ap.parse_args()
|
||||
if args.out: args.out.mkdir(exist_ok=True,parents=True)
|
||||
with tempfile.TemporaryDirectory(prefix='zyt-pagination-') as tmp:
|
||||
root=Path(tmp)
|
||||
(root/'node_modules').symlink_to(ADMIN/'node_modules',target_is_directory=True)
|
||||
(root/'build.mjs').write_text(BUILD)
|
||||
(root/'fixture.js').write_text(FIXTURE.replace('ADMIN_PATH',ADMIN.as_posix()))
|
||||
(root/'package.json').write_text('{"name":"pager-check","type":"module"}')
|
||||
subprocess.run(['node','build.mjs'],cwd=root,check=True,stdout=subprocess.DEVNULL)
|
||||
dist=root/'dist'
|
||||
with sync_playwright() as pw:
|
||||
exe=os.environ.get('CHROME_BIN')
|
||||
mac='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
|
||||
browser=pw.chromium.launch(executable_path=exe or (mac if Path(mac).exists() else None),
|
||||
args=['--disable-background-networking'])
|
||||
page=browser.new_page()
|
||||
errors,requests=[],[]
|
||||
page.on('pageerror',lambda e: errors.append(str(e)))
|
||||
page.on('request',lambda req: requests.append(req.url))
|
||||
page.route('**/*',lambda r:r.abort())
|
||||
page.set_content('<html data-admin-ui="v2"><body><main id="app" style="width:1000px;display:flex;justify-content:flex-end"></main></body></html>')
|
||||
page.add_style_tag(content=next(dist.glob('*.css')).read_text())
|
||||
page.evaluate("window.process={env:{NODE_ENV:'production'}}")
|
||||
page.add_script_tag(content=next(dist.glob('*.js')).read_text())
|
||||
result=run(page,args.out,args.baseline)
|
||||
assert not errors and not requests,(errors,requests)
|
||||
print(json.dumps(result,ensure_ascii=False))
|
||||
browser.close()
|
||||
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -1,2 +1,32 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN" data-default-admin-ui="v2"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>甄养堂管理后台</title><link rel="icon" href="data:,"></head><body><div id="app"></div><script type="module" src="/src/main.ts"></script></body></html>
|
||||
<html lang="zh-CN" data-default-admin-ui="v2">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<title>甄养堂管理后台</title>
|
||||
<link rel="icon" href="data:," />
|
||||
<link rel="stylesheet" href="/admin-loading.css" />
|
||||
<script defer src="/admin-boot.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="admin-boot" data-state="loading">
|
||||
<div>
|
||||
<svg class="boot-mark" width="40" height="40" viewBox="0 0 40 40" fill="currentColor" aria-hidden="true">
|
||||
<circle cx="20" cy="8" r="4"/><circle cx="32" cy="20" r="4" opacity=".76"/>
|
||||
<circle cx="20" cy="32" r="4" opacity=".52"/><circle cx="8" cy="20" r="4" opacity=".32"/>
|
||||
</svg>
|
||||
<strong>甄养堂管理后台</strong>
|
||||
<p role="status" aria-atomic="true">
|
||||
<span data-message="loading">正在打开工作台…</span>
|
||||
<span data-message="slow">加载时间较长,可继续等待或重新加载。</span>
|
||||
<span data-message="error">工作台未能打开,请检查网络后重试。</span>
|
||||
</p>
|
||||
<a id="admin-boot-retry" href="">重新加载</a>
|
||||
<noscript>请启用 JavaScript 后重新加载。</noscript>
|
||||
</div>
|
||||
</div>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user