fix(admin): 折叠菜单内逐级选页并记住桌面偏好
This commit is contained in:
@@ -19,6 +19,9 @@ HOME = "自录转化统计"
|
||||
DETAIL = "运营明细"
|
||||
HIDDEN = "仅后台可见明细"
|
||||
HIDDEN_ROOT = "隐藏目录"
|
||||
NAMES = "业务报表"
|
||||
SIMILAR = ("全院财务结算与跨部门对账月报表", "全院财务退款与跨部门对账月报表")
|
||||
DUPLICATE = "回访明细"
|
||||
TITLE = ".el-sub-menu__title"
|
||||
|
||||
|
||||
@@ -39,6 +42,10 @@ def setup_menu(fixture):
|
||||
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))
|
||||
roots.append(menu(440, NAMES, "reports", children=[
|
||||
menu(i, name, f"r{i}", component="stats/self_input/account_cost")
|
||||
for i, name in enumerate([*SIMILAR, DUPLICATE, DUPLICATE], start=441)
|
||||
]))
|
||||
# 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")
|
||||
|
||||
@@ -175,6 +182,45 @@ def layout(page, rail, panel=None, *, expected_width=None):
|
||||
"rail": rb["width"], "panel": pb["width"] if pb else 0, "main_x": main["x"]}.items()}
|
||||
|
||||
|
||||
def compact_layout(page, rail, panel, fold, baseline=None):
|
||||
expect(rail).to_be_visible()
|
||||
expect(fold).to_have_attribute("aria-expanded", "false")
|
||||
expect(panel).to_be_hidden()
|
||||
metrics = layout(page, rail)
|
||||
assert abs(metrics["rail"] - 64) <= 1, ("compact rail", metrics)
|
||||
assert abs(metrics["main_x"] - 64) <= 2, ("main should start next to the rail", metrics)
|
||||
if baseline is not None:
|
||||
assert metrics == baseline, ("drilling or resizing moved the content", metrics, baseline)
|
||||
|
||||
# Measuring width alone would pass even with an absolutely positioned flyout over the page.
|
||||
expect(page.locator(".el-menu--popup:visible, .el-popover:visible, .el-drawer:visible")).to_have_count(0)
|
||||
assert rail.evaluate("""nav => {
|
||||
const b = nav.getBoundingClientRect();
|
||||
return [...nav.querySelectorAll('a,button')].every(item => {
|
||||
const r = item.getBoundingClientRect();
|
||||
return !r.width || (r.left >= b.left - 1 && r.right <= b.right + 1);
|
||||
});
|
||||
}"""), "menu controls extend outside the compact rail"
|
||||
assert page.locator("main").evaluate("""main => {
|
||||
const b = main.getBoundingClientRect();
|
||||
return [4, 64, 160].every(dx => [8, 64, 144].every(dy =>
|
||||
main.contains(document.elementFromPoint(b.left + dx, b.top + dy))));
|
||||
}"""), "sidebar flyout or backdrop intercepts the content"
|
||||
return metrics
|
||||
|
||||
|
||||
def compact_label(row):
|
||||
# A full title can be shortened on screen, but it may not collapse to a single glyph
|
||||
# or become tooltip-only. The full title remains the control's accessible name.
|
||||
label = row.locator(".compact-label")
|
||||
expect(label).to_be_visible()
|
||||
text = label.inner_text().strip()
|
||||
assert len(text) > 1 and row.get_attribute("title"), ("missing visible or full label", text)
|
||||
box, ink = row.bounding_box(), label.bounding_box()
|
||||
assert box["x"] - 1 <= ink["x"] and ink["x"] + ink["width"] <= box["x"] + box["width"] + 1
|
||||
return text
|
||||
|
||||
|
||||
def clipped(row, selector, label):
|
||||
el = row.locator(selector)
|
||||
expect(row).to_have_accessible_name(label)
|
||||
@@ -207,6 +253,7 @@ def check(page, fixture, out):
|
||||
expect(page.locator("html")).to_have_attribute("data-admin-ui", "v2")
|
||||
|
||||
rail = page.get_by_role("navigation", name="一级菜单", exact=True)
|
||||
compact = 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)
|
||||
@@ -322,26 +369,123 @@ def check(page, fixture, out):
|
||||
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"]
|
||||
report["collapsed"] = compact_layout(page, compact, panel, fold)
|
||||
def unchanged():
|
||||
return compact_layout(page, compact, panel, fold, report["collapsed"])
|
||||
|
||||
group = lambda name: compact.get_by_role("button", name=name, exact=True)
|
||||
entry = lambda name: compact.get_by_role("link", name=name, exact=True)
|
||||
back = group("返回上一级")
|
||||
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])
|
||||
unchanged()
|
||||
expect(back).to_be_hidden()
|
||||
expect(group(HIDDEN_ROOT)).to_have_count(0)
|
||||
report["collapsed_centers"] = {"logo": center(compact, compact.locator(".logo img"), "brand image")}
|
||||
for name, row in ((ROOT, group(ROOT)), (OTHER, group(OTHER)), (TOP_LEAF, entry(TOP_LEAF))):
|
||||
compact_label(row)
|
||||
expect(row).to_have_attribute("title", name)
|
||||
report["collapsed_centers"][name] = center(compact, row.locator(".compact-icon svg"), name)
|
||||
screenshot(page, out, "collapsed")
|
||||
other.press("Enter")
|
||||
expect(fold).to_have_attribute("aria-expanded", "true")
|
||||
|
||||
# Similar and identical sibling names must be distinguishable without hovering.
|
||||
group(NAMES).click()
|
||||
assert compact_label(entry(SIMILAR[0])) != compact_label(entry(SIMILAR[1]))
|
||||
twins = compact.get_by_role("link", name=re.compile("^" + DUPLICATE))
|
||||
expect(twins).to_have_count(2)
|
||||
assert twins.nth(0).inner_text() != twins.nth(1).inner_text()
|
||||
assert twins.nth(0).get_attribute("aria-label") != twins.nth(1).get_attribute("aria-label")
|
||||
route_at(page, h_path, h_query)
|
||||
unchanged()
|
||||
back.click()
|
||||
expect(group(NAMES)).to_be_focused()
|
||||
|
||||
# Browsing directories (including one with only one permitted child) never chooses a route.
|
||||
group(OTHER).hover()
|
||||
page.wait_for_timeout(650) # Exercise the legacy Element Plus hover-to-open delay.
|
||||
unchanged()
|
||||
expect(entry(DETAIL)).to_be_hidden()
|
||||
group(OTHER).press("Enter")
|
||||
expect(entry(DETAIL)).to_be_focused()
|
||||
expect(entry(HIDDEN)).to_have_count(0)
|
||||
route_at(page, h_path, h_query)
|
||||
unchanged()
|
||||
back.press("Space")
|
||||
expect(group(OTHER)).to_be_focused()
|
||||
route_at(page, h_path, h_query)
|
||||
unchanged()
|
||||
|
||||
group(ROOT).click()
|
||||
expect(group(NESTED)).to_be_focused()
|
||||
expect(entry(LEAF)).to_be_hidden()
|
||||
route_at(page, h_path, h_query)
|
||||
unchanged()
|
||||
group(NESTED).press("Space")
|
||||
expect(entry(HOME)).to_be_focused()
|
||||
compact_label(entry(LEAF))
|
||||
expect(group(ROOT)).to_be_hidden()
|
||||
route_at(page, h_path, h_query)
|
||||
unchanged()
|
||||
screenshot(page, out, "collapsed-third-level")
|
||||
page.keyboard.press("Tab")
|
||||
expect(entry(LEAF)).to_be_focused()
|
||||
page.keyboard.press("Enter")
|
||||
route_at(page, c_path, c_query)
|
||||
expect(cost_page).to_be_visible()
|
||||
expect(entry(LEAF)).to_have_attribute("aria-current", "page")
|
||||
unchanged()
|
||||
back.click()
|
||||
expect(group(NESTED)).to_be_focused()
|
||||
back.press("Enter")
|
||||
expect(group(ROOT)).to_be_focused()
|
||||
expect(back).to_be_hidden()
|
||||
route_at(page, c_path, c_query)
|
||||
unchanged()
|
||||
|
||||
entry(TOP_LEAF).click()
|
||||
route_at(page, "solo", {})
|
||||
expect(entry(TOP_LEAF)).to_have_attribute("aria-current", "page")
|
||||
unchanged()
|
||||
group(OTHER).click()
|
||||
route_at(page, "solo", {})
|
||||
entry(DETAIL).click()
|
||||
route_at(page, d_path, d_query)
|
||||
selected(other, detail)
|
||||
expect(entry(DETAIL)).to_have_attribute("aria-current", "page")
|
||||
unchanged()
|
||||
page.reload()
|
||||
route_at(page, d_path, d_query)
|
||||
expect(cost_page).to_be_visible()
|
||||
unchanged()
|
||||
|
||||
# The mobile drawer starts closed, performs real link navigation, then closes. Neither
|
||||
# opening it nor choosing a link changes the desktop preference saved by the fold button.
|
||||
page.set_viewport_size({"width": 390, "height": 844})
|
||||
expect(compact).to_be_hidden()
|
||||
expect(rail).to_be_hidden()
|
||||
expect(panel).to_be_hidden()
|
||||
mobile = page.locator(".el-drawer:visible .side")
|
||||
expect(mobile).to_be_hidden()
|
||||
fold.click()
|
||||
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=LEAF, exact=True).click()
|
||||
expect(mobile).to_be_hidden()
|
||||
route_at(page, c_path, c_query)
|
||||
expect(cost_page).to_be_visible()
|
||||
page.set_viewport_size({"width": 1440, "height": 960})
|
||||
unchanged()
|
||||
|
||||
# Only the explicit header control restores the wide, fixed second column.
|
||||
fold.press("Enter")
|
||||
expect(fold).to_have_attribute("aria-expanded", "true")
|
||||
expect(compact).to_be_hidden()
|
||||
selected(root, cost)
|
||||
route_at(page, c_path, c_query)
|
||||
assert layout(page, rail, panel, expected_width=230) == report["expanded"]
|
||||
page.reload()
|
||||
selected(root, cost)
|
||||
expect(fold).to_have_attribute("aria-expanded", "true")
|
||||
assert layout(page, rail, panel, expected_width=230) == report["expanded"]
|
||||
|
||||
drawer = settings(page)
|
||||
@@ -363,23 +507,24 @@ def check(page, fixture, out):
|
||||
assert all(max(rgb) < 145 for rgb in report["dark_rgb"]), report["dark_rgb"]
|
||||
screenshot(page, out, "dark-180")
|
||||
|
||||
# Resize with the drawer *open*: Element Plus emits update:modelValue(false)
|
||||
# after its leave animation, by which time the desktop sidebar is visible again.
|
||||
page.set_viewport_size({"width": 390, "height": 844})
|
||||
expect(rail).to_be_hidden()
|
||||
expect(panel).to_be_hidden()
|
||||
expect(mobile).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=LEAF, exact=True).click()
|
||||
page.set_viewport_size({"width": 1440, "height": 960})
|
||||
expect(mobile).to_be_hidden()
|
||||
route_at(page, c_path, c_query)
|
||||
expect(cost_page).to_be_visible()
|
||||
settle(page.locator(".layout-default"))
|
||||
expect(fold).to_have_attribute("aria-expanded", "true")
|
||||
selected(root, home)
|
||||
assert layout(page, rail, panel, expected_width=180) == report["dark_180px"]
|
||||
|
||||
# Switch through the user's settings, not injected CSS/localStorage.
|
||||
page.set_viewport_size({"width": 1440, "height": 960})
|
||||
expect(rail).to_be_visible()
|
||||
cost.click()
|
||||
route_at(page, c_path, c_query)
|
||||
drawer = settings(page)
|
||||
drawer.get_by_text("经典", exact=True).click()
|
||||
close_settings(page, drawer)
|
||||
|
||||
+5
-15
@@ -32,23 +32,13 @@ const elConfig = {
|
||||
}
|
||||
const { width } = useWindowSize()
|
||||
watch(
|
||||
width,
|
||||
(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 &&
|
||||
[width, () => settings.adminUi],
|
||||
([value, ui], [previous, previousUi]) => {
|
||||
// Don't reset transient v2 navigation within the same desktop breakpoint.
|
||||
if (ui === 'v2' && ui === previousUi && 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)
|
||||
} else {
|
||||
appStore.setMobile(true)
|
||||
appStore.toggleCollapsed(true)
|
||||
}
|
||||
if (value < ScreenEnum.MD) {
|
||||
appStore.toggleCollapsed(true)
|
||||
}
|
||||
appStore.syncSidebarViewport(value, ui)
|
||||
},
|
||||
{
|
||||
immediate: true
|
||||
|
||||
@@ -13,8 +13,10 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import useAppStore from '@/stores/modules/app'
|
||||
import useSettingStore from '@/stores/modules/setting'
|
||||
|
||||
const appStore = useAppStore()
|
||||
const settings = useSettingStore()
|
||||
const isCollapsed = computed(() => appStore.isCollapsed)
|
||||
const toggleCollapsed = () => appStore.toggleCollapsed()
|
||||
const toggleCollapsed = () => appStore.toggleHeaderCollapsed(settings.adminUi)
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { DualNode } from './dual-model'
|
||||
|
||||
/** Resolve against today's authorized tree, not node objects saved before a role change. */
|
||||
export function compactTrail(roots: DualNode[], keys: string[]) {
|
||||
const trail: DualNode[] = []
|
||||
let level = roots
|
||||
for (const key of keys) {
|
||||
const directory = level.find(node => node.key === key && node.children.length)
|
||||
if (!directory) break
|
||||
trail.push(directory)
|
||||
level = directory.children
|
||||
}
|
||||
return trail
|
||||
}
|
||||
|
||||
/** Keep recognizable beginnings and endings. Never hide the only distinguishing text. */
|
||||
export function compactEntries(nodes: DualNode[]) {
|
||||
const titles = nodes.map(node => node.title.trim() || (node.children.length ? '目录' : '页面'))
|
||||
const shortened = titles.map(title => {
|
||||
const chars = Array.from(title)
|
||||
return chars.length <= 8 ? title : chars.slice(0, 4).join('') + '…' + chars.slice(-3).join('')
|
||||
})
|
||||
const counts = new Map<string, number>()
|
||||
const names = new Map<string, Set<string>>()
|
||||
titles.forEach((title, i) => {
|
||||
counts.set(title, (counts.get(title) || 0) + 1)
|
||||
const bucket = names.get(shortened[i]) || new Set<string>()
|
||||
bucket.add(title)
|
||||
names.set(shortened[i], bucket)
|
||||
})
|
||||
const seen = new Map<string, number>()
|
||||
return nodes.map((node, i) => {
|
||||
const title = titles[i]
|
||||
const ordinal = (seen.get(title) || 0) + 1
|
||||
seen.set(title, ordinal)
|
||||
const count = counts.get(title)!
|
||||
const badge = count > 1 ? `${ordinal}/${count}` : ''
|
||||
return {
|
||||
node,
|
||||
// Full names wrap if shortening would conflate two different menu entries.
|
||||
label: names.get(shortened[i])!.size > 1 ? title : shortened[i],
|
||||
name: badge ? `${title}(${badge})` : title,
|
||||
badge
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
<template>
|
||||
<div ref="rail" class="compact-rail" :data-depth="trail.length">
|
||||
<div v-if="directory" class="compact-context">
|
||||
<button type="button" class="compact-back" aria-label="返回上一级" title="返回上一级" @click="back">
|
||||
<icon name="el-icon-ArrowLeft" :size="14" aria-hidden="true" />
|
||||
返回
|
||||
</button>
|
||||
<div class="compact-heading" :title="directory.title">{{ directory.title }}</div>
|
||||
</div>
|
||||
<ul ref="list" class="compact-list" :aria-label="directory ? directory.title + '的子菜单' : '一级菜单'">
|
||||
<li v-for="{ node, name, label, badge } in entries" :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="compact-node"
|
||||
:class="{ 'is-active': node.key === leafKey || ancestorKeys.includes(node.key) }"
|
||||
:data-key="node.key"
|
||||
:aria-current="node.key === leafKey ? 'page' : undefined"
|
||||
:aria-label="name"
|
||||
:title="name"
|
||||
@click="node.children.length && enter(node)"
|
||||
>
|
||||
<span class="compact-icon" aria-hidden="true">
|
||||
<icon :name="node.icon || (node.children.length ? 'el-icon-Folder' : 'el-icon-Document')"
|
||||
:size="18" />
|
||||
</span>
|
||||
<span class="compact-label">{{ label }}</span>
|
||||
<span v-if="badge" class="compact-badge" aria-hidden="true">{{ badge }}</span>
|
||||
<icon v-if="node.children.length" class="compact-next" name="el-icon-ArrowRight"
|
||||
:size="10" aria-hidden="true" />
|
||||
</component>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
|
||||
import AppLink from '@/components/app-link/index.vue'
|
||||
import { compactEntries, compactTrail } from './compact-model'
|
||||
import type { DualNode } from './dual-model'
|
||||
|
||||
const props = defineProps<{
|
||||
roots: DualNode[]
|
||||
ancestorKeys: string[]
|
||||
leafKey?: string
|
||||
routeKey: string
|
||||
}>()
|
||||
|
||||
// Manual folding mounts a fresh root list; no sidebar/global store writes on drill-down.
|
||||
const keys = ref<string[]>([])
|
||||
const trail = computed(() => compactTrail(props.roots, keys.value))
|
||||
const directory = computed(() => trail.value[trail.value.length - 1])
|
||||
const entries = computed(() => compactEntries(directory.value?.children ?? props.roots))
|
||||
const rail = ref<HTMLElement>()
|
||||
const list = ref<HTMLElement>()
|
||||
|
||||
function focusItem(key?: string) {
|
||||
const items = Array.from(list.value?.querySelectorAll<HTMLElement>('.compact-node') ?? [])
|
||||
const item = items.find(el => el.getAttribute('data-key') === key) || items[0]
|
||||
item?.focus()
|
||||
}
|
||||
function enter(node: DualNode) {
|
||||
keys.value = [...keys.value, node.key]
|
||||
void nextTick(() => focusItem())
|
||||
}
|
||||
function back() {
|
||||
const returningTo = directory.value?.key
|
||||
keys.value = keys.value.slice(0, -1)
|
||||
void nextTick(() => focusItem(returningTo))
|
||||
}
|
||||
|
||||
// While browsing a sublevel, tab/history navigation may select a different branch.
|
||||
// A rail at its top level remains an overview. Neither action should move focus out of the page.
|
||||
watch(() => props.routeKey, () => {
|
||||
if (keys.value.length) keys.value = [...props.ancestorKeys]
|
||||
})
|
||||
watch(() => props.roots, () => {
|
||||
if (trail.value.length !== keys.value.length) keys.value = trail.value.map(node => node.key)
|
||||
})
|
||||
// If a permission update or a route change removes the focused row, restore focus locally.
|
||||
watch(entries, () => {
|
||||
const owner = rail.value?.ownerDocument
|
||||
if (!owner?.activeElement || !rail.value?.contains(owner.activeElement)) return
|
||||
void nextTick(() => {
|
||||
if (owner.activeElement === owner.body) focusItem(props.leafKey)
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.compact-rail {
|
||||
display: flex;
|
||||
flex: 1 1 0;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
.compact-context {
|
||||
flex: none;
|
||||
margin: 0 4px 4px;
|
||||
padding-bottom: 6px;
|
||||
border-bottom: 1px solid var(--zyt-card-border);
|
||||
text-align: center;
|
||||
}
|
||||
.compact-back, .compact-node {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
background: transparent;
|
||||
color: var(--zyt-nav-text);
|
||||
cursor: pointer;
|
||||
}
|
||||
.compact-back { min-height: 32px; gap: 2px; font-size: 12px; }
|
||||
.compact-heading {
|
||||
overflow: hidden;
|
||||
color: var(--zyt-nav-title);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.compact-list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: hidden auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-width: none;
|
||||
margin: 0;
|
||||
padding: 4px 4px 12px;
|
||||
list-style: none;
|
||||
}
|
||||
.compact-list::-webkit-scrollbar { display: none; }
|
||||
.compact-list li + li { margin-top: 3px; }
|
||||
.compact-node {
|
||||
position: relative;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
min-height: 52px;
|
||||
padding: 6px 2px;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
}
|
||||
.compact-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
color: var(--zyt-nav-icon);
|
||||
}
|
||||
.compact-next {
|
||||
position: absolute;
|
||||
top: 9px;
|
||||
right: 4px;
|
||||
color: var(--zyt-nav-icon);
|
||||
}
|
||||
.compact-label {
|
||||
max-width: 100%;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: 12px;
|
||||
line-height: 15px;
|
||||
}
|
||||
.compact-badge { font-size: 11px; line-height: 13px; }
|
||||
.compact-back:hover, .compact-node:hover { background: var(--zyt-nav-hover); }
|
||||
.compact-node.is-active {
|
||||
background: var(--zyt-nav-active);
|
||||
color: var(--zyt-nav-selected);
|
||||
}
|
||||
.compact-node.is-active .compact-icon { color: inherit; }
|
||||
.compact-node:focus-visible, .compact-back:focus-visible {
|
||||
outline: 2px solid var(--zyt-nav-selected);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="dual-sidebar" :class="{ 'dual-sidebar--compact': app.isCollapsed }"
|
||||
@keydown.space="activateLinkWithSpace">
|
||||
<nav class="dual-primary" aria-label="一级菜单">
|
||||
<nav class="dual-primary" :aria-label="app.isCollapsed ? '折叠菜单' : '一级菜单'">
|
||||
<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"
|
||||
@@ -13,7 +13,10 @@
|
||||
<circle cx="19" cy="6.5" r="2" fill="currentColor"/>
|
||||
</svg>
|
||||
</div>
|
||||
<ul ref="rootList" class="dual-roots">
|
||||
<compact-rail v-if="app.isCollapsed"
|
||||
:roots="roots" :ancestor-keys="ancestorKeys" :leaf-key="selection.leaf?.key"
|
||||
:route-key="route.fullPath" />
|
||||
<ul v-else ref="rootList" class="dual-roots">
|
||||
<li v-for="root in roots" :key="root.key">
|
||||
<component
|
||||
:is="root.children.length ? 'button' : AppLink"
|
||||
@@ -22,7 +25,7 @@
|
||||
: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-expanded="root.children.length ? activeRoot?.key === root.key : undefined"
|
||||
:aria-current="!root.children.length && selection.leaf?.key === root.key ? 'page' : undefined"
|
||||
:aria-label="root.title"
|
||||
:title="root.title"
|
||||
@@ -32,7 +35,7 @@
|
||||
<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>
|
||||
<span class="dual-root-label">{{ root.title }}</span>
|
||||
</component>
|
||||
</li>
|
||||
</ul>
|
||||
@@ -61,6 +64,7 @@ import AppLink from '@/components/app-link/index.vue'
|
||||
import useAppStore from '@/stores/modules/app'
|
||||
import useSettingStore from '@/stores/modules/setting'
|
||||
|
||||
import CompactRail from './compact-rail.vue'
|
||||
import DualBranch from './dual-branch.vue'
|
||||
import { buildDualMenu, findDualSelection, firstDualLeaf, type DualNode } from './dual-model'
|
||||
|
||||
@@ -105,7 +109,6 @@ function chooseRoot(node: DualNode) {
|
||||
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)
|
||||
@@ -178,7 +181,6 @@ function activateLinkWithSpace(event: KeyboardEvent) {
|
||||
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);
|
||||
|
||||
@@ -27,7 +27,8 @@ const showMenuDrawer = computed({
|
||||
return !appStore.isCollapsed && isMobile.value
|
||||
},
|
||||
set(value) {
|
||||
appStore.toggleCollapsed(!value)
|
||||
// A closing mobile drawer may emit after the desktop sidebar is restored.
|
||||
if (isMobile.value) appStore.toggleCollapsed(!value)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -2,6 +2,12 @@ import { defineStore } from 'pinia'
|
||||
|
||||
import { getConfig } from '@/api/app'
|
||||
import configs from '@/config'
|
||||
import { ScreenEnum } from '@/enums/appEnums'
|
||||
import cache from '@/utils/cache'
|
||||
|
||||
const DESKTOP_COLLAPSE_KEY = 'admin_ui_v2_desktop_collapsed'
|
||||
const nativeSidebar = !['live-readonly', 'local-preview'].includes(import.meta.env.MODE)
|
||||
type AdminUi = 'v2' | 'legacy'
|
||||
|
||||
interface AppSate {
|
||||
config: Record<string, any>
|
||||
@@ -9,17 +15,20 @@ interface AppSate {
|
||||
configFetchAttempted: boolean
|
||||
isMobile: boolean
|
||||
isCollapsed: boolean
|
||||
desktopV2Collapsed: boolean | null
|
||||
isRouteShow: boolean
|
||||
}
|
||||
|
||||
const useAppStore = defineStore({
|
||||
id: 'app',
|
||||
state: (): AppSate => {
|
||||
const saved = nativeSidebar ? cache.get(DESKTOP_COLLAPSE_KEY) : null
|
||||
return {
|
||||
config: {},
|
||||
configFetchAttempted: false,
|
||||
isMobile: true,
|
||||
isCollapsed: false,
|
||||
desktopV2Collapsed: typeof saved === 'boolean' ? saved : null,
|
||||
isRouteShow: true
|
||||
}
|
||||
},
|
||||
@@ -59,6 +68,19 @@ const useAppStore = defineStore({
|
||||
setMobile(value: boolean) {
|
||||
this.isMobile = value
|
||||
},
|
||||
syncSidebarViewport(width: number, ui: AdminUi) {
|
||||
this.setMobile(width <= ScreenEnum.SM)
|
||||
const preferDesktop = nativeSidebar && ui === 'v2' && !this.isMobile
|
||||
this.isCollapsed = (preferDesktop ? this.desktopV2Collapsed : null) ?? (width < ScreenEnum.MD)
|
||||
},
|
||||
toggleHeaderCollapsed(ui: AdminUi) {
|
||||
this.toggleCollapsed()
|
||||
// Drawer/route/layout updates are transient; only this button records the desktop choice.
|
||||
if (nativeSidebar && ui === 'v2' && !this.isMobile) {
|
||||
this.desktopV2Collapsed = this.isCollapsed
|
||||
cache.set(DESKTOP_COLLAPSE_KEY, this.isCollapsed)
|
||||
}
|
||||
},
|
||||
toggleCollapsed(toggle?: boolean) {
|
||||
this.isCollapsed = toggle ?? !this.isCollapsed
|
||||
},
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
// Real Vue component, router, and event handlers; the host tree is in memory (not a browser/layout engine).
|
||||
const assert = require('node:assert/strict')
|
||||
const test = require('node:test')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const { build } = require('esbuild')
|
||||
const { parse, compileScript } = require('@vue/compiler-sfc')
|
||||
const { createRenderer, reactive, h, nextTick, markRaw } = require('vue')
|
||||
const { createRouter, createMemoryHistory } = require('vue-router')
|
||||
const admin = process.env.ZYT_TEST_ADMIN_SOURCE || path.resolve(__dirname, '..')
|
||||
const treeDir = path.join(admin, 'src/layout/default/components/sidebar')
|
||||
async function components(doc) {
|
||||
const mod = { exports: {} }
|
||||
const { outputFiles } = await build({
|
||||
absWorkingDir: admin, stdin: {contents: `export { default as Dual } from '${treeDir}/dual-sidebar.vue'
|
||||
export { default as Link } from '@/components/app-link/index.vue'`,resolveDir:admin},
|
||||
alias: {'@':path.join(admin,'src')}, bundle:true, write:false, platform:'node',format:'cjs',
|
||||
external:['vue','vue-router','@vue/shared','lodash'],define:{'import.meta.env.MODE':'"live-native"'},
|
||||
plugins:[{name:'mounted-sfc',setup(b){
|
||||
b.onResolve({filter:/^@\/stores\/modules\/(app|setting)$/},a=>({path:a.path.split('/').pop(),namespace:'store'}))
|
||||
b.onLoad({filter:/.*/,namespace:'store'},a=>({contents:`import { inject } from 'vue'; export default ()=>inject('test-${a.path}')`}))
|
||||
b.onLoad({filter:/\.vue$/},async a=>{
|
||||
const s=fs.readFileSync(a.path,'utf8'), {descriptor,errors}=parse(s,{filename:a.path})
|
||||
assert.deepEqual(errors,[])
|
||||
let output=compileScript(descriptor,{id:path.basename(a.path),inlineTemplate:true}).content
|
||||
if(a.path.endsWith('app-link/index.vue'))output="import {computed} from 'vue';\n"+output
|
||||
return {contents:output,loader:'ts',resolveDir:path.dirname(a.path)}
|
||||
})
|
||||
}}]
|
||||
})
|
||||
new Function('require','module','exports','document',outputFiles[0].text)(require,mod,mod.exports,doc)
|
||||
return mod.exports
|
||||
}
|
||||
function memoryHost() {
|
||||
let focus
|
||||
class Node {
|
||||
constructor(type,text=''){this.type=type;this.text=text;this.props={};this.children=[];this.parent=null;this.scrollTop=0;markRaw(this)}
|
||||
nodes(){return this.children.flatMap(n=>[n,...n.nodes()])}
|
||||
get childrenText(){return this.text+this.children.map(n=>n.childrenText).join('')}
|
||||
matches(s){
|
||||
s=s.trim()
|
||||
if (s.startsWith('.'))return String(this.props.class||'').split(/\s+/).includes(s.slice(1))
|
||||
if (s.startsWith('[')){const m=s.match(/^\[([\w-]+)(?:=["']?([^"'\]]+)["']?)?\]$/);return !!m && this.props[m[1]]!=null && (m[2]===undefined || String(this.props[m[1]])===m[2])}
|
||||
return this.type===s
|
||||
}
|
||||
querySelectorAll(selector){return this.nodes().filter(n=>selector.split(',').some(s=>n.matches(s)))}
|
||||
querySelector(s){return this.querySelectorAll(s)[0]??null}
|
||||
get dataset(){return {key:this.props['data-key']}}
|
||||
getAttribute(k){return this.props[k]??null}
|
||||
getBoundingClientRect(){return {top:0,bottom:40,left:0,right:64,width:64,height:40}}
|
||||
contains(n){return n===this||this.nodes().includes(n)}
|
||||
focus(){focus=this}
|
||||
scrollIntoView(){}
|
||||
}
|
||||
function detach(el){if(el.parent)el.parent.children.splice(el.parent.children.indexOf(el),1);el.parent=null}
|
||||
const renderer=createRenderer({
|
||||
createElement:t=>new Node(t),createText:t=>new Node('#text',t),createComment:t=>new Node('#comment',t),
|
||||
parentNode:e=>e.parent,nextSibling:e=>e.parent?.children[e.parent.children.indexOf(e)+1]??null,
|
||||
setText:(e,t)=>e.text=t,setElementText:(e,t)=>{e.children=[];e.text=t},
|
||||
patchProp:(e,k,old,v)=>{e.props[k]=v},setScopeId:()=>{},
|
||||
remove:detach,insert:(e,parent,anchor)=>{detach(e);e.parent=parent;const at=parent.children.indexOf(anchor);parent.children.splice(at<0?parent.children.length:at,0,e)},
|
||||
insertStaticContent:(s,p,a)=>{const e=new Node('#static',s);e.parent=p;const i=p.children.indexOf(a);p.children.splice(i<0?p.children.length:i,0,e);return [e,e]}
|
||||
})
|
||||
return {renderer,root:new Node('root'),getFocus:()=>focus}
|
||||
}
|
||||
async function settle(){await nextTick();await new Promise(r=>setImmediate(r));await nextTick()}
|
||||
function click(el){
|
||||
assert.ok(el)
|
||||
const e={type:'click',currentTarget:el,target:el,button:0,preventDefault(){this.defaultPrevented=true}, defaultPrevented:false}
|
||||
for (const fn of [].concat(el.props.onClick || [])) fn(e)
|
||||
}
|
||||
test('compact groups browse in place and links keep their query; only explicit expansion restores a column',async()=>{
|
||||
const {renderer,root,getFocus} = memoryHost()
|
||||
const {Dual,Link} = await components({body:root,get activeElement(){return getFocus() || root}})
|
||||
const page=(path,title,query)=>({path,meta:{title,type:'C',query}})
|
||||
const group=(path,title,children)=>({path,meta:{title,type:'M'},children})
|
||||
const routes=reactive([group('/stats','数据统计',[group('reports','报表',[page('one','报表一'),page('two','报表二','?source=menu')]),page('summary','汇总')]),page('/solo','首页'),group('/links','帮助',[page('https://example.invalid/help','使用说明')])])
|
||||
const appStore=reactive({isCollapsed:false,config:{},toggleCollapsed(v){this.isCollapsed=v??!this.isCollapsed}})
|
||||
const settings=reactive({showLogo:false,sideWidth:230,isUniqueOpened:true})
|
||||
const router=createRouter({history:createMemoryHistory(),routes:['/solo','/stats/reports/one','/stats/reports/two','/stats/summary'].map(path=>({path,component:{render:()=>null}}))})
|
||||
await router.push('/solo');await router.isReady()
|
||||
const app=renderer.createApp({render:()=>h(Dual,{routes})})
|
||||
app.provide('test-app',appStore);app.provide('test-setting',settings)
|
||||
app.component('app-link',Link);app.component('icon',{render:()=>h('svg')});app.component('image-contain',{render:()=>h('img')});app.use(router)
|
||||
app.mount(root)
|
||||
const controls=()=>root.nodes().filter(n=>n.type==='button'||n.type==='a')
|
||||
const named=(name)=>controls().find(n=>n.props['aria-label']===name || n.props.title===name || n.childrenText.trim()===name)
|
||||
const fixedPane=()=>root.nodes().some(n=>n.type==='nav'&&n.props['aria-label']==='二级菜单')
|
||||
appStore.toggleCollapsed(true);await settle()
|
||||
click(named('数据统计'));await settle()
|
||||
assert.deepEqual({collapsed:appStore.isCollapsed,path:router.currentRoute.value.fullPath,pane:fixedPane()},
|
||||
{collapsed:true,path:'/solo',pane:false},'a compact directory should neither expand nor navigate')
|
||||
assert.equal(getFocus(),named('报表'),'focus enters the first child')
|
||||
click(named('报表'));await settle();assert.ok(named('报表一'));assert.ok(named('报表二'))
|
||||
click(named('报表二'));await settle()
|
||||
assert.equal(router.currentRoute.value.fullPath,'/stats/reports/two?source=menu')
|
||||
assert.ok(named('报表一'),'sibling remains reachable');assert.equal(appStore.isCollapsed,true)
|
||||
click(named('返回上一级'));await settle();assert.equal(getFocus(),named('报表'),'back restores focus to the directory');assert.ok(named('汇总'));assert.ok(named('报表'));assert.equal(fixedPane(),false)
|
||||
click(named('返回上一级'));await settle();assert.ok(named('首页'));assert.ok(named('数据统计'))
|
||||
assert.equal(router.currentRoute.value.fullPath,'/stats/reports/two?source=menu','back is menu-only')
|
||||
click(named('帮助'));await settle()
|
||||
assert.equal(router.currentRoute.value.fullPath,'/stats/reports/two?source=menu')
|
||||
assert.equal(named('使用说明').props.href,'https://example.invalid/help')
|
||||
// Change the permission-projected tree in place; no orphaned group or link survives.
|
||||
routes.pop();await settle();assert.ok(!named('使用说明'));assert.ok(!named('返回上一级'))
|
||||
click(named('首页'));await settle();assert.equal(router.currentRoute.value.path,'/solo')
|
||||
assert.equal(appStore.isCollapsed,true)
|
||||
click(named('数据统计'));await settle();click(named('报表'));await settle()
|
||||
await router.push('/stats/summary');await settle();assert.ok(named('汇总'));assert.ok(!named('报表二'))
|
||||
assert.equal(appStore.isCollapsed,true)
|
||||
appStore.toggleCollapsed(false);await settle();assert.equal(fixedPane(),true)
|
||||
app.unmount()
|
||||
})
|
||||
@@ -0,0 +1,104 @@
|
||||
// Exercise the real layout actions and cache envelope without a browser or API calls.
|
||||
const assert = require('node:assert/strict')
|
||||
const path = require('node:path')
|
||||
const test = require('node:test')
|
||||
const { buildSync } = require('esbuild')
|
||||
const { createPinia } = require('pinia')
|
||||
|
||||
const admin = path.resolve(__dirname, '..')
|
||||
const key = 'like_admin_admin_ui_v2_desktop_collapsed'
|
||||
function storeFactory(mode = 'live-native') {
|
||||
const { outputFiles } = buildSync({
|
||||
absWorkingDir: admin, entryPoints: ['src/stores/modules/app.ts'],
|
||||
alias: { '@': path.join(admin, 'src') }, external: ['pinia', '*/api/app', '*/src/config'],
|
||||
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)(
|
||||
name => name === 'pinia' ? require('pinia') : {}, module, module.exports)
|
||||
return () => module.exports.default(createPinia())
|
||||
}
|
||||
function setup(t, entries = []) {
|
||||
const values = new Map(entries), writes = []
|
||||
global.window = { localStorage: {
|
||||
getItem: k => values.get(k) ?? null,
|
||||
setItem(k, v) { writes.push(k); values.set(k, v) }
|
||||
} }
|
||||
t.after(() => { delete global.window })
|
||||
return { values, writes }
|
||||
}
|
||||
|
||||
test('no saved choice: uses the existing mobile and narrow desktop breakpoints without writing', t => {
|
||||
const { writes } = setup(t)
|
||||
const app = storeFactory()()
|
||||
for (const [width, mobile, collapsed] of [[640,true,true], [641,false,true], [767,false,true], [768,false,false]]) {
|
||||
app.syncSidebarViewport(width, 'v2')
|
||||
assert.equal(app.isMobile, mobile)
|
||||
assert.equal(app.isCollapsed, collapsed)
|
||||
}
|
||||
assert.deepEqual(writes, [])
|
||||
})
|
||||
|
||||
test('only the desktop v2 button writes; both choices survive refresh, resize and mobile/legacy transitions', t => {
|
||||
const { values, writes } = setup(t)
|
||||
const fresh = storeFactory()
|
||||
const app = fresh()
|
||||
app.syncSidebarViewport(1280, 'v2')
|
||||
app.toggleHeaderCollapsed('v2')
|
||||
assert.equal(app.isCollapsed, true)
|
||||
assert.equal(JSON.parse(values.get(key)).value, true)
|
||||
app.syncSidebarViewport(1280, 'legacy')
|
||||
assert.equal(app.isCollapsed, false)
|
||||
app.toggleHeaderCollapsed('legacy')
|
||||
app.syncSidebarViewport(390, 'v2')
|
||||
app.toggleHeaderCollapsed('v2') // opens the drawer
|
||||
assert.equal(app.isCollapsed, false)
|
||||
app.toggleCollapsed(true) // route selection / drawer dismissal
|
||||
app.syncSidebarViewport(1024, 'v2')
|
||||
assert.equal(app.isCollapsed, true)
|
||||
const reloaded = fresh()
|
||||
reloaded.syncSidebarViewport(1024, 'v2')
|
||||
assert.equal(reloaded.isCollapsed, true)
|
||||
reloaded.toggleHeaderCollapsed('v2')
|
||||
assert.equal(JSON.parse(values.get(key)).value, false)
|
||||
reloaded.syncSidebarViewport(700, 'v2')
|
||||
assert.equal(reloaded.isCollapsed, false)
|
||||
reloaded.syncSidebarViewport(390, 'v2')
|
||||
assert.equal(reloaded.isCollapsed, true)
|
||||
reloaded.syncSidebarViewport(700, 'v2')
|
||||
assert.equal(reloaded.isCollapsed, false)
|
||||
const narrow = fresh()
|
||||
narrow.syncSidebarViewport(700, 'v2')
|
||||
assert.equal(narrow.isCollapsed, false)
|
||||
assert.deepEqual(writes, [key, key])
|
||||
})
|
||||
|
||||
test('fixture and read-only clients neither apply nor overwrite the native preference', t => {
|
||||
const { writes } = setup(t, [[key, '{"expire":"","value":true}']])
|
||||
for (const mode of ['local-preview', 'live-readonly']) {
|
||||
const app = storeFactory(mode)()
|
||||
app.syncSidebarViewport(1280, 'v2')
|
||||
assert.equal(app.isCollapsed, false)
|
||||
app.toggleHeaderCollapsed('v2')
|
||||
assert.equal(app.isCollapsed, true)
|
||||
}
|
||||
assert.deepEqual(writes, [])
|
||||
})
|
||||
|
||||
test('a malformed or inaccessible preference falls back to layout; blocked writes still work in memory', t => {
|
||||
setup(t, [[key, '{"value":"false"}']])
|
||||
const fresh = storeFactory('production')
|
||||
const app = fresh()
|
||||
app.syncSidebarViewport(1024, 'v2')
|
||||
assert.equal(app.isCollapsed, false)
|
||||
Object.defineProperty(window, 'localStorage', { get() { throw Error('storage unavailable') } })
|
||||
app.toggleHeaderCollapsed('v2')
|
||||
assert.equal(app.isCollapsed, true)
|
||||
app.syncSidebarViewport(390, 'v2')
|
||||
app.syncSidebarViewport(1024, 'v2')
|
||||
assert.equal(app.isCollapsed, true)
|
||||
const reloaded = fresh()
|
||||
reloaded.syncSidebarViewport(1024, 'v2')
|
||||
assert.equal(reloaded.isCollapsed, false)
|
||||
})
|
||||
Reference in New Issue
Block a user