feat: MenuNav layer for the SummerCMS menu API
- typed client and useMenu/useMenuApi (SSR, menu:<code>:<locale> key, server and public bases, x-forwarded-for forwarded also on cached renders) - MenuNav and recursive MenuNavItem: WAI disclosure navigation, URL allowlist with a text fallback, rel on _blank, active link and trail, mobile toggle, Esc / focus-out / outside pointer / route change closing - menu tokens and base CSS, README - node tests (link rules, client, server-rendered NavItem) and a playground SSR smoke against a fixture API
This commit is contained in:
247
app/assets/css/menu-base.css
Normal file
247
app/assets/css/menu-base.css
Normal file
@@ -0,0 +1,247 @@
|
||||
/* MenuNav styles. Global, unscoped and token-driven, so an app restyles the
|
||||
menu through the tokens or its own rules. The 767px breakpoint is fixed
|
||||
here because custom properties cannot drive media queries. */
|
||||
|
||||
.menu-nav {
|
||||
font-family: var(--menu-font);
|
||||
font-size: var(--menu-font-size);
|
||||
line-height: var(--menu-line-height);
|
||||
color: var(--menu-color-text);
|
||||
}
|
||||
|
||||
.menu-nav__list,
|
||||
.menu-nav__submenu {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.menu-nav__list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--menu-space-2);
|
||||
}
|
||||
|
||||
.menu-nav__item {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.menu-nav__link,
|
||||
.menu-nav__text {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--menu-space-2);
|
||||
padding: var(--menu-space-2) var(--menu-space-3);
|
||||
border-radius: var(--menu-radius);
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
button.menu-nav__link,
|
||||
.menu-nav__subtoggle,
|
||||
.menu-nav__toggle {
|
||||
border: 0;
|
||||
background: none;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.menu-nav__link:hover,
|
||||
.menu-nav__subtoggle:hover {
|
||||
background: var(--menu-color-surface);
|
||||
}
|
||||
|
||||
.menu-nav__link--active {
|
||||
color: var(--menu-color-accent);
|
||||
text-decoration: underline;
|
||||
text-decoration-thickness: 2px;
|
||||
text-underline-offset: 0.35em;
|
||||
}
|
||||
|
||||
.menu-nav__item--trail > .menu-nav__link,
|
||||
.menu-nav__item--trail > .menu-nav__subtoggle {
|
||||
color: var(--menu-color-accent);
|
||||
}
|
||||
|
||||
.menu-nav__link:focus-visible,
|
||||
.menu-nav__subtoggle:focus-visible,
|
||||
.menu-nav__toggle:focus-visible {
|
||||
outline: 2px solid var(--menu-color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.menu-nav__subtoggle:not(.menu-nav__link) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: var(--menu-space-2);
|
||||
border-radius: var(--menu-radius);
|
||||
}
|
||||
|
||||
.menu-nav__chevron {
|
||||
width: 0.45rem;
|
||||
height: 0.45rem;
|
||||
border-right: 2px solid currentColor;
|
||||
border-bottom: 2px solid currentColor;
|
||||
transform: translateY(-2px) rotate(45deg);
|
||||
transition: transform 150ms ease;
|
||||
}
|
||||
|
||||
.menu-nav__item--open > .menu-nav__subtoggle .menu-nav__chevron {
|
||||
transform: translateY(1px) rotate(-135deg);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.menu-nav__chevron {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
.menu-nav__submenu {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.menu-nav__item--open > .menu-nav__submenu {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.menu-nav__submenu .menu-nav__link,
|
||||
.menu-nav__submenu .menu-nav__text {
|
||||
display: flex;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.menu-nav__divider {
|
||||
align-self: stretch;
|
||||
margin: var(--menu-space-1) 0;
|
||||
border-top: 1px solid var(--menu-color-border);
|
||||
}
|
||||
|
||||
.menu-nav__sr {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.menu-nav__toggle {
|
||||
display: none;
|
||||
position: relative;
|
||||
width: var(--menu-toggle-size);
|
||||
height: var(--menu-toggle-size);
|
||||
border: 1px solid var(--menu-color-border);
|
||||
border-radius: var(--menu-radius);
|
||||
background: var(--menu-color-bg);
|
||||
}
|
||||
|
||||
.menu-nav__toggle-bars,
|
||||
.menu-nav__toggle-bars::before,
|
||||
.menu-nav__toggle-bars::after {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
width: 1.25rem;
|
||||
height: 2px;
|
||||
margin-left: -0.625rem;
|
||||
background: var(--menu-color-text);
|
||||
content: '';
|
||||
}
|
||||
|
||||
.menu-nav__toggle-bars {
|
||||
top: 50%;
|
||||
}
|
||||
|
||||
.menu-nav__toggle-bars::before,
|
||||
.menu-nav__toggle-bars::after {
|
||||
left: 0;
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.menu-nav__toggle-bars::before {
|
||||
top: -6px;
|
||||
}
|
||||
|
||||
.menu-nav__toggle-bars::after {
|
||||
top: 6px;
|
||||
}
|
||||
|
||||
/* Desktop */
|
||||
@media (min-width: 768px) {
|
||||
.menu-nav__list > .menu-nav__divider {
|
||||
align-self: center;
|
||||
width: 1px;
|
||||
height: 1.25rem;
|
||||
margin: 0;
|
||||
border-top: 0;
|
||||
border-inline-start: 1px solid var(--menu-color-border);
|
||||
}
|
||||
|
||||
.menu-nav__item > .menu-nav__submenu {
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
inset-inline-start: 0;
|
||||
top: calc(100% + var(--menu-space-2));
|
||||
min-width: var(--menu-submenu-min-width);
|
||||
padding: var(--menu-space-2);
|
||||
background: var(--menu-color-bg);
|
||||
border: 1px solid var(--menu-color-border);
|
||||
border-radius: var(--menu-radius-panel);
|
||||
box-shadow: var(--menu-shadow);
|
||||
}
|
||||
|
||||
.menu-nav__submenu .menu-nav__item > .menu-nav__submenu {
|
||||
inset-inline-start: 100%;
|
||||
top: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Mobile */
|
||||
@media (max-width: 767px) {
|
||||
.menu-nav__toggle {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.menu-nav__list {
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
inset-inline: 0;
|
||||
top: 100%;
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: var(--menu-space-1);
|
||||
padding: var(--menu-space-2) var(--menu-space-3) var(--menu-space-3);
|
||||
background: var(--menu-color-bg);
|
||||
border-bottom: 1px solid var(--menu-color-border);
|
||||
box-shadow: var(--menu-shadow);
|
||||
}
|
||||
|
||||
.menu-nav--open .menu-nav__list {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.menu-nav__item > .menu-nav__link,
|
||||
.menu-nav__item > .menu-nav__text {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
button.menu-nav__link {
|
||||
width: 100%;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.menu-nav__submenu {
|
||||
flex-basis: 100%;
|
||||
padding-inline-start: var(--menu-space-3);
|
||||
}
|
||||
}
|
||||
33
app/assets/css/menu-tokens.css
Normal file
33
app/assets/css/menu-tokens.css
Normal file
@@ -0,0 +1,33 @@
|
||||
/* Menu design tokens. Every visual value of MenuNav comes from these. An app
|
||||
overrides any of them in its own CSS, e.g. on :root:root. */
|
||||
:root {
|
||||
/* Colour */
|
||||
--menu-color-text: #1f2328; /* links and text */
|
||||
--menu-color-muted: #59636e; /* secondary text */
|
||||
--menu-color-bg: #ffffff; /* submenu and mobile panels */
|
||||
--menu-color-surface: #f6f8fa; /* link hover background */
|
||||
--menu-color-border: #d1d9e0; /* panel borders, dividers */
|
||||
--menu-color-accent: #0969da; /* active link, focus ring */
|
||||
|
||||
/* Type */
|
||||
--menu-font: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
--menu-font-size: 1rem;
|
||||
--menu-line-height: 1.5;
|
||||
|
||||
/* Spacing scale */
|
||||
--menu-space-1: 0.25rem;
|
||||
--menu-space-2: 0.5rem;
|
||||
--menu-space-3: 1rem;
|
||||
--menu-space-4: 1.5rem;
|
||||
|
||||
/* Radii */
|
||||
--menu-radius: 4px; /* links */
|
||||
--menu-radius-panel: 8px; /* submenu panels */
|
||||
|
||||
/* Layout */
|
||||
--menu-submenu-min-width: 14rem;
|
||||
--menu-toggle-size: 2.75rem; /* 44px touch target */
|
||||
|
||||
/* Shadow */
|
||||
--menu-shadow: 0 8px 24px rgba(31, 35, 40, 0.12);
|
||||
}
|
||||
125
app/components/Menu/Nav.vue
Normal file
125
app/components/Menu/Nav.vue
Normal file
@@ -0,0 +1,125 @@
|
||||
<script setup lang="ts">
|
||||
// MenuNav: a menu of the menu plugin as a site navigation. Fetched during
|
||||
// SSR (useMenu), so the first paint has it. A missing menu (404), a failed
|
||||
// request or a menu without entries renders nothing, or the #fallback slot;
|
||||
// never an empty <nav>. Below 768px a 44x44 toggle opens the list as a
|
||||
// panel; Esc and every route change close it.
|
||||
import { computed, onBeforeUnmount, onMounted, ref, useId, watch } from 'vue'
|
||||
import type { MenuEntry } from '../../utils/types.ts'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** The menu code (GET /menus/{code}). */
|
||||
code: string
|
||||
/** ?locale= for the API; the API's default locale when unset. */
|
||||
locale?: string
|
||||
/** aria-label of the <nav>; the menu code when unset. */
|
||||
label?: string
|
||||
openLabel?: string
|
||||
closeLabel?: string
|
||||
/** Label of a submenu toggle next to a link; ":title" is the entry title. */
|
||||
submenuLabel?: string
|
||||
}>(),
|
||||
{
|
||||
locale: undefined,
|
||||
label: undefined,
|
||||
openLabel: 'Open menu',
|
||||
closeLabel: 'Close menu',
|
||||
submenuLabel: 'Show submenu: :title',
|
||||
},
|
||||
)
|
||||
|
||||
const slots = defineSlots<{
|
||||
item?(props: { entry: MenuEntry; depth: number; active: boolean }): unknown
|
||||
fallback?(): unknown
|
||||
}>()
|
||||
|
||||
const { data: menu, error } = await useMenu(
|
||||
() => props.code,
|
||||
{ locale: () => props.locale },
|
||||
)
|
||||
|
||||
const items = computed<MenuEntry[]>(() => (error.value ? [] : (menu.value?.items ?? [])))
|
||||
// Dividers alone are no menu.
|
||||
const visible = computed(() => items.value.some((entry) => entry.type !== 'divider'))
|
||||
|
||||
const route = useRoute()
|
||||
const host = useRequestURL().host
|
||||
const uid = useId()
|
||||
const listId = `${uid}-list`
|
||||
|
||||
const panelOpen = ref(false)
|
||||
const openIndex = ref<number | null>(null)
|
||||
const navEl = ref<HTMLElement | null>(null)
|
||||
const toggleEl = ref<HTMLButtonElement | null>(null)
|
||||
|
||||
watch(
|
||||
() => route.path,
|
||||
() => {
|
||||
panelOpen.value = false
|
||||
openIndex.value = null
|
||||
},
|
||||
)
|
||||
|
||||
function setOpen(index: number, value: boolean): void {
|
||||
if (value) openIndex.value = index
|
||||
else if (openIndex.value === index) openIndex.value = null
|
||||
}
|
||||
|
||||
// Esc that no open submenu took closes the mobile panel.
|
||||
function onEscape(): void {
|
||||
if (!panelOpen.value) return
|
||||
panelOpen.value = false
|
||||
toggleEl.value?.focus()
|
||||
}
|
||||
|
||||
// A pointer-down outside the nav closes its open submenus.
|
||||
function onPointerDown(event: PointerEvent): void {
|
||||
if (navEl.value && !navEl.value.contains(event.target as Node)) openIndex.value = null
|
||||
}
|
||||
|
||||
onMounted(() => document.addEventListener('pointerdown', onPointerDown))
|
||||
onBeforeUnmount(() => document.removeEventListener('pointerdown', onPointerDown))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav
|
||||
v-if="visible"
|
||||
ref="navEl"
|
||||
class="menu-nav"
|
||||
:class="[menu?.css_class, { 'menu-nav--open': panelOpen }]"
|
||||
:aria-label="label || code"
|
||||
@keydown.esc="onEscape"
|
||||
>
|
||||
<button
|
||||
ref="toggleEl"
|
||||
type="button"
|
||||
class="menu-nav__toggle"
|
||||
:aria-controls="listId"
|
||||
:aria-expanded="panelOpen ? 'true' : 'false'"
|
||||
@click="panelOpen = !panelOpen"
|
||||
>
|
||||
<span class="menu-nav__toggle-bars" aria-hidden="true" />
|
||||
<span class="menu-nav__sr">{{ panelOpen ? closeLabel : openLabel }}</span>
|
||||
</button>
|
||||
<ul :id="listId" class="menu-nav__list">
|
||||
<MenuNavItem
|
||||
v-for="(entry, i) in items"
|
||||
:key="entry.id ?? `generated-${i}`"
|
||||
:entry="entry"
|
||||
:depth="0"
|
||||
:id-base="`${uid}-${i}`"
|
||||
:open="openIndex === i"
|
||||
:route-path="route.path"
|
||||
:host="host"
|
||||
:submenu-label="submenuLabel"
|
||||
@update:open="(value: boolean) => setOpen(i, value)"
|
||||
>
|
||||
<template v-if="slots.item" #item="slotProps">
|
||||
<slot name="item" v-bind="slotProps" />
|
||||
</template>
|
||||
</MenuNavItem>
|
||||
</ul>
|
||||
</nav>
|
||||
<slot v-else name="fallback" />
|
||||
</template>
|
||||
189
app/components/Menu/NavItem.vue
Normal file
189
app/components/Menu/NavItem.vue
Normal file
@@ -0,0 +1,189 @@
|
||||
<script setup lang="ts">
|
||||
// One menu entry (MenuNavItem, recursive): a link, a disclosure toggle with
|
||||
// its submenu, plain text, or a divider. The WAI disclosure navigation
|
||||
// pattern: an entry with children and a URL keeps its link and gets a
|
||||
// sibling toggle button; an entry with children and no URL is one button.
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import type { MenuEntry } from '../../utils/types.ts'
|
||||
import { entryHref, fillTitle, inTrail, isActive, linkKind, linkRel } from '../../utils/menuLinks.ts'
|
||||
|
||||
const props = defineProps<{
|
||||
entry: MenuEntry
|
||||
depth: number
|
||||
/** Unique, SSR-stable id prefix of this entry (submenu ids). */
|
||||
idBase: string
|
||||
open: boolean
|
||||
routePath: string
|
||||
host: string
|
||||
submenuLabel: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:open': [value: boolean] }>()
|
||||
|
||||
defineSlots<{
|
||||
item?(props: { entry: MenuEntry; depth: number; active: boolean }): unknown
|
||||
}>()
|
||||
|
||||
const isDivider = computed(() => props.entry.type === 'divider')
|
||||
const children = computed(() => (isDivider.value ? [] : (props.entry.items ?? [])))
|
||||
const hasChildren = computed(() => children.value.length > 0)
|
||||
const href = computed(() => entryHref(props.entry))
|
||||
const kind = computed(() => linkKind(props.entry))
|
||||
const active = computed(() => isActive(props.entry, props.routePath, props.host))
|
||||
const trail = computed(() => !active.value && inTrail(props.entry, props.routePath, props.host))
|
||||
const target = computed(() => (props.entry.target === '_blank' ? '_blank' : undefined))
|
||||
const rel = computed(() => linkRel(props.entry.target))
|
||||
const submenuId = computed(() => `${props.idBase}-sub`)
|
||||
const linkClass = computed(() => ['menu-nav__link', props.entry.css_class, { 'menu-nav__link--active': active.value }])
|
||||
|
||||
const openChild = ref<number | null>(null)
|
||||
const itemEl = ref<HTMLElement | null>(null)
|
||||
const toggleEl = ref<HTMLButtonElement | null>(null)
|
||||
|
||||
// A closed submenu closes its own open submenus too.
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
if (!open) openChild.value = null
|
||||
},
|
||||
)
|
||||
|
||||
// Hover opens a submenu only for hover-capable pointers on the desktop
|
||||
// layout; a click on the toggle then pins it open.
|
||||
const HOVER_QUERY = '(hover: hover) and (min-width: 768px)'
|
||||
let hoverOpened = false
|
||||
|
||||
function canHover(): boolean {
|
||||
return typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia(HOVER_QUERY).matches
|
||||
}
|
||||
|
||||
function setOpen(value: boolean): void {
|
||||
if (!value) hoverOpened = false
|
||||
emit('update:open', value)
|
||||
}
|
||||
|
||||
function toggle(): void {
|
||||
if (hoverOpened) {
|
||||
hoverOpened = false
|
||||
return
|
||||
}
|
||||
setOpen(!props.open)
|
||||
}
|
||||
|
||||
function onEnter(): void {
|
||||
if (hasChildren.value && !props.open && canHover()) {
|
||||
hoverOpened = true
|
||||
emit('update:open', true)
|
||||
}
|
||||
}
|
||||
|
||||
function onLeave(): void {
|
||||
if (hoverOpened) setOpen(false)
|
||||
}
|
||||
|
||||
function onEscape(event: KeyboardEvent): void {
|
||||
if (!props.open || !hasChildren.value) return
|
||||
event.stopPropagation()
|
||||
setOpen(false)
|
||||
toggleEl.value?.focus()
|
||||
}
|
||||
|
||||
function onFocusOut(event: FocusEvent): void {
|
||||
if (!props.open) return
|
||||
const next = event.relatedTarget as Node | null
|
||||
if (!next || !itemEl.value?.contains(next)) setOpen(false)
|
||||
}
|
||||
|
||||
function setChild(index: number, value: boolean): void {
|
||||
if (value) openChild.value = index
|
||||
else if (openChild.value === index) openChild.value = null
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<li v-if="isDivider" class="menu-nav__divider" aria-hidden="true" />
|
||||
<li
|
||||
v-else
|
||||
ref="itemEl"
|
||||
class="menu-nav__item"
|
||||
:class="{
|
||||
'menu-nav__item--parent': hasChildren,
|
||||
'menu-nav__item--open': hasChildren && open,
|
||||
'menu-nav__item--trail': trail,
|
||||
}"
|
||||
:data-depth="depth"
|
||||
@mouseenter="onEnter"
|
||||
@mouseleave="onLeave"
|
||||
@focusout="onFocusOut"
|
||||
@keydown.esc="onEscape"
|
||||
>
|
||||
<button
|
||||
v-if="hasChildren && href === null"
|
||||
ref="toggleEl"
|
||||
type="button"
|
||||
class="menu-nav__link menu-nav__subtoggle"
|
||||
:class="entry.css_class"
|
||||
:aria-expanded="open ? 'true' : 'false'"
|
||||
:aria-controls="submenuId"
|
||||
@click="toggle"
|
||||
>
|
||||
<span class="menu-nav__label"><slot name="item" :entry="entry" :depth="depth" :active="active">{{ entry.title }}</slot></span>
|
||||
<span class="menu-nav__chevron" aria-hidden="true" />
|
||||
</button>
|
||||
<NuxtLink
|
||||
v-else-if="kind === 'router'"
|
||||
:to="href!"
|
||||
:class="linkClass"
|
||||
:target="target"
|
||||
:rel="rel"
|
||||
:aria-current="active ? 'page' : undefined"
|
||||
>
|
||||
<slot name="item" :entry="entry" :depth="depth" :active="active">{{ entry.title }}</slot>
|
||||
</NuxtLink>
|
||||
<a
|
||||
v-else-if="kind === 'anchor'"
|
||||
:href="href!"
|
||||
:class="linkClass"
|
||||
:target="target"
|
||||
:rel="rel"
|
||||
:aria-current="active ? 'page' : undefined"
|
||||
>
|
||||
<slot name="item" :entry="entry" :depth="depth" :active="active">{{ entry.title }}</slot>
|
||||
</a>
|
||||
<span v-else class="menu-nav__text" :class="entry.css_class">
|
||||
<slot name="item" :entry="entry" :depth="depth" :active="active">{{ entry.title }}</slot>
|
||||
</span>
|
||||
|
||||
<button
|
||||
v-if="hasChildren && href !== null"
|
||||
ref="toggleEl"
|
||||
type="button"
|
||||
class="menu-nav__subtoggle"
|
||||
:aria-expanded="open ? 'true' : 'false'"
|
||||
:aria-controls="submenuId"
|
||||
@click="toggle"
|
||||
>
|
||||
<span class="menu-nav__chevron" aria-hidden="true" />
|
||||
<span class="menu-nav__sr">{{ fillTitle(submenuLabel, entry.title) }}</span>
|
||||
</button>
|
||||
|
||||
<ul v-if="hasChildren" :id="submenuId" class="menu-nav__submenu">
|
||||
<MenuNavItem
|
||||
v-for="(child, i) in children"
|
||||
:key="child.id ?? `generated-${i}`"
|
||||
:entry="child"
|
||||
:depth="depth + 1"
|
||||
:id-base="`${idBase}-${i}`"
|
||||
:open="openChild === i"
|
||||
:route-path="routePath"
|
||||
:host="host"
|
||||
:submenu-label="submenuLabel"
|
||||
@update:open="(value: boolean) => setChild(i, value)"
|
||||
>
|
||||
<template v-if="$slots.item" #item="slotProps">
|
||||
<slot name="item" v-bind="slotProps" />
|
||||
</template>
|
||||
</MenuNavItem>
|
||||
</ul>
|
||||
</li>
|
||||
</template>
|
||||
20
app/composables/useMenu.ts
Normal file
20
app/composables/useMenu.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
// A menu by code, fetched during SSR through useAsyncData with the key
|
||||
// menu:<code>:<locale>, so the first paint has the menu and client
|
||||
// navigation reuses the result. data is null for a missing (404) menu;
|
||||
// error is set when the API failed.
|
||||
|
||||
import type { MaybeRefOrGetter } from 'vue'
|
||||
import type { Menu } from '../utils/types.ts'
|
||||
|
||||
export interface UseMenuOptions {
|
||||
/** ?locale= for the API; the API's default locale when empty. */
|
||||
locale?: MaybeRefOrGetter<string | undefined>
|
||||
}
|
||||
|
||||
export function useMenu(code: MaybeRefOrGetter<string>, opts: UseMenuOptions = {}) {
|
||||
const api = useMenuApi()
|
||||
const key = computed(() => `menu:${toValue(code)}:${toValue(opts.locale) ?? ''}`)
|
||||
return useAsyncData<Menu | null>(key, () => api.getMenu(toValue(code), toValue(opts.locale) || undefined), {
|
||||
default: () => null,
|
||||
})
|
||||
}
|
||||
28
app/composables/useMenuApi.ts
Normal file
28
app/composables/useMenuApi.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
// The menu API client. On the server it calls the internal base
|
||||
// (runtimeConfig.menu.apiBase) and forwards the visitor's x-forwarded-for,
|
||||
// plus the address of the peer that reached Nuxt, so the Go rate limiter
|
||||
// keeps one bucket per visitor, also on route-cached renders. In the browser
|
||||
// it calls the same-origin public base. The base is always runtime config,
|
||||
// never request input.
|
||||
|
||||
import { createMenuClient, type MenuClient, type MenuFetcher } from '../utils/client.ts'
|
||||
|
||||
export function useMenuApi(): MenuClient {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
if (import.meta.server) {
|
||||
const base = (config.menu as { apiBase: string }).apiBase
|
||||
const event = useRequestEvent()
|
||||
const recorded = event?.context.menuForwardedFor as string | undefined
|
||||
const incoming = useRequestHeaders(['x-forwarded-for'])['x-forwarded-for']
|
||||
const peer = event?.node?.req?.socket?.remoteAddress
|
||||
const forwarded = recorded || [incoming, peer].filter((v): v is string => typeof v === 'string' && v !== '').join(', ')
|
||||
const headers: Record<string, string> = forwarded ? { 'x-forwarded-for': forwarded } : {}
|
||||
const fetcher: MenuFetcher = (path, query) => $fetch(path, { baseURL: base, query, headers })
|
||||
return createMenuClient(fetcher)
|
||||
}
|
||||
|
||||
const base = (config.public.menu as { apiBase: string }).apiBase
|
||||
const fetcher: MenuFetcher = (path, query) => $fetch(path, { baseURL: base, query })
|
||||
return createMenuClient(fetcher)
|
||||
}
|
||||
43
app/utils/client.ts
Normal file
43
app/utils/client.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
// Typed client for the anonymous menu API. It wraps an injected fetcher, so
|
||||
// the Nuxt composable decides the base URL and headers and `node --test` can
|
||||
// drive it with a stub.
|
||||
|
||||
import type { Menu, MenuEnvelope } from './types.ts'
|
||||
|
||||
/** Issues one GET for `path` (e.g. "/menus/main") with `query`, resolving the parsed JSON. */
|
||||
export type MenuFetcher = (path: string, query?: Record<string, string>) => Promise<unknown>
|
||||
|
||||
/** True for a fetch error that carries HTTP status 404 (ofetch, h3 or plain). */
|
||||
export function isNotFound(err: unknown): boolean {
|
||||
if (!err || typeof err !== 'object') return false
|
||||
const e = err as { status?: unknown; statusCode?: unknown; response?: { status?: unknown } }
|
||||
return e.status === 404 || e.statusCode === 404 || e.response?.status === 404
|
||||
}
|
||||
|
||||
/** The API path of a menu: /menus/<code>, the code URL-encoded. */
|
||||
export function menuPath(code: string): string {
|
||||
return `/menus/${encodeURIComponent(code)}`
|
||||
}
|
||||
|
||||
export interface MenuClient {
|
||||
/** The menu with `code`, or null when the API answers 404 (unknown or inactive). */
|
||||
getMenu(code: string, locale?: string): Promise<Menu | null>
|
||||
}
|
||||
|
||||
export function createMenuClient(fetcher: MenuFetcher): MenuClient {
|
||||
return {
|
||||
async getMenu(code, locale) {
|
||||
const query = locale ? { locale } : undefined
|
||||
let res: MenuEnvelope
|
||||
try {
|
||||
res = (await (query ? fetcher(menuPath(code), query) : fetcher(menuPath(code)))) as MenuEnvelope
|
||||
} catch (err) {
|
||||
if (isNotFound(err)) return null
|
||||
throw err
|
||||
}
|
||||
const menu = res?.data
|
||||
if (!menu || typeof menu !== 'object') return null
|
||||
return { ...menu, items: Array.isArray(menu.items) ? menu.items : [] }
|
||||
},
|
||||
}
|
||||
}
|
||||
103
app/utils/menuLinks.ts
Normal file
103
app/utils/menuLinks.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
// How a menu entry renders as a link: the URL allowlist, the link kind, rel
|
||||
// for new-window links, and active / trail matching against the current
|
||||
// route. Pure functions, so `node --test` covers them without Nuxt.
|
||||
|
||||
import type { MenuEntry } from './types.ts'
|
||||
|
||||
/** A NuxtLink (same-site path), a plain anchor, or text with no href. */
|
||||
export type LinkKind = 'router' | 'anchor' | 'text'
|
||||
|
||||
const SCHEMES = ['http://', 'https://', 'mailto:', 'tel:']
|
||||
|
||||
/**
|
||||
* True for a URL the layer renders as a link: http, https, mailto, tel, a
|
||||
* leading slash or a leading #. Control characters and surrounding spaces
|
||||
* refuse it (the server applies the same allowlist; this is the second
|
||||
* line, Pitfall 15).
|
||||
*/
|
||||
export function isAllowedUrl(url: string | null | undefined): url is string {
|
||||
if (typeof url !== 'string' || url === '') return false
|
||||
if (url.trim() !== url) return false
|
||||
for (let i = 0; i < url.length; i++) {
|
||||
const c = url.charCodeAt(i)
|
||||
if (c < 0x20 || c === 0x7f) return false
|
||||
}
|
||||
if (url[0] === '/' || url[0] === '#') return true
|
||||
const lower = url.toLowerCase()
|
||||
return SCHEMES.some((s) => lower.startsWith(s))
|
||||
}
|
||||
|
||||
/**
|
||||
* The navigable URL of an entry, or null. A bare "#" is a placeholder (a
|
||||
* dropdown parent in many Winter menus), so it counts as no URL.
|
||||
*/
|
||||
export function entryHref(entry: Pick<MenuEntry, 'url'>): string | null {
|
||||
const url = entry.url
|
||||
if (!isAllowedUrl(url) || url === '#') return null
|
||||
return url
|
||||
}
|
||||
|
||||
/** A path on this site: one leading slash, not // or /\ (protocol-relative). */
|
||||
function isSitePath(url: string): boolean {
|
||||
return url[0] === '/' && url[1] !== '/' && url[1] !== '\\'
|
||||
}
|
||||
|
||||
/** router for a site path, anchor for absolute, mailto, tel and #fragment URLs, text otherwise. */
|
||||
export function linkKind(entry: Pick<MenuEntry, 'url'>): LinkKind {
|
||||
const href = entryHref(entry)
|
||||
if (href === null) return 'text'
|
||||
return isSitePath(href) ? 'router' : 'anchor'
|
||||
}
|
||||
|
||||
/** rel for an entry's link: "noopener noreferrer" with target _blank. */
|
||||
export function linkRel(target: string | null | undefined): string | undefined {
|
||||
return target === '_blank' ? 'noopener noreferrer' : undefined
|
||||
}
|
||||
|
||||
/** A path for comparison: query and hash dropped, decoded, trailing slash removed except on "/". */
|
||||
export function normalizePath(path: string): string {
|
||||
let p = path.split('#', 1)[0]!.split('?', 1)[0]!
|
||||
try {
|
||||
p = decodeURI(p)
|
||||
} catch {
|
||||
// keep the raw path when it is not valid percent-encoding
|
||||
}
|
||||
if (p === '') p = '/'
|
||||
while (p.length > 1 && p.endsWith('/')) p = p.slice(0, -1)
|
||||
return p
|
||||
}
|
||||
|
||||
/**
|
||||
* The site path an entry points at, for active matching: a site path as
|
||||
* is, an http(s) URL only when its host equals `host`; null otherwise.
|
||||
*/
|
||||
export function entryPath(entry: Pick<MenuEntry, 'url'>, host: string): string | null {
|
||||
const href = entryHref(entry)
|
||||
if (href === null) return null
|
||||
if (isSitePath(href)) return normalizePath(href)
|
||||
if (!/^https?:\/\//i.test(href)) return null
|
||||
let parsed: URL
|
||||
try {
|
||||
parsed = new URL(href)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (host === '' || parsed.host.toLowerCase() !== host.toLowerCase()) return null
|
||||
return normalizePath(parsed.pathname)
|
||||
}
|
||||
|
||||
/** True when the entry links to the current route path. */
|
||||
export function isActive(entry: Pick<MenuEntry, 'url'>, routePath: string, host: string): boolean {
|
||||
const p = entryPath(entry, host)
|
||||
return p !== null && p === normalizePath(routePath)
|
||||
}
|
||||
|
||||
/** True when a descendant of the entry (not the entry itself) is active. */
|
||||
export function inTrail(entry: Pick<MenuEntry, 'items'>, routePath: string, host: string): boolean {
|
||||
return (entry.items ?? []).some((child) => isActive(child, routePath, host) || inTrail(child, routePath, host))
|
||||
}
|
||||
|
||||
/** Fills ":title" in a label template. */
|
||||
export function fillTitle(template: string, title: string): string {
|
||||
return template.split(':title').join(title)
|
||||
}
|
||||
28
app/utils/types.ts
Normal file
28
app/utils/types.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
// The response shape of GET /_menu/api/v1/menus/{code}?locale=xx (the menu
|
||||
// plugin's public API). Generated children of a list type carry id null and
|
||||
// the parent's registry type.
|
||||
|
||||
export interface MenuEntry {
|
||||
id: number | null
|
||||
title: string
|
||||
/** "url", "divider" or a registry type key such as "all-journal-categories". */
|
||||
type: string
|
||||
/** Null for dividers and for a URL the server refused (scheme allowlist). */
|
||||
url: string | null
|
||||
target: '_self' | '_blank' | null
|
||||
css_class: string | null
|
||||
icon: string | null
|
||||
code: string | null
|
||||
items: MenuEntry[]
|
||||
}
|
||||
|
||||
export interface Menu {
|
||||
code: string
|
||||
name: string
|
||||
css_class: string | null
|
||||
items: MenuEntry[]
|
||||
}
|
||||
|
||||
export interface MenuEnvelope {
|
||||
data: Menu
|
||||
}
|
||||
Reference in New Issue
Block a user