feat(admin): 优化窄屏工作标签及键盘导航

This commit is contained in:
2026-12-01 18:19:18 +08:00
parent bfaf51796d
commit 878376a7fc
4 changed files with 283 additions and 29 deletions
+183
View File
@@ -0,0 +1,183 @@
"""Offline Playwright contract for the real native work tabs (never contacts the official API)."""
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, COST, LOGIN, OVERVIEW, PASS, SELF, USER, Fixture, loopback, menu, open_group
HOME = "自录转化统计"
LONG = "账户消耗录入与跨部门合作经营分析报表历史记录逐日统计明细汇总工作清单"
THIRD = "渠道复核"
TOOLS = "标签页操作"
def register_menu(fixture):
leaves = fixture.reads[SELF]["menu"][0]["children"][0]["children"]
leaves[1]["name"] = LONG
leaves.append(menu(305, THIRD, "review?via=tabs&team=qa", component="stats/self_input/index"))
def geometry(tab):
return tab.evaluate("""async el => {
const next = () => new Promise(r => requestAnimationFrame(r));
await next(); await next();
const strip = el.closest('.app-tabs');
await Promise.allSettled(strip.getAnimations({subtree:true})
.filter(a => a.effect?.getComputedTiming().endTime < Infinity).map(a => a.finished));
const r = el.getBoundingClientRect(), clip = strip.querySelector('.el-tabs__nav-scroll').getBoundingClientRect();
const x = el.querySelector('.is-icon-close'), c = x.getBoundingClientRect();
const hit = (node,rect) => node.contains(document.elementFromPoint(rect.x+rect.width/2, rect.y+rect.height/2));
const label = [...el.querySelectorAll('*')].find(n => n.innerText === el.innerText &&
getComputedStyle(n).textOverflow === 'ellipsis' && n.scrollWidth > n.clientWidth);
return {tabWidth:r.width, stripWidth:clip.width, inside: r.left >= clip.left-1 && r.right <= clip.right+1,
hitLabel: hit(el,r), hitClose: c.width > 0 && hit(x,c), ellipsis: !!label,
overlap: label ? label.getBoundingClientRect().right > c.left+1 : null,
title: el.title || [...el.querySelectorAll('[title]')].find(n=>n.title)?.title || '',
namedActions: !!strip.querySelector('button[aria-label="标签页操作"]')};
}""")
def shot(page, out, name):
if out:
page.screenshot(path=str(out / f"tabs-{name}.png"), animations="disabled")
def exercise(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)
strip = page.locator(".app-tabs")
tabs = strip.get_by_role("tab")
actions = strip.get_by_role("button", name=TOOLS, exact=True)
tab = lambda name: strip.get_by_role("tab", name=name, exact=True)
cmd = lambda name: page.get_by_role("menuitem", name=name, exact=True)
menu_root = page.locator(".app-aside .menu:visible")
def visit(name):
parent = open_group(open_group(menu_root, "数据统计"), "自录数据统计")
parent.get_by_role("link", name=name, exact=True).click()
active(name)
def active(name):
expect(tab(name)).to_have_attribute("aria-selected", "true")
path, query, component = {
HOME: ("/admin/stats/self_input", {}, "self-input-stats-page"),
LONG: ("/admin/stats/self_input/account_cost", {"via": ["sidebar"]}, "personal-account-cost-page"),
THIRD: ("/admin/stats/self_input/review", {"via": ["tabs"], "team": ["qa"]}, "self-input-stats-page"),
}[name]
expect(page).to_have_url(re.compile(re.escape(path) + r"/?(?:\?.*)?$"))
assert parse_qs(urlsplit(page.url).query) == query, ("route query", name)
expect(page.locator("main ." + component)).to_be_visible()
expect(strip.locator('[role=tab][aria-selected="true"]')).to_have_count(1)
visit(HOME)
visit(LONG)
visit(THIRD)
expect(tabs).to_have_count(3)
tab(LONG).click()
active(LONG)
# An inactive close icon must remove *that* tab without first navigating to it.
tab(THIRD).locator(".is-icon-close").click()
expect(tabs).to_have_count(2)
active(LONG)
visit(THIRD)
# A user may follow an in-page bookmark; switching tabs must not drop it.
page.evaluate("location.hash = 'details'")
expect(tab(THIRD)).to_have_attribute("id", re.compile(r"#details$"))
tab(HOME).click()
active(HOME)
page.emulate_media(color_scheme="dark")
expect(page.locator("html")).to_have_class(re.compile(r"\bdark\b"))
page.set_viewport_size({"width": 390, "height": 844})
tab(HOME).focus()
page.keyboard.press("ArrowRight")
active(LONG)
metrics = geometry(tab(LONG))
# ElTabs schedules scrollToActiveTab after the route update and resize
# observer. Poll the painted hit targets, rather than assume two frames.
for _ in range(25):
if metrics["inside"] and metrics["hitClose"]:
break
page.wait_for_timeout(40)
metrics = geometry(tab(LONG))
print("dark 390px:", json.dumps(metrics, ensure_ascii=False), flush=True)
shot(page, out, "dark-390")
assert metrics["inside"] and metrics["hitClose"] and metrics["hitLabel"], metrics
assert metrics["ellipsis"] and not metrics["overlap"], metrics
if metrics["title"] != LONG:
tab(LONG).hover()
expect(page.get_by_role("tooltip").get_by_text(LONG, exact=True)).to_be_visible()
expect(actions).to_be_visible()
tab(LONG).focus()
page.keyboard.press("Tab")
expect(actions).to_be_focused()
page.keyboard.press("Enter")
expect(cmd("关闭当前")).to_be_visible()
page.keyboard.press("Escape")
expect(cmd("关闭当前")).to_be_hidden()
expect(actions).to_be_focused()
actions.press("Enter")
cmd("关闭当前").click()
expect(tabs).to_have_count(2)
expect(tab(LONG)).to_have_count(0)
active(HOME)
# Route & query of the retained tab must survive both the switch and bulk close.
tab(THIRD).click()
active(THIRD)
assert urlsplit(page.url).fragment == "details", page.url
actions.click()
cmd("关闭其他").click()
expect(tabs).to_have_count(1)
active(THIRD)
expect(tab(THIRD).locator(".is-icon-close")).to_have_count(0)
actions.press("Enter")
expect(cmd("关闭当前")).to_be_disabled()
expect(cmd("关闭其他")).to_be_disabled()
shot(page, out, "single")
page.keyboard.press("Escape")
expect(cmd("关闭其他")).to_be_hidden()
return metrics
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--host", type=loopback, default="127.0.0.1:5179")
parser.add_argument("--chrome", required=True)
parser.add_argument("--out", type=Path, help="Optional directory for local screenshots")
args = parser.parse_args()
if args.out:
args.out.mkdir(parents=True, exist_ok=True)
fixture = Fixture(args.host, False, False)
register_menu(fixture)
with sync_playwright() as pw, pw.chromium.launch(executable_path=args.chrome, 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:
metrics = exercise(page, fixture, args.out)
assert ["GET", COST] in fixture.calls and ["GET", OVERVIEW] in fixture.calls
assert [p for method, p in fixture.calls if method == "POST"] == [LOGIN], fixture.calls
assert not fixture.errors, fixture.errors
except Exception:
shot(page, args.out, "failure")
print("mocked:", fixture.calls, "errors:", fixture.errors, flush=True)
raise
print(json.dumps({"work_tabs": "PASS", "real_api_calls": 0, "dark390": metrics}, ensure_ascii=False))
if __name__ == "__main__":
main()
@@ -1,25 +1,28 @@
<template>
<div class="app-tabs pl-4 flex bg-body">
<div class="flex-1 min-w-0">
<div class="app-tabs pl-4 flex bg-body" :class="{ 'work-tabs--art': art }">
<div class="work-tabs__lane flex-1 min-w-0">
<el-tabs
:model-value="currentTab"
:closable="tabsLists.length > 1"
@tab-change="handleChange"
@tab-remove="removeTab($event)"
@tab-remove="closeTab"
>
<template v-for="item in tabsLists" :key="item.fullPath">
<el-tab-pane :label="item.title" :name="item.fullPath"></el-tab-pane>
</template>
<el-tab-pane v-for="item in tabsLists" :key="item.fullPath" :name="item.fullPath" :label="item.title">
<template #label>
<span class="work-tabs__label" :title="item.title">{{ item.title }}</span>
</template>
</el-tab-pane>
</el-tabs>
</div>
<el-dropdown @command="handleCommand">
<span class="flex items-center px-3">
<icon :size="16" name="el-icon-arrow-down" />
</span>
<el-dropdown ref="actionsMenu" class="work-tabs__actions" :trigger="art ? 'click' : 'hover'" @command="handleCommand">
<button ref="actionsButton" class="work-tabs__trigger flex items-center px-3" type="button"
aria-label="标签页操作" title="标签页操作" @keydown.esc.stop.prevent="dismissActions">
<icon :size="art ? 20 : 16" name="el-icon-arrow-down" />
</button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item command="closeCurrent"> 关闭当前 </el-dropdown-item>
<el-dropdown-item command="closeOther"> 关闭其他 </el-dropdown-item>
<el-dropdown-menu @keydown.esc.capture.stop.prevent="dismissActions">
<el-dropdown-item command="closeCurrent" :disabled="!canCloseCurrent">关闭当前</el-dropdown-item>
<el-dropdown-item command="closeOther" :disabled="!canCloseCurrent">关闭其他</el-dropdown-item>
<el-dropdown-item command="closeAll"> 关闭全部 </el-dropdown-item>
</el-dropdown-menu>
</template>
@@ -28,29 +31,48 @@
</template>
<script setup lang="ts">
import type { DropdownInstance } from 'element-plus'
import useMultipleTabs from '@/hooks/useMultipleTabs'
import { useWatchRoute } from '@/hooks/useWatchRoute'
import useTabsStore, { getRouteParams } from '@/stores/modules/multipleTabs'
import { getRouteParams } from '@/stores/modules/multipleTabs'
import useSettingStore from '@/stores/modules/setting'
const router = useRouter()
const tabsStore = useTabsStore()
const settings = useSettingStore()
const actionsMenu = ref<DropdownInstance>()
const actionsButton = ref<HTMLButtonElement>()
const dismissActions = () => {
actionsMenu.value?.handleClose()
actionsButton.value?.focus()
}
const art = computed(() => settings.adminUi === 'v2')
const { removeOtherTab, addTab, removeAllTab, removeTab, tabsLists, currentTab } = useMultipleTabs()
useWatchRoute(() => {
addTab()
})
const handleChange = (fullPath: any) => {
const tabItem = tabsStore.tasMap[fullPath]
router.push(getRouteParams(tabItem))
const canCloseCurrent = computed(() =>
tabsLists.value.length > 1 && tabsLists.value.some(tab => tab.fullPath === currentTab.value)
)
const handleChange = (fullPath: string | number) => {
// Removal or a route refresh may notify ElTabs after the pane disappeared.
if (fullPath === currentTab.value) return
const tab = tabsLists.value.find(item => item.fullPath === fullPath)
if (tab) router.push(getRouteParams(tab))
}
const closeTab = (fullPath: string | number) => {
if (tabsLists.value.length > 1 && tabsLists.value.some(item => item.fullPath === fullPath)) {
removeTab(fullPath)
}
}
const handleCommand = (command: any) => {
const handleCommand = (command: string) => {
switch (command) {
case 'closeCurrent':
removeTab()
if (canCloseCurrent.value) removeTab()
break
case 'closeOther':
removeOtherTab()
if (canCloseCurrent.value) removeOtherTab()
break
case 'closeAll':
removeAllTab()
@@ -121,4 +143,53 @@ const handleCommand = (command: any) => {
}
}
}
// ArtWorkTab separates its scrolling 32px chips from a fixed 32px action
// button. Keep Element's tablist, scroll arrows, Delete key and roving focus.
.app-tabs.work-tabs--art {
min-width: 0;
align-items: flex-start;
column-gap: 6px;
.work-tabs__lane { container-type: inline-size; }
.work-tabs__label {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
:deep(.el-tabs__item) {
max-width: min(220px, 50vw);
// Leave room for Element's two scroll arrows even on a narrow lane.
max-width: min(220px, calc(100cqi - 52px));
padding: 0 10px !important;
&.is-closable { padding-inline: 12px 8px !important; }
&:focus-visible { outline: 2px solid var(--zyt-primary); outline-offset: -2px; }
.is-icon-close {
flex: 0 0 18px;
width: 18px;
height: 18px;
margin-left: 2px;
font-size: 10px;
color: var(--art-gray-600);
&:hover { background: var(--zyt-hover); color: var(--zyt-ink); }
}
}
.work-tabs__actions { flex: none; }
.work-tabs__trigger {
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
padding: 0;
border: 1px solid var(--zyt-card-border);
border-radius: calc(var(--zyt-radius) / 2.5);
background: var(--zyt-surface);
color: var(--art-gray-700);
cursor: pointer;
&:hover { background: var(--zyt-hover); }
&:focus-visible { outline: 2px solid var(--zyt-primary); outline-offset: -2px; }
}
}
</style>
+2 -8
View File
@@ -55,14 +55,8 @@ const getComponentName = (route: RouteLocationNormalized) => {
return route.matched.at(-1)?.components?.default?.name
}
export const getRouteParams = (tabItem: TabItem) => {
const { params, path, query } = tabItem
return {
params: params || {},
path,
query: query || {}
}
}
// fullPath already includes resolved dynamic params, encoded query, and fragment.
export const getRouteParams = (tabItem: TabItem) => tabItem.fullPath
const useTabsStore = defineStore({
id: 'tabs',
@@ -17,3 +17,9 @@
- 上游对照:`art-sidebar-menu/widget/SidebarSubmenu.vue` 与 `theme.scss`。保留 Element Plus 原有展开、浮层、旋转和路由,只固定箭头图形宽度,为标题预留空间,折叠时以整条菜单轨道居中。
- 离线 Chrome:214px 菜单行的箭头宽由 198px 回到 13px;“医生管理”文字到箭头的间距由 -101px 到 84px。品牌、备用标记、目录及叶项图标在 64px 轨道的中心均为 x=32;180px 深色、230px 常规、390px 抽屉均能打开三级叶项,标签起点依次为 49/69/89px。全屏壳和登录/路由夹具回归通过,无正式接口请求。
- 复审决定:390px 窗口里,原工作标签的长标题占 457px,而轨道只有 280px;操作入口没有可访问名称。V2 限定修这两处及标签切换时的地址保留,不更换页面缓存或标签管理机制。
### V2:工作标签
- 对照上游 `art-work-tab/index.vue`,将滚动标签与操作入口分开。390px 暗色浏览器里,同一个标题现在占 220px(可视轨道 282px),文本省略、完整标题可查、关闭叉可点击。关闭其他标签后,保留页的 query 和锚点均不丢。
- 三个原生业务路由实测:键盘方向键切页、Enter 打开操作、Esc 关闭并返回焦点、关闭非当前页不误跳转、单页禁用“关闭当前/其他”;登录组合及原始菜单回归通过。
- 复审决定:原自录统计页在暗色下仍绘制近白卡片;390px 每行仅 1 张卡;加载、遗漏字段都显示为零。离线制造“近7天”慢于“近30天”时,还会出现过期统计、日期和财务字段。V3 限定这一个业务页面,使用已有的“只采纳最后一次响应”能力,不改服务端计算或鉴权。