feat(admin): 以固定双列替代桌面二级悬浮菜单

This commit is contained in:
2026-12-01 19:39:25 +08:00
parent e8da0054fa
commit d8a16b0778
12 changed files with 888 additions and 118 deletions
+15 -14
View File
@@ -109,13 +109,19 @@ class Fixture:
return route.fulfill(headers=cors, json={"code": 1, "show": 0, "msg": "", "data": data})
def open_group(parent, name):
label = parent.locator(".el-sub-menu__title").filter(has_text=re.compile("^" + re.escape(name) + "$"))
expect(label).to_be_visible()
group = label.locator("..")
if "is-opened" not in (group.get_attribute("class") or "").split():
label.click()
return group
def desktop_entry(page, name, root="数据统计", nested="自录数据统计"):
"""Use the visible desktop controls; avoid reselecting a root that is already open."""
rail = page.get_by_role("navigation", name="一级菜单", exact=True)
panel = page.get_by_role("navigation", name="二级菜单", exact=True)
group = rail.get_by_role("button", name=root, exact=True)
if group.get_attribute("aria-expanded") != "true":
group.click()
expect(panel).to_be_visible()
if nested:
branch = panel.get_by_role("button", name=nested, exact=True)
if branch.get_attribute("aria-expanded") != "true":
branch.click()
return panel.get_by_role("link", name=name, exact=True)
def check_app(page, fixture, out):
@@ -132,17 +138,12 @@ def check_app(page, fixture, out):
expect(page.get_by_text(label, exact=True)).to_be_visible()
page.mouse.move(1, 1)
aside = page.locator(".app-aside .menu:visible")
def entry(name):
parent = open_group(open_group(aside, "数据统计"), "自录数据统计")
return parent.get_by_role("menuitem", name=name, exact=True)
# First visit the sibling; the empty child below must be selected by click, not just by initial redirect.
entry("账户消耗录入").click()
desktop_entry(page, "账户消耗录入").click()
expect(page.locator("main .personal-account-cost-page")).to_be_visible()
expect(page.locator("main .personal-account-cost-page").get_by_role("button", name="新增", exact=True)).to_be_visible() # Authorized control is present; never submit any business write.
assert parse_qs(urlsplit(page.url).query).get("via") == ["sidebar"], page.url
entry("自录转化统计").click()
desktop_entry(page, "自录转化统计").click()
stats = page.locator("main .self-input-stats-page")
expect(stats.get_by_text("业绩明细", exact=True)).to_be_visible()
expect(stats.locator(".el-table").get_by_text("OFFLINE-today", exact=True)).to_be_visible()
+223 -73
View File
@@ -3,6 +3,7 @@ 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
@@ -14,8 +15,11 @@ NESTED = "自录数据统计与跨部门综合分析报表导航"
LEAF = "账户消耗录入与跨部门财务对账明细"
OTHER = "运营管理与跨部门协作流程工作中心"
TOP_LEAF = "独立账户消耗录入"
HOME = "自录转化统计"
DETAIL = "运营明细"
HIDDEN = "仅后台可见明细"
HIDDEN_ROOT = "隐藏目录"
TITLE = ".el-sub-menu__title"
POP = ".el-menu--popup:visible"
def setup_menu(fixture):
@@ -24,11 +28,19 @@ def setup_menu(fixture):
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=[
menu(411, "运营明细", "details", component="stats/self_input/account_cost")]))
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))
# 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):
@@ -136,6 +148,56 @@ def close_settings(page, drawer):
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 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)
@@ -144,76 +206,145 @@ def check(page, fixture, out):
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")
side = page.locator(".side:visible")
rail = side.locator(".menu")
r, n = title(rail, ROOT), title(rail, NESTED)
toggle(r, True)
toggle(n, False)
leaf = rail.get_by_text(LEAF, exact=True)
expect(leaf).to_be_hidden()
arrow = n.locator(".el-sub-menu__icon-arrow")
orientation = "(el) => [getComputedStyle(el).transform, el.innerHTML].join(' ')"
closed_state = arrow.evaluate(orientation)
toggle(n, True)
assert arrow.evaluate(orientation) != closed_state, "nested arrow did not indicate its new state"
expect(leaf).to_be_visible()
toggle(r, False)
expect(n).to_be_hidden()
other = title(rail, OTHER)
toggle(other, True)
expect(rail.get_by_text("运营明细", exact=True)).to_be_visible()
toggle(other, False)
expect(rail.get_by_text("运营明细", exact=True)).to_be_hidden()
report = {"expanded": expanded(rail)}
screenshot(page, out, "expanded")
# Move by Tab from its known preceding leaf, then activate the actual router link.
previous = rail.get_by_role("link", name="自录转化统计", exact=True)
previous.focus()
page.keyboard.press("Tab")
expect(rail.get_by_role("link", name=LEAF, exact=True)).to_be_focused()
page.keyboard.press("Enter")
expect(page.locator("main .personal-account-cost-page")).to_be_visible()
rail = 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")
expect(fold).to_have_attribute("aria-expanded", "true")
fold.focus()
page.keyboard.press("Enter")
expect(fold).to_have_attribute("aria-expanded", "false")
expect(rail.locator(".el-menu--collapse")).to_be_visible()
settle(side)
logo = side.locator(".logo img")
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")
report["collapsed_centers"] = {
"logo": center(rail, logo, "brand image"),
"group": center(rail, r.locator(".menu-item-icon svg"), "root group icon"),
"no_icon_group": center(rail, other.locator(".menu-item-icon"), "root initial"),
"leaf": center(rail, rail.locator("a[href$='/solo'] .menu-item-icon svg"), "root leaf icon")
}
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")
initial = other.locator(".menu-item-icon")
assert initial.evaluate("""el => {
const s = getComputedStyle(el, '::before');
return el.textContent.trim() || (s.content !== 'none' && s.content !== 'normal' &&
s.content !== '""' && s.display !== 'none' && s.visibility === 'visible');
}"""), "an iconless root must retain a visible identifier in the collapsed rail"
# 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)
# Element Plus teleports the submenu outside .side when collapsed.
r.hover()
popup_n = title(page.locator(POP), NESTED)
expect(popup_n).to_be_visible()
settle(popup_n.locator("xpath=ancestor::*[contains(concat(' ',normalize-space(@class),' '),' el-popper ')][1]"))
arrow_metrics(popup_n, NESTED)
popup_n.hover()
popup_leaf = page.locator(POP).get_by_text(LEAF, exact=True)
expect(popup_leaf).to_be_visible()
screenshot(page, out, "popup")
fold.hover()
expect(popup_leaf).to_be_hidden()
# 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")
expect(fold).to_have_attribute("aria-expanded", "false")
expect(panel).to_be_hidden()
report["collapsed"] = layout(page, rail)
assert report["collapsed"]["rail"] < report["expanded"]["rail"]
page.set_viewport_size({"width": 1350, "height": 960})
settle(page.locator(".layout-default"))
expect(panel).to_be_hidden()
expect(fold).to_have_attribute("aria-expanded", "false")
assert layout(page, rail) == report["collapsed"]
report["collapsed_centers"] = {"logo": center(rail, logo, "brand image")}
for key, target in (("group", root.locator(".dual-root-icon svg")),
("no_icon_group", other.locator(".dual-root-icon")),
("leaf", solo.locator(".dual-root-icon svg"))):
report["collapsed_centers"][key] = center(rail, target, key)
expect(other.locator(".dual-root-icon")).to_have_text(OTHER[0])
screenshot(page, out, "collapsed")
other.press("Enter")
expect(fold).to_have_attribute("aria-expanded", "true")
route_at(page, d_path, d_query)
selected(other, detail)
assert layout(page, rail, panel, expected_width=230) == report["expanded"]
drawer = settings(page)
# Element Plus exposes a visually-hidden checkbox and a separate painted track.
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()
@@ -222,27 +353,46 @@ def check(page, fixture, out):
width.fill("180")
width.press("Enter")
close_settings(page, drawer)
root.click()
selected(root, home)
expect(logo).to_be_hidden()
report["collapsed_centers"]["fallback"] = center(rail, side.locator(".admin-nav-heading svg"), "no-logo icon")
fold.press("Enter")
expect(fold).to_have_attribute("aria-expanded", "true")
expect(rail).to_have_class(re.compile(r"\btheme-dark\b"))
settle(side)
assert abs(rail.bounding_box()["width"] - 180) <= 1, rail.bounding_box()
report["dark_180px"] = expanded(rail)
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")
page.set_viewport_size({"width": 390, "height": 844})
expect(rail).to_be_hidden()
expect(panel).to_be_hidden()
fold.click()
mobile = page.locator(".el-drawer:visible .side")
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="自录转化统计", exact=True).click()
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()
# Switch through the user's settings, not injected CSS/localStorage.
page.set_viewport_size({"width": 1440, "height": 960})
expect(rail).to_be_visible()
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
+2 -3
View File
@@ -9,7 +9,7 @@ from urllib.parse import parse_qs, urlsplit
from PIL import Image
from playwright.sync_api import expect, sync_playwright
from browser_contract import ACCOUNT, LOGIN, OFFICIAL, OVERVIEW, PASS, SELF, TOKEN, USER, Fixture, loopback, open_group
from browser_contract import ACCOUNT, LOGIN, OFFICIAL, OVERVIEW, PASS, SELF, TOKEN, USER, Fixture, desktop_entry, loopback
SOURCE = "离线验收来源"
@@ -170,8 +170,7 @@ def enter(page, fixture):
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")
aside = page.locator(".app-aside .menu:visible")
open_group(open_group(aside, "数据统计"), "自录数据统计").get_by_text("自录转化统计", exact=True).click()
desktop_entry(page, "自录转化统计").click()
stats = page.locator(PAGE)
expect(stats).to_be_visible()
return stats
+2 -5
View File
@@ -7,7 +7,7 @@ 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
from browser_contract import ACCOUNT, COST, LOGIN, OVERVIEW, PASS, SELF, USER, Fixture, desktop_entry, loopback, menu
HOME = "自录转化统计"
LONG = "账户消耗录入与跨部门合作经营分析报表历史记录逐日统计明细汇总工作清单"
@@ -57,11 +57,8 @@ def exercise(page, fixture, out):
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()
desktop_entry(page, name).click()
active(name)
def active(name):
+10 -4
View File
@@ -1,17 +1,18 @@
<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { useThrottleFn, useWindowSize } from '@vueuse/core'
import { useWindowSize } from '@vueuse/core'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ScreenEnum } from './enums/appEnums'
import useAppStore from './stores/modules/app'
import { useAdminDark } from './stores/modules/setting'
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'
const appStore = useAppStore()
const settings = useSettingStore()
// Resolve the saved appearance, system mode and palette before routes render.
useAdminDark()
const userStore = useUserStore()
@@ -31,7 +32,12 @@ const elConfig = {
const { width } = useWindowSize()
watch(
width,
useThrottleFn((value) => {
(value, previous) => {
// Resizing within one desktop breakpoint must not reopen the fixed
// navigation pane after the user explicitly closed it.
if (settings.adminUi === 'v2' && previous !== undefined &&
value > ScreenEnum.SM && previous > ScreenEnum.SM &&
(value < ScreenEnum.MD) === (previous < ScreenEnum.MD)) return
if (value > ScreenEnum.SM) {
appStore.setMobile(false)
appStore.toggleCollapsed(false)
@@ -42,7 +48,7 @@ watch(
if (value < ScreenEnum.MD) {
appStore.toggleCollapsed(true)
}
}),
},
{
immediate: true
}
@@ -0,0 +1,118 @@
<template>
<ul class="dual-branch">
<li v-for="node in nodes" :key="node.key">
<component
:is="node.children.length ? 'button' : AppLink"
:type="node.children.length ? 'button' : undefined"
:to="node.children.length ? undefined : node.target"
:rel="node.external ? 'noopener noreferrer' : undefined"
class="dual-row"
:class="{ 'is-active': node.key === leafKey }"
:style="{ '--branch-depth': depth }"
:title="node.title"
:aria-label="node.title"
:aria-current="node.key === leafKey ? 'page' : undefined"
:aria-expanded="node.children.length ? opened.includes(node.key) : undefined"
@click="node.children.length && toggle(node.key)"
>
<icon v-if="node.icon" :name="node.icon" :size="18" class="dual-row-icon" aria-hidden="true" />
<span class="dual-label">{{ node.title }}</span>
<svg v-if="node.children.length" class="dual-chevron" aria-hidden="true"
viewBox="0 0 16 16" width="14" height="14" fill="none">
<path d="m4 6 4 4 4-4" stroke="currentColor" stroke-width="1.5"
stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</component>
<dual-branch
v-if="node.children.length && opened.includes(node.key)"
:nodes="node.children"
:depth="depth + 1"
:leaf-key="leafKey"
:ancestor-keys="ancestorKeys"
:route-key="routeKey"
:unique="unique"
/>
</li>
</ul>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import AppLink from '@/components/app-link/index.vue'
import type { DualNode } from './dual-model'
const props = withDefaults(defineProps<{
nodes: DualNode[]
leafKey?: string
ancestorKeys: string[]
routeKey: string
unique: boolean
depth?: number
}>(), { depth: 0 })
// Each list owns its sibling disclosures. Router changes reveal the active
// chain (including on direct load); a user can still close that chain in place.
const opened = ref<string[]>([])
watch([() => props.ancestorKeys, () => props.routeKey, () => props.unique], () => {
const ancestor = props.nodes.find(node => node.children.length && props.ancestorKeys.includes(node.key))
if (ancestor) {
if (props.unique) opened.value = [ancestor.key]
else if (!opened.value.includes(ancestor.key)) opened.value.push(ancestor.key)
} else if (props.unique) {
opened.value = []
}
}, { immediate: true })
function toggle(key: string) {
if (opened.value.includes(key)) opened.value = opened.value.filter(item => item !== key)
else if (props.unique) opened.value = [key]
else opened.value.push(key)
}
</script>
<style scoped>
.dual-branch { margin: 0; padding: 0; list-style: none; }
.dual-row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
height: 42px;
margin-bottom: 4px;
padding-inline: calc(12px + min(3, var(--branch-depth, 0)) * 14px) 12px;
border: 0;
border-radius: 6px;
background: transparent;
color: var(--zyt-nav-text);
font-size: 14px;
line-height: 1.35;
text-align: start;
text-decoration: none;
cursor: pointer;
}
.dual-row:hover { background: var(--zyt-nav-hover); }
.dual-row.is-active {
background: var(--zyt-nav-active);
color: var(--zyt-nav-selected);
}
.dual-row-icon { flex: none; color: var(--zyt-nav-icon); }
.dual-row.is-active .dual-row-icon { color: inherit; }
.dual-label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dual-chevron {
flex: none;
color: var(--zyt-nav-arrow);
transition: transform .16s ease;
}
.dual-row[aria-expanded='true'] > .dual-chevron { transform: rotate(180deg); }
.dual-row:focus-visible { outline: 2px solid var(--zyt-nav-selected); outline-offset: -2px; }
html:not(.dark) .side--light .dual-row.is-active { box-shadow: inset 3px 0 var(--zyt-primary); }
@media (prefers-reduced-motion: reduce) { .dual-chevron { transition: none; } }
</style>
@@ -0,0 +1,154 @@
import {
parseQuery,
type LocationQuery,
type RouteLocationNormalizedLoaded,
type RouteRecordRaw
} from 'vue-router'
import { MenuEnum } from '@/enums/appEnums'
import { getNormalPath, objectToQuery } from '@/utils/util'
import { isExternal } from '@/utils/validate'
export interface DualNode {
key: string
path: string
target: string
title: string
icon?: string
children: DualNode[]
external: boolean
}
function resolvePath(path: string, parent?: string) {
if (parent === undefined || isExternal(path)) return path
// The read-only router assigns absolute IDs even to deeply nested entries.
if (import.meta.env.MODE === 'live-readonly' && path.startsWith('/nav/')) return path
return getNormalPath(`${parent}/${path}`)
}
function menuTarget(path: string, query: unknown) {
let suffix = ''
if (typeof query === 'string' && query) {
try {
suffix = objectToQuery(JSON.parse(query))
} catch {
suffix = query
}
} else if (query && typeof query === 'object') {
suffix = objectToQuery(query)
}
suffix = suffix.replace(/^\?/, '')
return suffix ? `${path}${path.includes('?') ? '&' : '?'}${suffix}` : path
}
/** Project only the current account's supplied menu tree; permission strings are not new routes. */
export function buildDualMenu(routes: RouteRecordRaw[]): DualNode[] {
function visit(records: RouteRecordRaw[], parentPath?: string, parentKey = ''): DualNode[] {
const nodes: DualNode[] = []
const occurrences = new Map<string, number>()
for (const route of records) {
const meta = route.meta
if (meta?.hidden || meta?.type === MenuEnum.BUTTON) continue
const path = resolvePath(route.path, parentPath)
const target = menuTarget(path, meta?.query)
// Index children share their parent's path; query variants also need distinct keys.
const count = occurrences.get(target) || 0
occurrences.set(target, count + 1)
const key = `${parentKey}/${encodeURIComponent(target)}:${count}`
const children = visit(route.children || [], path, key)
// A catalogue is not an authorized landing page. A real page may have hidden details.
if (
!children.length &&
(meta?.type === MenuEnum.CATALOGUE ||
(route.children?.length && meta?.type !== MenuEnum.MENU))
)
continue
nodes.push({
key,
path,
target,
title: meta?.title || '',
icon: meta?.icon,
children,
external: isExternal(path)
})
}
return nodes
}
return visit(routes)
}
/** Entering a module must never open an external site as a side effect. */
export function firstDualLeaf(node: DualNode): DualNode | undefined {
if (!node.children.length) return node.external ? undefined : node
for (const child of node.children) {
const leaf = firstDualLeaf(child)
if (leaf) return leaf
}
}
function splitLocation(location: string) {
const href = location.split('#', 1)[0]
const q = href.indexOf('?')
const path = q < 0 ? href : href.slice(0, q)
return {
path: path.replace(/\/+$/, '') || '/',
query: q < 0 ? undefined : parseQuery(href.slice(q + 1))
}
}
// Compare decoded Vue Router values, not query-string order. Extra page filters are allowed.
function matchQuery(defaults: LocationQuery, current: LocationQuery) {
const keys = Object.keys(defaults)
const matches = keys.every((key) => {
const expected = defaults[key]
const actual = current[key]
return Array.isArray(expected)
? Array.isArray(actual) &&
expected.length === actual.length &&
expected.every((v, i) => v === actual[i])
: expected === actual
})
if (!matches) return -1
if (keys.length === Object.keys(current).length) return Number.POSITIVE_INFINITY
return keys.length
}
interface DualSelection {
root?: DualNode
leaf?: DualNode
/** Includes the root and every group to expand, never the highlighted leaf. */
ancestors: DualNode[]
}
export function findDualSelection(
roots: DualNode[],
route: RouteLocationNormalizedLoaded
): DualSelection {
const active = splitLocation(route.meta.activeMenu || route.path)
const current = active.query ?? route.query
let selection: DualSelection = { ancestors: [] }
let bestScore = Number.NEGATIVE_INFINITY
function visit(nodes: DualNode[], parents: DualNode[]) {
for (const node of nodes) {
if (node.external) continue
const groups = node.children.length ? [...parents, node] : parents
const target = splitLocation(node.target)
if (target.path === active.path) {
// Empty index leaves take precedence over grouping records at the very same path.
const score = node.children.length ? -2 : matchQuery(target.query || {}, current)
if (score > bestScore) {
bestScore = score
selection = {
root: parents[0] || node,
leaf: node.children.length ? undefined : node,
ancestors: groups
}
}
}
if (node.children.length) visit(node.children, groups)
}
}
visit(roots, [])
return selection
}
@@ -0,0 +1,222 @@
<template>
<div class="dual-sidebar" :class="{ 'dual-sidebar--compact': app.isCollapsed }"
@keydown.space="activateLinkWithSpace">
<nav class="dual-primary" aria-label="一级菜单">
<app-link v-if="settings.showLogo" class="logo dual-brand" to="/"
:aria-label="brandName ? brandName + ',返回首页' : '返回首页'" :title="brandName || '首页'">
<image-contain class="logo-mark" :height="34" :width="34" fit="contain"
:src="app.config.web_logo" alt="" />
</app-link>
<div v-else class="admin-nav-heading dual-brand" aria-hidden="true">
<svg viewBox="0 0 24 24" width="24" height="24" fill="none">
<path d="M4 6.5h10M4 12h16M4 17.5h10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<circle cx="19" cy="6.5" r="2" fill="currentColor"/>
</svg>
</div>
<ul ref="rootList" class="dual-roots">
<li v-for="root in roots" :key="root.key">
<component
:is="root.children.length ? 'button' : AppLink"
:type="root.children.length ? 'button' : undefined"
:to="root.children.length ? undefined : root.target"
:rel="root.external ? 'noopener noreferrer' : undefined"
class="dual-root"
:class="{ 'is-active': activeRoot?.key === root.key }"
:aria-expanded="root.children.length ? !app.isCollapsed && activeRoot?.key === root.key : undefined"
:aria-current="!root.children.length && selection.leaf?.key === root.key ? 'page' : undefined"
:aria-label="root.title"
:title="root.title"
@click="chooseRoot(root)"
>
<span class="dual-root-icon" aria-hidden="true">
<icon v-if="root.icon" :name="root.icon" :size="20" />
<template v-else>{{ Array.from(root.title.trim())[0] }}</template>
</span>
<span v-if="!app.isCollapsed" class="dual-root-label">{{ root.title }}</span>
</component>
</li>
</ul>
</nav>
<nav v-if="!app.isCollapsed && activeRoot?.children.length" class="dual-secondary"
aria-label="二级菜单" :style="{ width: settings.sideWidth + 'px' }">
<div class="dual-heading" :title="panelHeading">{{ panelHeading }}</div>
<div ref="branchList" class="dual-scroll" :key="activeRoot.key">
<dual-branch
:nodes="activeRoot.children"
:leaf-key="selection.leaf?.key"
:ancestor-keys="ancestorKeys"
:route-key="route.fullPath"
:unique="settings.isUniqueOpened"
/>
</div>
</nav>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter, type RouteRecordRaw } from 'vue-router'
import AppLink from '@/components/app-link/index.vue'
import useAppStore from '@/stores/modules/app'
import useSettingStore from '@/stores/modules/setting'
import DualBranch from './dual-branch.vue'
import { buildDualMenu, findDualSelection, firstDualLeaf, type DualNode } from './dual-model'
const props = defineProps<{ routes: RouteRecordRaw[] }>()
const app = useAppStore()
const settings = useSettingStore()
const router = useRouter()
const route = useRoute()
const roots = computed(() => buildDualMenu(props.routes))
const selection = computed(() => findDualSelection(roots.value, route))
const ancestorKeys = computed(() => selection.value.ancestors.map(node => node.key))
// Only an external-only directory needs a local selection: it has no internal
// destination. Never open an external site while selecting a group or syncing a route.
const externalGroup = ref<string>()
watch([() => route.fullPath, roots], () => { externalGroup.value = undefined })
const activeRoot = computed(() => externalGroup.value
? roots.value.find(node => node.key === externalGroup.value)
: selection.value.root)
const brandName = computed(() => String(app.config.web_name || ''))
const panelHeading = computed(() =>
(settings.showLogo && brandName.value) || activeRoot.value?.title || ''
)
const rootList = ref<HTMLElement>()
const branchList = ref<HTMLElement>()
function revealActiveItems() {
for (const list of [rootList.value, branchList.value]) {
const item = list?.querySelector('.is-active')
if (!list || !item) continue
const row = item.getBoundingClientRect()
const box = list.getBoundingClientRect()
if (row.top < box.top) list.scrollTop += row.top - box.top
else if (row.bottom > box.bottom) list.scrollTop += row.bottom - box.bottom
}
}
onMounted(revealActiveItems)
watch([activeRoot, selection, () => app.isCollapsed], revealActiveItems, { flush: 'post' })
function chooseRoot(node: DualNode) {
if (!node.children.length) {
if (!node.external) externalGroup.value = undefined
return // The AppLink handles normal navigation and modifier-clicks.
}
if (app.isCollapsed) app.toggleCollapsed(false)
const leaf = firstDualLeaf(node)
externalGroup.value = leaf ? undefined : node.key
if (leaf) void router.push(leaf.target)
}
function activateLinkWithSpace(event: KeyboardEvent) {
// Buttons already handle both keys natively. Extend anchors with Space
// without intercepting their Enter or modified pointer navigation.
if (!(event.target instanceof HTMLAnchorElement)) return
event.preventDefault()
if (!event.repeat) event.target.click()
}
</script>
<style scoped>
.dual-sidebar {
--rail-width: 80px;
display: flex;
flex: 1 1 0;
min-height: 0;
background: var(--zyt-nav-bg);
color: var(--zyt-nav-text);
}
.dual-sidebar--compact { --rail-width: 64px; }
.dual-primary, .dual-secondary {
display: flex;
flex: none;
flex-direction: column;
min-height: 0;
}
.dual-primary { width: var(--rail-width); }
.dual-sidebar .dual-primary > .dual-brand {
flex: none;
justify-content: center;
width: 100%;
height: var(--navbar-height);
padding: 0;
}
.dual-roots, .dual-scroll {
flex: 1;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
overscroll-behavior: contain;
scrollbar-width: thin;
}
.dual-roots {
display: flex;
flex-direction: column;
gap: 6px;
margin: 0;
padding: 4px 8px 12px;
list-style: none;
scrollbar-width: none; /* Keep icon centers aligned with the logo on scroll. */
}
.dual-roots::-webkit-scrollbar { display: none; }
.dual-root {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 5px;
width: 100%;
height: 60px;
padding: 0 2px;
border: 0;
border-radius: 5px;
background: transparent;
color: var(--zyt-nav-text);
text-align: center;
cursor: pointer;
}
.dual-sidebar--compact .dual-root { height: 46px; }
.dual-root:hover { background: var(--zyt-nav-hover); }
.dual-root.is-active {
background: var(--zyt-nav-active);
color: var(--zyt-nav-selected);
}
.dual-root-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
color: var(--zyt-nav-icon);
font-size: 16px;
line-height: 1;
}
.dual-root.is-active .dual-root-icon { color: inherit; }
.dual-root-label, .dual-heading {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dual-root-label { width: 100%; font-size: 12px; line-height: 16px; }
.dual-secondary {
box-sizing: border-box;
border-inline-start: 1px solid var(--zyt-card-border);
}
.dual-heading {
flex: none;
padding-inline: 20px;
color: var(--zyt-nav-title);
font-size: 17px;
font-weight: 600;
line-height: var(--navbar-height);
}
.dual-scroll { padding: 4px 8px 12px; }
.dual-root:focus-visible, .dual-brand:focus-visible {
outline: 2px solid var(--zyt-nav-selected);
outline-offset: -2px;
}
</style>
@@ -1,23 +1,26 @@
<template>
<div class="side" :class="['side--' + sideTheme, { 'side--collapsed': isCollapsed }]" :style="sideStyle">
<side-logo v-if="settingStore.showLogo" :show-title="!isCollapsed" :theme="sideTheme" />
<div v-else-if="settingStore.adminUi === 'v2'" class="admin-nav-heading" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" width="24" height="24">
<path d="M4 6.5h10M4 12h16M4 17.5h10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<circle cx="19" cy="6.5" r="2" fill="currentColor"/>
</svg>
<span v-if="!isCollapsed">工作导航</span>
</div>
<side-menu
:routes="routes"
:is-collapsed="isCollapsed"
:width="settingStore.sideWidth"
:unique-opened="settingStore.isUniqueOpened"
:config="menuProp"
:theme="sideTheme"
:classic="settingStore.adminUi === 'legacy'"
@select="handleSelect"
/>
<dual-sidebar v-if="useDualSidebar" :routes="routes" />
<template v-else>
<side-logo v-if="settingStore.showLogo" :show-title="!isCollapsed" :theme="sideTheme" />
<div v-else-if="settingStore.adminUi === 'v2'" class="admin-nav-heading" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" width="24" height="24">
<path d="M4 6.5h10M4 12h16M4 17.5h10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<circle cx="19" cy="6.5" r="2" fill="currentColor"/>
</svg>
<span v-if="!isCollapsed">工作导航</span>
</div>
<side-menu
:routes="routes"
:is-collapsed="isCollapsed"
:width="settingStore.sideWidth"
:unique-opened="settingStore.isUniqueOpened"
:config="menuProp"
:theme="sideTheme"
:classic="settingStore.adminUi === 'legacy'"
@select="handleSelect"
/>
</template>
</div>
</template>
@@ -26,6 +29,7 @@ import useAppStore from '@/stores/modules/app'
import useSettingStore from '@/stores/modules/setting'
import useUserStore from '@/stores/modules/user'
import DualSidebar from './dual-sidebar.vue'
import SideLogo from './logo.vue'
import SideMenu from './menu.vue'
@@ -39,6 +43,11 @@ const isCollapsed = computed(() => {
})
const settingStore = useSettingStore()
// The fixture and read-only preview clients retain their own menu contracts.
const useDualSidebar = computed(() =>
settingStore.adminUi === 'v2' && !appStore.isMobile &&
!['live-readonly', 'local-preview'].includes(import.meta.env.MODE)
)
const sideTheme = computed(() => settingStore.sideTheme)
const userStore = useUserStore()
+4 -1
View File
@@ -33,7 +33,10 @@ const getHasTabIndex = (fullPath: string, tabList: TabItem[]) => {
/** 同一菜单页可能因 query、重定向等产生不同 fullPath,用 name + 解析后的 path 去重 */
const getTabMergeKey = (item: Pick<TabItem, 'name' | 'path'>) => {
if (item.name == null || item.name === '') return ''
return `${String(item.name)}::${item.path}`
// Router resolves an index child both with and without its parent's final
// slash. Only normalize the tab identity, never the navigation URL.
const path = item.path.replace(/\/+$/, '') || '/'
return `${String(item.name)}::${path}`
}
const isCannotAddRoute = (route: RouteLocationNormalized, router: Router) => {
+104
View File
@@ -0,0 +1,104 @@
const assert = require('node:assert/strict')
const path = require('node:path')
const test = require('node:test')
const { buildSync } = require('esbuild')
const { createMemoryHistory, createRouter } = require('vue-router')
const admin = path.resolve(__dirname, '..')
function loadModel(mode) {
const { outputFiles } = buildSync({
absWorkingDir: admin,
entryPoints: ['src/layout/default/components/sidebar/dual-model.ts'],
alias: { '@': path.join(admin, 'src') },
external: ['vue-router', '@vue/shared', 'lodash'],
bundle: true, write: false, platform: 'node', format: 'cjs',
define: { 'import.meta.env.MODE': JSON.stringify(mode) }
})
const module = { exports: {} }
new Function('require', 'module', 'exports', outputFiles[0].text)(require, module, module.exports)
return module.exports
}
const { buildDualMenu, findDualSelection, firstDualLeaf } = loadModel('production')
const page = (path, title, props = {}) => ({ path, meta: { type: 'C', title, ...props } })
const group = (path, title, children) => ({ path, meta: { type: 'M', title }, children })
test('preserves server order and never promotes hidden, action or empty catalogue entries', () => {
const input = [
group('/empty', '仅隐页', [page('detail', '详情', { hidden: true })]),
group('/also-empty', '空目录', []),
{ ...group('/hidden', '隐目录', [page('jump', '不可见')]), meta: { hidden: true } },
page('/action', '按钮', { type: 'A' }),
{ ...page('/list', '列表', { perms: 'data/list' }), children: [page('edit', '编辑', { hidden: true })] },
group('/ops', '业务', [page('https://example.com/go?from=admin', '外部', { query: '?q=1' }),
group('reports', '报表', [page('day', '日报', { icon: 'el-icon-DataLine' })])])
]
const original = JSON.stringify(input)
const roots = buildDualMenu(input)
assert.deepEqual(roots.map(n => n.title), ['列表', '业务'])
assert.equal(roots[0].children.length, 0)
const [external, reports] = roots[1].children
assert.equal(external.target, 'https://example.com/go?from=admin&q=1')
assert.equal(external.external, true)
assert.equal(firstDualLeaf(external), undefined)
assert.equal(firstDualLeaf(roots[1]), reports.children[0])
assert.equal(firstDualLeaf({ ...roots[1], children: [external] }), undefined)
assert.equal(reports.children[0].path, '/ops/reports/day')
assert.equal(reports.children[0].icon, 'el-icon-DataLine')
assert.equal(JSON.stringify(input), original)
})
test('preserves query defaults and index keys, including multiple index children', () => {
const [root] = buildDualMenu([group('/stats', '统计', [
page('', '默认'), page('', '分组', { query: '{"type":"a b","tab":"本 月"}' }),
page('', '相同目标', { query: '{"type":"a b","tab":"本 月"}' })
])])
assert.deepEqual(root.children.map(n => n.path), ['/stats', '/stats', '/stats'])
assert.equal(root.children[1].target, '/stats?type=a%20b&tab=%E6%9C%AC%20%E6%9C%88')
assert.equal(new Set([root, ...root.children].map(n => n.key)).size, 4)
})
test('restores module and exact query leaf from a URL, router back and hidden-detail activeMenu', async () => {
const roots = buildDualMenu([group('/ops', '业务', [group('stats', '统计', [
page('', '全部'), page('', 'A', { query: '?kind=a' }),
page('', 'A月度', { query: '{"kind":"a","tab":"月 度"}' }), page('', 'B', { query: 'kind=b' })
])]), page('/home', '主页')])
const routes = [
{ path: '/ops/stats', component: {} }, { path: '/home', component: {} },
{ path: '/detail', component: {}, meta: { activeMenu: '/ops/stats?kind=b' } }
]
const router = createRouter({ history: createMemoryHistory(), routes })
const selection = () => findDualSelection(roots, router.currentRoute.value)
await router.push('/ops/stats/?tab=%E6%9C%88+%E5%BA%A6&kind=a')
assert.equal(selection().leaf.title, 'A月度')
assert.deepEqual(selection().ancestors.map(n => n.title), ['业务', '统计'])
await router.push('/ops/stats?kind=b&page=2')
assert.equal(selection().leaf.title, 'B')
await router.push('/detail?id=42')
assert.equal(selection().leaf.title, 'B')
await router.push('/home')
assert.equal(selection().root.title, '主页')
assert.deepEqual(selection().ancestors, [])
const returned = new Promise(resolve => {
const stop = router.afterEach(() => { stop(); resolve() })
})
router.back()
await returned
assert.equal(selection().leaf.title, 'B')
const refreshed = createRouter({ history: createMemoryHistory(), routes })
await refreshed.push(router.currentRoute.value.fullPath)
assert.equal(findDualSelection(roots, refreshed.currentRoute.value).leaf.title, 'B')
await router.push('/ops/stats?kind=c')
assert.equal(selection().leaf.title, '全部')
assert.deepEqual(findDualSelection([], router.currentRoute.value), { ancestors: [] })
})
test('honors read-only absolute /nav IDs without inventing an absolute-path override in native mode', () => {
const records = [group('/nav/module', '一级', [group('/nav/group', '二级', [page('/nav/item', '页面')])])]
const readonly = loadModel('live-readonly')
const roots = readonly.buildDualMenu(records)
assert.equal(readonly.firstDualLeaf(roots[0]).target, '/nav/item')
const selected = readonly.findDualSelection(roots, { path: '/members/detail', meta: { activeMenu: '/nav/item' }, query: { id: '2' } })
assert.equal(selected.root.title, '一级')
assert.deepEqual(selected.ancestors.map(n => n.path), ['/nav/module', '/nav/group'])
assert.equal(firstDualLeaf(buildDualMenu(records)[0]).path, '/nav/module/nav/group/nav/item')
})