feat(admin): 增加启动与导航反馈并保护工作标签状态
This commit is contained in:
+19
-47
@@ -5,51 +5,13 @@
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>后台管理系统</title>
|
||||
<link rel="stylesheet" href="/admin-loading.css" />
|
||||
<script defer src="/admin-boot.js"></script>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.preload {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100vh;
|
||||
width: 100vw;
|
||||
}
|
||||
|
||||
.circular {
|
||||
height: 42px;
|
||||
width: 42px;
|
||||
animation: loading-rotate 2s linear infinite;
|
||||
}
|
||||
|
||||
.circular .path {
|
||||
animation: loading-dash 1.5s ease-in-out infinite;
|
||||
stroke-dasharray: 90, 150;
|
||||
stroke-dashoffset: 0;
|
||||
stroke-width: 2;
|
||||
stroke: #4073fa;
|
||||
stroke-linecap: round;
|
||||
}
|
||||
|
||||
@keyframes loading-rotate {
|
||||
100% {
|
||||
transform: rotate(1turn);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes loading-dash {
|
||||
0% {
|
||||
stroke-dasharray: 90, 150;
|
||||
stroke-dashoffset: -40px;
|
||||
}
|
||||
|
||||
100% {
|
||||
stroke-dasharray: 90, 150;
|
||||
stroke-dashoffset: -120px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<script>
|
||||
// 动态加载 Chat UIKit 样式
|
||||
@@ -165,13 +127,23 @@
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<div class="preload">
|
||||
<svg viewBox="25 25 50 50" class="circular">
|
||||
<circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
<script>
|
||||
// Dify 聊天窗口全屏切换:#dify-chatbot-bubble-window 是 iframe 本身,
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Deferred same-origin script: no remote dependency, inline handler or application API.
|
||||
;(function () {
|
||||
var boot = document.getElementById('admin-boot')
|
||||
if (!boot) return
|
||||
try {
|
||||
// Only appearance keys are read. Vue/Pinia remains the owner after mount.
|
||||
function readPreference(name) {
|
||||
var record = JSON.parse(localStorage.getItem('like_admin_' + name) || 'null')
|
||||
return record && (!record.expire || record.expire >= Date.now() / 1000) ? record.value : null
|
||||
}
|
||||
var appearance = readPreference('admin_ui') || document.documentElement.dataset.defaultAdminUi
|
||||
var profile = appearance === 'v2' && readPreference('admin_ui_v2_setting')
|
||||
var mode = appearance === 'v2' ? (profile && profile.colorMode) : localStorage.getItem('vueuse-color-scheme')
|
||||
if (mode === 'dark' || mode === 'light') boot.dataset.mode = mode
|
||||
} catch (_) { /* Browser privacy settings: CSS follows the system. */ }
|
||||
|
||||
// A slow network is not a failure. Keep waiting unless the user chooses to reload.
|
||||
var slow = setTimeout(function () {
|
||||
if (boot.dataset.state === 'loading') boot.dataset.state = 'slow'
|
||||
}, 12000)
|
||||
function entryFailed(event) {
|
||||
// Optional SDK/style/image errors must never turn a healthy app into a failure.
|
||||
var script = event.target
|
||||
if (script && script.tagName === 'SCRIPT' && script.type === 'module') boot.dataset.state = 'error'
|
||||
}
|
||||
window.addEventListener('error', entryFailed, true)
|
||||
window.addEventListener('admin:mounted', function () {
|
||||
clearTimeout(slow)
|
||||
window.removeEventListener('error', entryFailed, true)
|
||||
}, { once: true })
|
||||
})()
|
||||
@@ -0,0 +1,50 @@
|
||||
/* Native entry, including the interval before Vue's first chunk is evaluated. */
|
||||
#admin-boot {
|
||||
--boot-bg: #fafbfc;
|
||||
--boot-ink: #323251;
|
||||
--boot-muted: #596681;
|
||||
--boot-accent: #5d87ff;
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: var(--boot-bg);
|
||||
color: var(--boot-ink);
|
||||
text-align: center;
|
||||
font: 14px/1.6 system-ui, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
pointer-events: none;
|
||||
}
|
||||
#admin-boot[data-mode="dark"] {
|
||||
--boot-bg: #121318; --boot-ink: #e8ecf3; --boot-muted: #a8b2c7; --boot-accent: #829eff;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
#admin-boot:not([data-mode="light"]) {
|
||||
--boot-bg: #121318; --boot-ink: #e8ecf3; --boot-muted: #a8b2c7; --boot-accent: #829eff;
|
||||
}
|
||||
}
|
||||
#admin-boot .boot-mark { display: block; margin: 0 auto 18px; color: var(--boot-accent); animation: boot-turn 1.6s linear infinite; }
|
||||
#admin-boot strong { font-size: 18px; font-weight: 600; letter-spacing: .04em; }
|
||||
#admin-boot p { margin: 5px 12px 0; color: var(--boot-muted); }
|
||||
#admin-boot [data-message], #admin-boot-retry { display: none; }
|
||||
#admin-boot[data-state="loading"] [data-message="loading"],
|
||||
#admin-boot[data-state="slow"] [data-message="slow"],
|
||||
#admin-boot[data-state="error"] [data-message="error"] { display: inline; }
|
||||
#admin-boot[data-state="error"] .boot-mark { animation: none; }
|
||||
#admin-boot:not([data-state="loading"]) #admin-boot-retry {
|
||||
display: inline-block; margin-top: 10px; padding: 4px 12px; color: inherit;
|
||||
text-decoration: underline; text-underline-offset: 3px; pointer-events: auto;
|
||||
}
|
||||
@keyframes boot-turn { to { transform: rotate(1turn); } }
|
||||
|
||||
/* Indeterminate like the Art header. No fake percentage, overlay or scroll lock. */
|
||||
#admin-route-progress {
|
||||
position: fixed; top: 0; left: 0; width: 100%; height: 3px; z-index: 2400;
|
||||
background: var(--el-color-primary, #5d87ff);
|
||||
pointer-events: none; transform-origin: left; transform: scaleX(.22);
|
||||
animation: admin-route-advance 8s cubic-bezier(.12,.76,.22,1) forwards;
|
||||
}
|
||||
@keyframes admin-route-advance { to { transform: scaleX(.92); } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
#admin-boot .boot-mark, #admin-route-progress { animation: none; }
|
||||
#admin-route-progress { transform: scaleX(.4); }
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import useSettingStore, { useAdminDark } from './stores/modules/setting'
|
||||
import useUserStore from './stores/modules/user'
|
||||
import ChatNotifyToast from './components/chat-notify-toast/index.vue'
|
||||
import RevisitDueToast from './components/revisit-due-toast/index.vue'
|
||||
import RouteLoadNotice from './components/route-load-notice/index.vue'
|
||||
|
||||
const appStore = useAppStore()
|
||||
const settings = useSettingStore()
|
||||
@@ -58,6 +59,7 @@ watch(
|
||||
<template>
|
||||
<el-config-provider :locale="elConfig.locale" :z-index="elConfig.zIndex">
|
||||
<router-view />
|
||||
<route-load-notice />
|
||||
<ChatNotifyToast v-if="showChatNotifyToast" />
|
||||
<!-- 复诊到期弹窗(右下角):与会话通知并列挂载,复用同一条件避免未绑企微时无意义轮询 -->
|
||||
<RevisitDueToast v-if="showChatNotifyToast" />
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
<el-date-picker
|
||||
v-model="dateRangeModel"
|
||||
type="daterange"
|
||||
popper-class="list-time-filter-calendar"
|
||||
value-format="YYYY-MM-DD"
|
||||
range-separator="至"
|
||||
start-placeholder="开始日期"
|
||||
@@ -38,6 +39,7 @@
|
||||
v-if="timeType === 'custom'"
|
||||
v-model="dateRangeModel"
|
||||
type="daterange"
|
||||
popper-class="list-time-filter-calendar"
|
||||
value-format="YYYY-MM-DD"
|
||||
range-separator="至"
|
||||
start-placeholder="开始日期"
|
||||
@@ -94,3 +96,26 @@ const emit = defineEmits<{
|
||||
margin-bottom: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
<!-- The picker is teleported outside its form. Limit this override to the shared
|
||||
list filter, the new admin profile and narrow screens; keep both months reachable. -->
|
||||
<style lang="scss">
|
||||
@media (max-width: 640px) {
|
||||
:root[data-admin-ui='v2'] .list-time-filter-calendar .el-date-range-picker {
|
||||
width: min(360px, calc(100vw - 24px));
|
||||
|
||||
.el-picker-panel__body-wrapper {
|
||||
max-height: min(62vh, 480px);
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
.el-picker-panel__body { min-width: 0; }
|
||||
.el-date-range-picker__content {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 8px 12px;
|
||||
&.is-left { border-right: 0; border-bottom: 1px solid var(--el-border-color-lighter); }
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
<template>
|
||||
<div class="pagination">
|
||||
<div class="pagination zyt-pagination" :class="{ 'zyt-pagination--standard': effectiveLayout === standardLayout }">
|
||||
<el-pagination
|
||||
v-bind="props"
|
||||
:pager-count="5"
|
||||
v-model:currentPage="pager.page"
|
||||
v-model:pageSize="pager.size"
|
||||
:page-sizes="pageSizes"
|
||||
:layout="layout"
|
||||
:layout="effectiveLayout"
|
||||
:total="pager.count"
|
||||
:hide-on-single-page="false"
|
||||
@size-change="sizeChange"
|
||||
@@ -23,9 +23,10 @@ interface Props {
|
||||
}
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
modelValue: () => ({}),
|
||||
pageSizes: () => [15, 20, 30, 40],
|
||||
layout: 'total, sizes, prev, pager, next, jumper'
|
||||
pageSizes: () => [15, 20, 30, 40]
|
||||
})
|
||||
const standardLayout = 'total, sizes, prev, pager, next, jumper'
|
||||
const effectiveLayout = computed(() => props.layout ?? standardLayout)
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: 'change'): void
|
||||
@@ -48,3 +49,37 @@ const pageChange = () => {
|
||||
emit('change')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss">
|
||||
// A sidebar, dialog or split view can leave less room than the viewport.
|
||||
:root[data-admin-ui='v2'] .zyt-pagination {
|
||||
container: zyt-pages / inline-size;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
> .el-pagination { justify-content: flex-end; flex-wrap: wrap; }
|
||||
}
|
||||
@container zyt-pages (max-width: 740px) {
|
||||
.zyt-pagination > .el-pagination {
|
||||
--el-pagination-item-gap: 0px;
|
||||
gap: 6px;
|
||||
.el-pagination__rightwrapper, .el-pager { max-width: 100%; flex-wrap: wrap; }
|
||||
.el-pager { display: flex; justify-content: center; }
|
||||
// The classic stylesheet hides these slots on mobile. Keep only the
|
||||
// slots actually requested by this instance's layout.
|
||||
.el-pagination__sizes, .el-pagination__jump { display: inline-flex !important; }
|
||||
}
|
||||
// Only our default order gets explicit rows. Custom layouts keep their DOM order.
|
||||
.zyt-pagination--standard > .el-pagination {
|
||||
display: grid;
|
||||
grid-template-columns: 32px repeat(2, minmax(0, 1fr)) 32px;
|
||||
column-gap: 0;
|
||||
max-width: 360px;
|
||||
margin-inline-start: auto;
|
||||
.el-pagination__total, .el-pagination__sizes, .el-pager { grid-column: span 2; }
|
||||
.el-pagination__total { white-space: normal; overflow-wrap: anywhere; }
|
||||
.el-pagination__sizes { justify-self: end; max-width: 100%; }
|
||||
.el-pagination__sizes .el-select { max-width: 100%; }
|
||||
.el-pagination__jump { grid-column: 1 / -1; justify-self: end; }
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<template>
|
||||
<aside v-if="failedRoute" class="route-load-notice" aria-label="页面加载提示">
|
||||
<div role="status">
|
||||
<strong>页面未能打开</strong>
|
||||
<p>当前页面已保留。请检查网络后重试;如需刷新,请先保存正在填写的内容。</p>
|
||||
</div>
|
||||
<div class="notice-actions">
|
||||
<el-button size="small" @click="reportRouteLoad()">关闭提示</el-button>
|
||||
<el-button size="small" type="primary" @click="retry">重试打开</el-button>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { useRouter } from 'vue-router'
|
||||
import { failedRoute, reportRouteLoad } from '@/utils/route-load-notice'
|
||||
|
||||
const router = useRouter()
|
||||
function retry() {
|
||||
const target = failedRoute.value
|
||||
if (target) void router.push(target).catch(() => { /* router.onError owns the feedback */ })
|
||||
}
|
||||
</script>
|
||||
<style scoped>
|
||||
.route-load-notice {
|
||||
position: fixed; z-index: 2050; inset-inline-end: 16px; bottom: max(16px, env(safe-area-inset-bottom));
|
||||
width: min(360px, calc(100vw - 32px)); padding: 16px; border: 1px solid var(--el-border-color);
|
||||
border-radius: var(--zyt-radius, 10px); color: var(--el-text-color-primary);
|
||||
background: var(--el-bg-color-overlay); box-shadow: var(--el-box-shadow-light);
|
||||
}
|
||||
.route-load-notice p { margin: 4px 0 12px; color: var(--el-text-color-regular); font-size: 13px; }
|
||||
.notice-actions { display: flex; justify-content: flex-end; gap: 8px; }
|
||||
.notice-actions .el-button + .el-button { margin: 0; }
|
||||
</style>
|
||||
@@ -26,17 +26,17 @@ useWatchRoute((route) => {
|
||||
.app-breadcrumb {
|
||||
:deep(.el-breadcrumb__item) {
|
||||
.el-breadcrumb__inner {
|
||||
color: #303133;
|
||||
color: var(--zyt-text, #303133);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
&:last-child .el-breadcrumb__inner {
|
||||
color: #303133;
|
||||
color: var(--zyt-ink, #303133);
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.el-breadcrumb__separator) {
|
||||
color: #606266;
|
||||
color: var(--zyt-muted, #606266);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -6,9 +6,7 @@
|
||||
<fold />
|
||||
</div>
|
||||
<div class="navbar-item">
|
||||
<el-tooltip class="box-item" effect="dark" content="刷新" placement="bottom">
|
||||
<refresh />
|
||||
</el-tooltip>
|
||||
<refresh />
|
||||
</div>
|
||||
<div class="flex items-center px-2" v-if="!isMobile && settingStore.showCrumb">
|
||||
<breadcrumb />
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
<template>
|
||||
<div class="refresh cursor-pointer h-full flex items-center px-2" @click="refreshView">
|
||||
<button type="button" class="refresh cursor-pointer h-full flex items-center px-2"
|
||||
aria-label="刷新当前页面" title="刷新当前页面" @click="refreshView">
|
||||
<icon name="el-icon-RefreshRight" :size="18" />
|
||||
</div>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import useAppStore from '@/stores/modules/app'
|
||||
import useTabsStore from '@/stores/modules/multipleTabs'
|
||||
|
||||
const appStore = useAppStore()
|
||||
// 刷新页面
|
||||
const tabs = useTabsStore()
|
||||
const route = useRoute()
|
||||
const refreshView = () => {
|
||||
appStore.refreshView()
|
||||
if (!tabs.refreshCachedTab(route.fullPath)) appStore.refreshView()
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -2,9 +2,12 @@
|
||||
<main class="main-wrap h-full bg-page">
|
||||
<el-scrollbar>
|
||||
<div class="admin-content px-2 py-4">
|
||||
<router-view v-if="isRouteShow" v-slot="{ Component, route }">
|
||||
<router-view v-slot="{ Component, route: viewRoute }">
|
||||
<keep-alive :include="includeList" :max="20">
|
||||
<component :is="Component" :key="route.fullPath" />
|
||||
<component v-if="Component && isRouteShow && currentView.shell" :is="currentView.shell" :key="currentView.id">
|
||||
<component :is="Component" :key="viewRoute.fullPath" />
|
||||
</component>
|
||||
<component v-else-if="Component && isRouteShow" :is="Component" :key="viewRoute.fullPath" />
|
||||
</keep-alive>
|
||||
</router-view>
|
||||
</div>
|
||||
@@ -13,15 +16,40 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, defineComponent, watch, type Component } from 'vue'
|
||||
|
||||
import useAppStore from '@/stores/modules/app'
|
||||
import useTabsStore from '@/stores/modules/multipleTabs'
|
||||
import useSettingStore from '@/stores/modules/setting'
|
||||
|
||||
const appStore = useAppStore()
|
||||
const tabsStore = useTabsStore()
|
||||
const settingStore = useSettingStore()
|
||||
const tabs = useTabsStore()
|
||||
const settings = useSettingStore()
|
||||
const route = useRoute()
|
||||
const isRouteShow = computed(() => appStore.isRouteShow)
|
||||
const includeList = computed(() => (settingStore.openMultipleTabs ? tabsStore.getCacheTabList : []))
|
||||
</script>
|
||||
|
||||
<style></style>
|
||||
// KeepAlive includes/excludes component names, not URLs. Give each opted-in
|
||||
// work tab its own transparent, named cache boundary so removing one page
|
||||
// cannot also evict another page backed by the same Vue component.
|
||||
const cacheName = (id: number) => 'AdminCachedView' + id
|
||||
const shells = new Map<number, Component>()
|
||||
const openIds = computed(() => tabs.tabList.flatMap(tab => tab.cacheId ? [tab.cacheId] : []))
|
||||
const includeList = computed(() => settings.openMultipleTabs ? openIds.value.map(cacheName) : [])
|
||||
watch(openIds, ids => {
|
||||
for (const id of shells.keys()) if (!ids.includes(id)) shells.delete(id)
|
||||
})
|
||||
const currentView = computed<{ path: string; id?: number; shell?: Component }>((previous) => {
|
||||
const path = route.fullPath
|
||||
const id = tabs.tabList.find(item => item.fullPath === path)?.cacheId
|
||||
// While the router is leaving a just-closed tab, don't mount a throwaway
|
||||
// copy of its business page. KeepAlive will prune it after the route commit.
|
||||
if (!id) return previous?.path === path ? previous : { path }
|
||||
if (!shells.has(id)) {
|
||||
shells.set(id, defineComponent({
|
||||
name: cacheName(id),
|
||||
setup: (_, { slots }) => () => slots.default?.()[0] ?? null
|
||||
}))
|
||||
}
|
||||
return { path, id, shell: shells.get(id) }
|
||||
})
|
||||
</script>
|
||||
|
||||
+15
-3
@@ -6,8 +6,20 @@ import { createApp } from 'vue'
|
||||
|
||||
import App from './App.vue'
|
||||
import install from './install'
|
||||
import router from './router'
|
||||
|
||||
const app = createApp(App)
|
||||
async function start() {
|
||||
const app = createApp(App)
|
||||
app.use(install)
|
||||
// The static boot panel remains in place through auth redirects and lazy route imports.
|
||||
await router.isReady()
|
||||
app.mount('#app')
|
||||
document.getElementById('admin-boot')?.remove()
|
||||
window.dispatchEvent(new Event('admin:mounted'))
|
||||
}
|
||||
|
||||
app.use(install)
|
||||
app.mount('#app')
|
||||
start().catch(error => {
|
||||
const panel = document.getElementById('admin-boot')
|
||||
if (panel) panel.dataset.state = 'error'
|
||||
console.error('管理后台启动失败:', error)
|
||||
})
|
||||
|
||||
@@ -11,6 +11,8 @@ import { INDEX_ROUTE, INDEX_ROUTE_NAME } from './router/routes'
|
||||
import useTabsStore from './stores/modules/multipleTabs'
|
||||
import useUserStore from './stores/modules/user'
|
||||
import { clearAuthInfo } from './utils/auth'
|
||||
import { installNavigationFeedback } from './utils/nav-loading'
|
||||
import { reportRouteLoad } from './utils/route-load-notice'
|
||||
import { isExternal } from './utils/validate'
|
||||
|
||||
function firstQueryString(q: LocationQueryValue | LocationQueryValue[] | undefined): string {
|
||||
@@ -82,6 +84,7 @@ const changePasswordPath = '/change-password'
|
||||
const bindWorkWechatPath = '/bind-work-wechat'
|
||||
// 免登录白名单
|
||||
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403]
|
||||
installNavigationFeedback(router, document, reportRouteLoad)
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
document.title = to.meta.title ?? config.title
|
||||
const userStore = useUserStore()
|
||||
|
||||
@@ -13,6 +13,7 @@ import { isExternal } from '@/utils/validate'
|
||||
interface TabItem {
|
||||
name: RouteRecordName
|
||||
fullPath: string
|
||||
cacheId?: number
|
||||
path: string
|
||||
title?: string
|
||||
query?: LocationQuery
|
||||
@@ -20,9 +21,8 @@ interface TabItem {
|
||||
}
|
||||
|
||||
interface TabsSate {
|
||||
cacheTabList: Set<string>
|
||||
nextCacheId: number
|
||||
tabList: TabItem[]
|
||||
tasMap: Record<string, TabItem>
|
||||
indexRouteName: RouteRecordName
|
||||
}
|
||||
|
||||
@@ -50,52 +50,33 @@ const isCannotAddRoute = (route: RouteLocationNormalized, router: Router) => {
|
||||
return false
|
||||
}
|
||||
|
||||
const findTabsIndex = (fullPath: string, tabList: TabItem[]) => {
|
||||
return tabList.findIndex((item) => item.fullPath === fullPath)
|
||||
}
|
||||
|
||||
const getComponentName = (route: RouteLocationNormalized) => {
|
||||
return route.matched.at(-1)?.components?.default?.name
|
||||
}
|
||||
|
||||
// fullPath already includes resolved dynamic params, encoded query, and fragment.
|
||||
export const getRouteParams = (tabItem: TabItem) => tabItem.fullPath
|
||||
|
||||
const useTabsStore = defineStore({
|
||||
id: 'tabs',
|
||||
state: (): TabsSate => ({
|
||||
cacheTabList: new Set(),
|
||||
nextCacheId: 0,
|
||||
tabList: [],
|
||||
tasMap: {},
|
||||
indexRouteName: ''
|
||||
}),
|
||||
getters: {
|
||||
getTabList(): TabItem[] {
|
||||
return this.tabList
|
||||
},
|
||||
getCacheTabList(): string[] {
|
||||
return Array.from(this.cacheTabList)
|
||||
}
|
||||
},
|
||||
actions: {
|
||||
setRouteName(name: RouteRecordName) {
|
||||
this.indexRouteName = name
|
||||
},
|
||||
addCache(componentName?: string) {
|
||||
if (componentName) this.cacheTabList.add(componentName)
|
||||
},
|
||||
removeCache(componentName?: string) {
|
||||
if (componentName && this.cacheTabList.has(componentName)) {
|
||||
this.cacheTabList.delete(componentName)
|
||||
}
|
||||
},
|
||||
clearCache() {
|
||||
this.cacheTabList.clear()
|
||||
refreshCachedTab(fullPath: string) {
|
||||
const tab = this.tabList.find(item => item.fullPath === fullPath)
|
||||
if (!tab?.cacheId) return false
|
||||
tab.cacheId = ++this.nextCacheId
|
||||
return true
|
||||
},
|
||||
resetState() {
|
||||
this.cacheTabList = new Set()
|
||||
this.tabList = []
|
||||
this.tasMap = {}
|
||||
this.indexRouteName = ''
|
||||
},
|
||||
addTab(router: Router) {
|
||||
@@ -103,23 +84,19 @@ const useTabsStore = defineStore({
|
||||
const { name, query, meta, params, fullPath, path } = route
|
||||
if (isCannotAddRoute(route, router)) return
|
||||
const hasTabIndex = getHasTabIndex(fullPath!, this.tabList)
|
||||
const componentName = getComponentName(route)
|
||||
const tabItem = {
|
||||
name: name!,
|
||||
path,
|
||||
fullPath,
|
||||
cacheId: meta.keepAlive ? (this.tabList[hasTabIndex]?.cacheId ?? ++this.nextCacheId) : undefined,
|
||||
title: meta?.title,
|
||||
query,
|
||||
params
|
||||
}
|
||||
if (meta?.keepAlive) {
|
||||
this.addCache(componentName)
|
||||
}
|
||||
|
||||
// 已存在相同 fullPath:刷新该项(标题/query 等可能变化)
|
||||
if (hasTabIndex !== -1) {
|
||||
this.tabList[hasTabIndex] = tabItem
|
||||
this.tasMap[fullPath!] = tabItem
|
||||
return
|
||||
}
|
||||
|
||||
@@ -133,54 +110,26 @@ const useTabsStore = defineStore({
|
||||
const keepIdx = dupIndices[0]
|
||||
for (let k = dupIndices.length - 1; k >= 1; k--) {
|
||||
const idx = dupIndices[k]
|
||||
delete this.tasMap[this.tabList[idx].fullPath]
|
||||
this.tabList.splice(idx, 1)
|
||||
}
|
||||
const prev = this.tabList[keepIdx]
|
||||
if (prev.fullPath !== fullPath) {
|
||||
delete this.tasMap[prev.fullPath]
|
||||
}
|
||||
this.tabList[keepIdx] = tabItem
|
||||
this.tasMap[fullPath!] = tabItem
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
this.tasMap[fullPath!] = tabItem
|
||||
this.tabList.push(tabItem)
|
||||
},
|
||||
removeTab(fullPath: string, router: Router) {
|
||||
const { currentRoute, push } = router
|
||||
const index = findTabsIndex(fullPath, this.tabList)
|
||||
// 移除tab
|
||||
if (this.tabList.length > 1) {
|
||||
index !== -1 && this.tabList.splice(index, 1)
|
||||
const index = getHasTabIndex(fullPath, this.tabList)
|
||||
if (index < 0 || this.tabList.length < 2) return
|
||||
this.tabList.splice(index, 1)
|
||||
if (fullPath === currentRoute.value.fullPath) {
|
||||
push(getRouteParams(this.tabList[Math.max(0, index - 1)]))
|
||||
}
|
||||
const componentName = getComponentName(currentRoute.value)
|
||||
this.removeCache(componentName)
|
||||
if (fullPath !== currentRoute.value.fullPath) {
|
||||
return
|
||||
}
|
||||
// 删除选中的tab
|
||||
let toTab: TabItem | null = null
|
||||
|
||||
if (index === 0) {
|
||||
toTab = this.tabList[index]
|
||||
} else {
|
||||
toTab = this.tabList[index - 1]
|
||||
}
|
||||
|
||||
const toRoute = getRouteParams(toTab)
|
||||
push(toRoute)
|
||||
},
|
||||
removeOtherTab(route: RouteLocationNormalized) {
|
||||
this.tabList = this.tabList.filter((item) => item.fullPath == route.fullPath)
|
||||
const componentName = getComponentName(route)
|
||||
this.cacheTabList.forEach((name) => {
|
||||
if (componentName !== name) {
|
||||
this.removeCache(name)
|
||||
}
|
||||
})
|
||||
this.tabList = this.tabList.filter(item => item.fullPath === route.fullPath)
|
||||
},
|
||||
removeAllTab(router: Router) {
|
||||
const { push, currentRoute } = router
|
||||
@@ -190,7 +139,6 @@ const useTabsStore = defineStore({
|
||||
return
|
||||
}
|
||||
this.tabList = []
|
||||
this.clearCache()
|
||||
push(PageEnum.INDEX)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,9 @@
|
||||
--zyt-shadow: none; // Art's default boxBorderMode.
|
||||
--zyt-primary: var(--el-color-primary);
|
||||
--zyt-accent: var(--el-color-primary);
|
||||
// Keep status indicators legible even with a near-white/black custom accent.
|
||||
--zyt-feedback-ink: var(--zyt-text);
|
||||
--zyt-loading-surface: var(--zyt-surface);
|
||||
--zyt-accent-soft: var(--el-color-primary-light-9);
|
||||
--zyt-accent-border: var(--el-color-primary-light-8);
|
||||
--zyt-nav-bg: #fff;
|
||||
@@ -72,6 +75,11 @@
|
||||
--table-header-bg-color: var(--zyt-surface-subtle);
|
||||
@include art-status-colors(#fff, #000);
|
||||
|
||||
@supports (color: color-mix(in srgb, black, white)) {
|
||||
--zyt-feedback-ink: color-mix(in srgb, var(--zyt-primary) 30%, var(--zyt-ink));
|
||||
--zyt-loading-surface: color-mix(in srgb, var(--zyt-surface) 90%, transparent);
|
||||
}
|
||||
|
||||
.side--dark, &.dark {
|
||||
--zyt-nav-bg: #191a23;
|
||||
--zyt-nav-title: #d9dadb;
|
||||
@@ -242,7 +250,40 @@
|
||||
--el-button-hover-text-color: var(--zyt-on-primary, #fff);
|
||||
}
|
||||
.el-pagination.is-background :is(.btn-next, .btn-prev, .el-pager li) { border-radius: 6px; }
|
||||
:focus-visible:is(button, a, [role='button']) { outline: 2px solid var(--zyt-primary); outline-offset: 2px; }
|
||||
// Ring the visible control, not the small or hidden input inside it.
|
||||
// An outline leaves Element's error border and checked state intact.
|
||||
:is(button, a[href], summary, [role='button'], [role='tab'], [role='menuitem'], [role='option']):focus-visible,
|
||||
.el-textarea__inner:focus-visible,
|
||||
:is(.el-input__wrapper, .el-select__wrapper, .el-checkbox__input, .el-radio__input, .el-switch):has(input:focus-visible) {
|
||||
outline: 2px solid var(--zyt-feedback-ink);
|
||||
outline-offset: var(--zyt-focus-offset, 2px);
|
||||
}
|
||||
.side, .app-tabs { --zyt-focus-offset: -2px; }
|
||||
.side--dark { --zyt-feedback-ink: var(--zyt-nav-title); }
|
||||
|
||||
// Match the surface beneath local table/panel loads, without changing a
|
||||
// full-screen lock, the original request lifecycle, or an explicit mask color.
|
||||
.el-loading-mask:not(.is-fullscreen) {
|
||||
--el-mask-color: var(--zyt-loading-surface);
|
||||
--el-loading-spinner-size: 28px;
|
||||
border-radius: inherit;
|
||||
.el-loading-spinner {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: 5px;
|
||||
margin-top: 0;
|
||||
transform: translateY(-50%);
|
||||
.path { stroke: var(--zyt-feedback-ink); stroke-width: 3.5; }
|
||||
.el-loading-text { margin: 0; color: var(--zyt-text); }
|
||||
}
|
||||
}
|
||||
// Keep the native busy icon and button label visible without the extra veil.
|
||||
.el-button.is-loading { --el-mask-color-extra-light: transparent; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.el-loading-mask, .el-button, .el-select__wrapper { transition-duration: 0s; }
|
||||
.el-loading-spinner .circular, .el-loading-spinner .path,
|
||||
.el-button.is-loading .el-icon.is-loading { animation: none; }
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.admin-content { padding-inline: 15px; }
|
||||
.navbar, .app-header .app-tabs { padding-inline: 15px; }
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { isNavigationFailure, NavigationFailureType, type RouteLocationNormalized, type Router } from 'vue-router'
|
||||
|
||||
/**
|
||||
* Observe the navigation, never decide it. Keep one lightweight bar across redirects
|
||||
* and overlapping guards; a late failure for an older route doesn't own the bar.
|
||||
*/
|
||||
export function installNavigationFeedback(router: Router, doc: Document = document,
|
||||
notify?: (failedPath?: string) => void) {
|
||||
let owner: RouteLocationNormalized | undefined
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let bar: HTMLElement | undefined
|
||||
|
||||
function stop() {
|
||||
clearTimeout(timer)
|
||||
timer = undefined
|
||||
owner = undefined
|
||||
bar?.remove()
|
||||
bar = undefined
|
||||
}
|
||||
|
||||
function owns(to: RouteLocationNormalized) {
|
||||
return owner === to || (to.redirectedFrom && to.redirectedFrom === (owner?.redirectedFrom ?? owner))
|
||||
}
|
||||
|
||||
router.beforeEach(to => {
|
||||
if (doc.getElementById('admin-boot')) return
|
||||
notify?.()
|
||||
owner = to
|
||||
if (timer !== undefined || bar) return
|
||||
timer = setTimeout(() => {
|
||||
timer = undefined
|
||||
bar = doc.createElement('div')
|
||||
bar.id = 'admin-route-progress'
|
||||
bar.setAttribute('role', 'progressbar')
|
||||
bar.setAttribute('aria-label', '正在打开页面')
|
||||
doc.body.appendChild(bar)
|
||||
}, 180)
|
||||
})
|
||||
router.afterEach((to, _from, failure) => {
|
||||
// Duplicates bypass beforeEach, including redirects back to the current route.
|
||||
if (owns(to) || isNavigationFailure(failure, NavigationFailureType.duplicated)) stop()
|
||||
})
|
||||
router.onError((error, to) => {
|
||||
if (owns(to)) {
|
||||
stop()
|
||||
// Page assets failed after the app started. Don't reload over an
|
||||
// unsaved form or mistake a background request for a route error.
|
||||
notify?.(to.fullPath)
|
||||
}
|
||||
console.error('路由导航失败:', error)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { shallowRef } from 'vue'
|
||||
|
||||
// Ephemeral UI state. Navigation targets are issued only by the existing router.
|
||||
export const failedRoute = shallowRef<string>()
|
||||
export function reportRouteLoad(path?: string) { failedRoute.value = path }
|
||||
@@ -0,0 +1,118 @@
|
||||
// Real Vue Router guards, memory history, no network or browser profile.
|
||||
const { test } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
const { readFileSync } = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const ts = require('typescript')
|
||||
const { createMemoryHistory, createRouter } = require('vue-router')
|
||||
const read = file => readFileSync(path.join(__dirname, '..', file), 'utf8')
|
||||
const result = ts.transpileModule(read('src/utils/nav-loading.ts'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }
|
||||
})
|
||||
const lib = {}; new Function('exports', 'require', result.outputText)(lib, require)
|
||||
const turn = () => new Promise(resolve => setImmediate(resolve))
|
||||
|
||||
function setup(t) {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] })
|
||||
const nodes = new Map()
|
||||
const doc = {
|
||||
getElementById: id => nodes.get(id),
|
||||
createElement: () => ({
|
||||
setAttribute(name, value) { this[name] = value },
|
||||
remove() { nodes.delete(this.id) }
|
||||
}),
|
||||
body: { appendChild(item) { nodes.set(item.id, item) } }
|
||||
}
|
||||
const router = createRouter({ history: createMemoryHistory(),
|
||||
routes: ['/a', '/b', '/c'].map(path => ({ path, component: {} })) })
|
||||
lib.installNavigationFeedback(router, doc)
|
||||
const bar = () => nodes.get('admin-route-progress')
|
||||
return { router, bar, nodes, tick: ms => t.mock.timers.tick(ms) }
|
||||
}
|
||||
|
||||
test('both native entries share static start / recovery UI and a CSP-compatible local boot asset', () => {
|
||||
for (const file of ['index.html', 'live-native/index.html']) {
|
||||
const entry = read(file)
|
||||
assert.match(entry, /id="admin-boot" data-state="loading"/)
|
||||
assert.match(entry, /role="status"/)
|
||||
assert.match(entry, /id="admin-boot-retry"/)
|
||||
assert.match(entry, /admin-boot\.js/)
|
||||
}
|
||||
const css = read('public/admin-loading.css')
|
||||
assert.match(css, /prefers-reduced-motion: reduce/)
|
||||
assert.match(css, /pointer-events: none/)
|
||||
})
|
||||
|
||||
test('fast switch does not flash; a slow switch is hidden by the boot screen', async t => {
|
||||
const { router, bar, nodes, tick } = setup(t)
|
||||
let finish
|
||||
router.beforeEach(() => new Promise(resolve => { finish = resolve }))
|
||||
nodes.set('admin-boot', {})
|
||||
let nav = router.push('/a'); await turn(); tick(5000)
|
||||
assert.equal(bar(), undefined); finish(); await nav; nodes.delete('admin-boot')
|
||||
nav = router.push('/b'); await turn(); tick(179)
|
||||
assert.equal(bar(), undefined); finish(); await nav; tick(5000)
|
||||
assert.equal(bar(), undefined)
|
||||
})
|
||||
|
||||
test('a stale completion does not hide the new pending route; abort and error both finish', async t => {
|
||||
const { router, bar, tick } = setup(t)
|
||||
await router.push('/a')
|
||||
const pending = {}
|
||||
router.beforeEach(to => new Promise((resolve, reject) => { pending[to.path] = {resolve, reject} }))
|
||||
const first = router.push('/b'); await turn(); tick(180)
|
||||
const visible = bar(); assert.equal(visible.role, 'progressbar')
|
||||
const second = router.push('/c'); await turn()
|
||||
pending['/b'].resolve(); await first
|
||||
assert.equal(bar(), visible)
|
||||
pending['/c'].resolve(false); await second
|
||||
assert.equal(bar(), undefined)
|
||||
const failed = router.push('/b'); await turn(); tick(180); assert.ok(bar())
|
||||
pending['/b'].reject(new Error('test chunk'))
|
||||
await assert.rejects(failed, /test chunk/); assert.equal(bar(), undefined)
|
||||
})
|
||||
|
||||
test('redirect to new destination or to same page finishes without leftovers', async t => {
|
||||
const { router, bar, tick } = setup(t)
|
||||
let finish
|
||||
router.beforeEach(to => to.path === '/b' ? new Promise(resolve => { finish = resolve }) : undefined)
|
||||
await router.push('/a')
|
||||
for (const target of ['/a', '/c']) {
|
||||
const redirected = router.push('/b'); await turn(); tick(180); assert.ok(bar())
|
||||
finish(target); await redirected
|
||||
assert.equal(bar(), undefined); assert.equal(router.currentRoute.value.path, target)
|
||||
}
|
||||
})
|
||||
|
||||
test('duplicate navigation cancels the progress while the superseded guard is still waiting', async t => {
|
||||
const { router, bar, tick } = setup(t)
|
||||
await router.push('/a')
|
||||
let finish
|
||||
router.beforeEach(() => new Promise(resolve => { finish = resolve }))
|
||||
const pending = router.push('/b'); await turn(); tick(180); assert.ok(bar())
|
||||
await router.push('/a'); assert.equal(bar(), undefined)
|
||||
finish(); await pending; assert.equal(bar(), undefined)
|
||||
})
|
||||
|
||||
test('preflight honors saved appearance, slow is recoverable, and only module failure marks error', t => {
|
||||
const vm = require('node:vm')
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] })
|
||||
const listeners = new Map()
|
||||
const boot = { dataset: {state:'loading'} }
|
||||
vm.runInNewContext(read('public/admin-boot.js'), {
|
||||
document: { getElementById: () => boot, documentElement: { dataset: {defaultAdminUi:'v2'} } },
|
||||
localStorage: { getItem: key => key === 'like_admin_admin_ui_v2_setting' ? '{"value":{"colorMode":"dark"}}' : null },
|
||||
window: {
|
||||
addEventListener(name, fn) { listeners.set(name, fn) },
|
||||
removeEventListener(name) { listeners.delete(name) }
|
||||
},
|
||||
setTimeout, clearTimeout
|
||||
})
|
||||
assert.equal(boot.dataset.mode, 'dark')
|
||||
listeners.get('error')({target:{tagName:'SCRIPT',type:'text/javascript'}})
|
||||
assert.equal(boot.dataset.state, 'loading')
|
||||
t.mock.timers.tick(12000); assert.equal(boot.dataset.state, 'slow')
|
||||
listeners.get('error')({target:{tagName:'SCRIPT',type:'module'}})
|
||||
assert.equal(boot.dataset.state, 'error')
|
||||
listeners.get('admin:mounted')(); assert.equal(listeners.has('error'), false)
|
||||
})
|
||||
Reference in New Issue
Block a user