From d8a16b07782a1b4f25f7cdb52ea3129a9c9d5ab3 Mon Sep 17 00:00:00 2001 From: long <452591453@qq.com> Date: Tue, 1 Dec 2026 19:39:25 +0800 Subject: [PATCH] =?UTF-8?q?feat(admin):=20=E4=BB=A5=E5=9B=BA=E5=AE=9A?= =?UTF-8?q?=E5=8F=8C=E5=88=97=E6=9B=BF=E4=BB=A3=E6=A1=8C=E9=9D=A2=E4=BA=8C?= =?UTF-8?q?=E7=BA=A7=E6=82=AC=E6=B5=AE=E8=8F=9C=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- admin/live-native/browser_contract.py | 29 +- admin/live-native/browser_sidebar.py | 296 +++++++++++++----- admin/live-native/browser_stats_visual.py | 5 +- admin/live-native/browser_tabs.py | 7 +- admin/src/App.vue | 14 +- .../components/sidebar/dual-branch.vue | 118 +++++++ .../default/components/sidebar/dual-model.ts | 154 +++++++++ .../components/sidebar/dual-sidebar.vue | 222 +++++++++++++ .../default/components/sidebar/side.vue | 45 +-- admin/src/stores/modules/multipleTabs.ts | 5 +- admin/tests/dual-menu-model.test.cjs | 104 ++++++ docs/plans/admin-ui-iteration-2026-12-01.md | 7 + 12 files changed, 888 insertions(+), 118 deletions(-) create mode 100644 admin/src/layout/default/components/sidebar/dual-branch.vue create mode 100644 admin/src/layout/default/components/sidebar/dual-model.ts create mode 100644 admin/src/layout/default/components/sidebar/dual-sidebar.vue create mode 100644 admin/tests/dual-menu-model.test.cjs diff --git a/admin/live-native/browser_contract.py b/admin/live-native/browser_contract.py index dba44a8b8..b58c8a294 100644 --- a/admin/live-native/browser_contract.py +++ b/admin/live-native/browser_contract.py @@ -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() diff --git a/admin/live-native/browser_sidebar.py b/admin/live-native/browser_sidebar.py index a105c6545..2d79f1a02 100644 --- a/admin/live-native/browser_sidebar.py +++ b/admin/live-native/browser_sidebar.py @@ -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 diff --git a/admin/live-native/browser_stats_visual.py b/admin/live-native/browser_stats_visual.py index 3e1f8f561..93648dfb5 100644 --- a/admin/live-native/browser_stats_visual.py +++ b/admin/live-native/browser_stats_visual.py @@ -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 diff --git a/admin/live-native/browser_tabs.py b/admin/live-native/browser_tabs.py index a9fd727ea..a0362f3ff 100644 --- a/admin/live-native/browser_tabs.py +++ b/admin/live-native/browser_tabs.py @@ -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): diff --git a/admin/src/App.vue b/admin/src/App.vue index b151f1186..a4ee8644b 100755 --- a/admin/src/App.vue +++ b/admin/src/App.vue @@ -1,17 +1,18 @@ + + diff --git a/admin/src/layout/default/components/sidebar/dual-model.ts b/admin/src/layout/default/components/sidebar/dual-model.ts new file mode 100644 index 000000000..abe49247d --- /dev/null +++ b/admin/src/layout/default/components/sidebar/dual-model.ts @@ -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() + 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 +} diff --git a/admin/src/layout/default/components/sidebar/dual-sidebar.vue b/admin/src/layout/default/components/sidebar/dual-sidebar.vue new file mode 100644 index 000000000..f99c99eb6 --- /dev/null +++ b/admin/src/layout/default/components/sidebar/dual-sidebar.vue @@ -0,0 +1,222 @@ + + + + + diff --git a/admin/src/layout/default/components/sidebar/side.vue b/admin/src/layout/default/components/sidebar/side.vue index 41bc9bf0a..4954e4b34 100755 --- a/admin/src/layout/default/components/sidebar/side.vue +++ b/admin/src/layout/default/components/sidebar/side.vue @@ -1,23 +1,26 @@ @@ -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() diff --git a/admin/src/stores/modules/multipleTabs.ts b/admin/src/stores/modules/multipleTabs.ts index 6ce2f53bd..10c2825e3 100755 --- a/admin/src/stores/modules/multipleTabs.ts +++ b/admin/src/stores/modules/multipleTabs.ts @@ -33,7 +33,10 @@ const getHasTabIndex = (fullPath: string, tabList: TabItem[]) => { /** 同一菜单页可能因 query、重定向等产生不同 fullPath,用 name + 解析后的 path 去重 */ const getTabMergeKey = (item: Pick) => { 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) => { diff --git a/admin/tests/dual-menu-model.test.cjs b/admin/tests/dual-menu-model.test.cjs new file mode 100644 index 000000000..8b6ee7b37 --- /dev/null +++ b/admin/tests/dual-menu-model.test.cjs @@ -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') +}) diff --git a/docs/plans/admin-ui-iteration-2026-12-01.md b/docs/plans/admin-ui-iteration-2026-12-01.md index 977aa74b1..06b6d977a 100644 --- a/docs/plans/admin-ui-iteration-2026-12-01.md +++ b/docs/plans/admin-ui-iteration-2026-12-01.md @@ -29,3 +29,10 @@ - 卡片沿用上游默认的主题表面和细边框。在 390px 宽度,每行从 1 张变 2 张,明细起点由距页面顶部 2008px 缩短至 951px;长金额换行显示,它不会推宽页面。暗色卡片实测为 RGB(22,22,24),指标文字对比度 7.97:1,数值 14.13:1。 - 对加载、真实零、缺失值、查询失败分别呈现。日期乱序实验中,最后选择的月份、明细、财务可见性一致;编辑/删除操作保持原权限判断。原生页面的 20 项离线检查通过,覆盖筛选参数、自定义日期、空结果、错误重试、长金额和单项权限;导航、标签、登录四组合回归通过。切换经典/新版的独立检查通过。 - **本轮复审收口:** 提出的侧栏问题及本轮三个批次全部通过。保留其余业务页原样,不把统计样板未经验证地推广全站。未来如继续扩展,优先为“账户消耗录入”单独建立加载、金额、权限及窄屏基线,再决定哪些样式适合复用;不要以修改通用表格或表单样式代替逐页验收。 + +### V4:用固定双列取代桌面二级悬浮菜单 + +- 依据 [Art Design Pro 双列导航](https://github.com/Daymychen/art-design-pro/blob/f3aaf58eec1a0e988f162352c33862327a484f95/src/components/core/layouts/art-menus/art-sidebar-menu/index.vue#L8-L115),新版桌面一级常驻,二级参与布局,三级在二级栏内展开。点一级分组进入首个可用站内页面;只有外链的分组先显示选项,一级叶项不产生空栏。手机与经典界面沿用原菜单。 +- 输入仍是当前账号的菜单树。刷新、前进/后退及切换标签时按实际路径、查询和激活项同步;不把隐藏目录转成入口。修正目录首页末尾斜线造成的重复工作标签。 +- 本地无界面 Chrome:默认两栏 80px + 230px,内容起点 x=311;收起后 64px,Logo 与图标中心 x=32,移开鼠标不弹菜单。通过窄二级栏、长标题、键盘进三级、手机抽屉、经典版、登录、原有查询和路由回归。独立构建副本还原后,布局与升级前相同。 +- 已知独立项:既有预约类型夹具和处方跟踪测试共五项失败,在本轮之前的 Git 副本也可复现;不作为本版菜单通过或失败的依据。没有改动相关业务页、鉴权或数据库。