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:
78
tests/client.test.ts
Normal file
78
tests/client.test.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
// The menu client against a fake fetcher: the URL built from base, code and
|
||||
// locale, the envelope unwrapped, 404 as null. No network.
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { createMenuClient, isNotFound, menuPath } from '../app/utils/client.ts'
|
||||
|
||||
type Call = { path: string; query?: Record<string, string> }
|
||||
|
||||
function fakeFetcher(answer: (path: string) => unknown) {
|
||||
const calls: Call[] = []
|
||||
const fetcher = async (path: string, query?: Record<string, string>) => {
|
||||
calls.push(query === undefined ? { path } : { path, query })
|
||||
return answer(path)
|
||||
}
|
||||
return { fetcher, calls }
|
||||
}
|
||||
|
||||
const MENU = {
|
||||
data: {
|
||||
code: 'main',
|
||||
name: 'Main',
|
||||
css_class: null,
|
||||
items: [{ id: 1, title: 'Home', type: 'url', url: '/', target: null, css_class: null, icon: null, code: null, items: [] }],
|
||||
},
|
||||
}
|
||||
|
||||
test('menuPath encodes the code', () => {
|
||||
assert.equal(menuPath('main'), '/menus/main')
|
||||
assert.equal(menuPath('a b/c'), '/menus/a%20b%2Fc')
|
||||
})
|
||||
|
||||
test('getMenu calls /menus/<code> and passes locale only when set', async () => {
|
||||
const { fetcher, calls } = fakeFetcher(() => MENU)
|
||||
const client = createMenuClient(fetcher)
|
||||
const menu = await client.getMenu('main')
|
||||
assert.equal(menu?.code, 'main')
|
||||
assert.equal(menu?.items.length, 1)
|
||||
await client.getMenu('main', 'en')
|
||||
assert.deepEqual(calls, [{ path: '/menus/main' }, { path: '/menus/main', query: { locale: 'en' } }])
|
||||
})
|
||||
|
||||
test('the fetcher base plus the path is the API URL', async () => {
|
||||
const urls: string[] = []
|
||||
const base = 'http://127.0.0.1:8096/_menu/api/v1'
|
||||
const client = createMenuClient(async (path, query) => {
|
||||
const u = new URL(base + path)
|
||||
for (const [k, v] of Object.entries(query ?? {})) u.searchParams.set(k, v)
|
||||
urls.push(u.toString())
|
||||
return MENU
|
||||
})
|
||||
await client.getMenu('main-menu', 'pl')
|
||||
assert.deepEqual(urls, ['http://127.0.0.1:8096/_menu/api/v1/menus/main-menu?locale=pl'])
|
||||
})
|
||||
|
||||
test('a 404 resolves to null; other errors are thrown', async () => {
|
||||
const notFound = createMenuClient(async () => {
|
||||
throw Object.assign(new Error('Not Found'), { statusCode: 404 })
|
||||
})
|
||||
assert.equal(await notFound.getMenu('nope'), null)
|
||||
const failing = createMenuClient(async () => {
|
||||
throw Object.assign(new Error('boom'), { status: 500 })
|
||||
})
|
||||
await assert.rejects(failing.getMenu('main'), /boom/)
|
||||
})
|
||||
|
||||
test('a body without data is null; missing items become an empty list', async () => {
|
||||
assert.equal(await createMenuClient(async () => ({})).getMenu('x'), null)
|
||||
const menu = await createMenuClient(async () => ({ data: { code: 'x', name: 'X', css_class: null } })).getMenu('x')
|
||||
assert.deepEqual(menu?.items, [])
|
||||
})
|
||||
|
||||
test('isNotFound reads status, statusCode and response.status', () => {
|
||||
assert.equal(isNotFound({ status: 404 }), true)
|
||||
assert.equal(isNotFound({ statusCode: 404 }), true)
|
||||
assert.equal(isNotFound({ response: { status: 404 } }), true)
|
||||
assert.equal(isNotFound({ status: 500 }), false)
|
||||
assert.equal(isNotFound(null), false)
|
||||
})
|
||||
137
tests/menuLinks.test.ts
Normal file
137
tests/menuLinks.test.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
// Link rules of the menu: the URL allowlist (javascript: and data: never get
|
||||
// an href), rel on new-window links, and active / trail matching. The last
|
||||
// tests compile Menu/NavItem.vue and render it on the server, so the rules
|
||||
// are proven on the markup too. No network, no Nuxt.
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { renderNavItem } from './render.ts'
|
||||
import {
|
||||
entryHref,
|
||||
entryPath,
|
||||
fillTitle,
|
||||
inTrail,
|
||||
isActive,
|
||||
isAllowedUrl,
|
||||
linkKind,
|
||||
linkRel,
|
||||
normalizePath,
|
||||
} from '../app/utils/menuLinks.ts'
|
||||
import type { MenuEntry } from '../app/utils/types.ts'
|
||||
|
||||
function entry(url: string | null, extra: Partial<MenuEntry> = {}): MenuEntry {
|
||||
return { id: 1, title: 'T', type: 'url', url, target: null, css_class: null, icon: null, code: null, items: [], ...extra }
|
||||
}
|
||||
|
||||
test('the allowlist takes http, https, mailto, tel, / and #', () => {
|
||||
for (const url of ['http://a.test/', 'HTTPS://a.test', 'mailto:a@b.test', 'tel:+48123', '/blog', '#faq', '//cdn.test/x']) {
|
||||
assert.equal(isAllowedUrl(url), true, url)
|
||||
}
|
||||
for (const url of [
|
||||
'javascript:alert(1)',
|
||||
'JavaScript:alert(1)',
|
||||
'data:text/html,<b>x</b>',
|
||||
'vbscript:x',
|
||||
'blog',
|
||||
'rodzaje/reishi',
|
||||
' /blog',
|
||||
'/blog\n',
|
||||
'\tjavascript:alert(1)',
|
||||
'',
|
||||
null,
|
||||
]) {
|
||||
assert.equal(isAllowedUrl(url), false, String(url))
|
||||
}
|
||||
})
|
||||
|
||||
test('javascript: and data: URLs render as text with no href', () => {
|
||||
for (const url of ['javascript:alert(1)', 'data:text/html;base64,PHNjcmlwdD4=']) {
|
||||
assert.equal(entryHref(entry(url)), null)
|
||||
assert.equal(linkKind(entry(url)), 'text')
|
||||
}
|
||||
})
|
||||
|
||||
test('link kinds: router for site paths, anchor for absolute, mailto, tel and fragments', () => {
|
||||
assert.equal(linkKind(entry('/blog')), 'router')
|
||||
assert.equal(linkKind(entry('https://a.test/x')), 'anchor')
|
||||
assert.equal(linkKind(entry('mailto:a@b.test')), 'anchor')
|
||||
assert.equal(linkKind(entry('tel:+48123')), 'anchor')
|
||||
assert.equal(linkKind(entry('#faq')), 'anchor')
|
||||
assert.equal(linkKind(entry('//cdn.test/x')), 'anchor')
|
||||
assert.equal(linkKind(entry('/\\evil.test')), 'anchor')
|
||||
// A bare "#" (a dropdown placeholder) and null are no link.
|
||||
assert.equal(linkKind(entry('#')), 'text')
|
||||
assert.equal(linkKind(entry(null)), 'text')
|
||||
})
|
||||
|
||||
test('_blank links get rel noopener noreferrer', () => {
|
||||
assert.equal(linkRel('_blank'), 'noopener noreferrer')
|
||||
assert.equal(linkRel('_self'), undefined)
|
||||
assert.equal(linkRel(null), undefined)
|
||||
})
|
||||
|
||||
test('paths normalize: query, hash and trailing slash ignored, decoded', () => {
|
||||
assert.equal(normalizePath('/blog/'), '/blog')
|
||||
assert.equal(normalizePath('/blog?page=2#x'), '/blog')
|
||||
assert.equal(normalizePath('/'), '/')
|
||||
assert.equal(normalizePath(''), '/')
|
||||
assert.equal(normalizePath('/grzyby%20le%C5%9Bne'), '/grzyby leśne')
|
||||
assert.equal(normalizePath('/bad%E0%A4%A'), '/bad%E0%A4%A')
|
||||
})
|
||||
|
||||
test('active matching compares paths; absolute URLs only on the request host', () => {
|
||||
assert.equal(isActive(entry('/blog/'), '/blog', 'site.test'), true)
|
||||
assert.equal(isActive(entry('/blog?x=1'), '/blog/', 'site.test'), true)
|
||||
assert.equal(isActive(entry('/blog'), '/blog/post', 'site.test'), false)
|
||||
assert.equal(isActive(entry('https://site.test/blog'), '/blog', 'site.test'), true)
|
||||
assert.equal(isActive(entry('https://other.test/blog'), '/blog', 'site.test'), false)
|
||||
assert.equal(isActive(entry('#'), '/', 'site.test'), false)
|
||||
assert.equal(entryPath(entry('mailto:a@b.test'), 'site.test'), null)
|
||||
})
|
||||
|
||||
test('the trail marks ancestors of the active entry', () => {
|
||||
const tree = entry('#', { items: [entry('/a'), entry(null, { items: [entry('/deep')] })] })
|
||||
assert.equal(inTrail(tree, '/deep', 'site.test'), true)
|
||||
assert.equal(inTrail(tree, '/a/', 'site.test'), true)
|
||||
assert.equal(inTrail(tree, '/other', 'site.test'), false)
|
||||
})
|
||||
|
||||
test('fillTitle fills :title', () => {
|
||||
assert.equal(fillTitle('Show submenu: :title', 'Grzyby'), 'Show submenu: Grzyby')
|
||||
})
|
||||
|
||||
test('rendered: unsafe URLs are a span without href, _blank links carry rel', async () => {
|
||||
const html = await renderNavItem({
|
||||
entry: entry('#', {
|
||||
title: 'Parent',
|
||||
items: [
|
||||
entry('javascript:alert(1)', { id: 2, title: 'Js' }),
|
||||
entry('data:text/html,x', { id: 3, title: 'Data' }),
|
||||
entry('https://ext.test/', { id: 4, title: 'Ext', target: '_blank' }),
|
||||
entry('/here', { id: 5, title: 'Here' }),
|
||||
entry(null, { id: 6, title: '', type: 'divider' }),
|
||||
],
|
||||
}),
|
||||
routePath: '/here/',
|
||||
})
|
||||
assert.ok(!html.includes('javascript:'), html)
|
||||
assert.ok(!html.includes('data:text'), html)
|
||||
assert.match(html, /<span class="menu-nav__text"[^>]*>Js<\/span>/)
|
||||
assert.match(html, /<span class="menu-nav__text"[^>]*>Data<\/span>/)
|
||||
assert.match(html, /<a href="https:\/\/ext\.test\/" class="menu-nav__link" target="_blank" rel="noopener noreferrer"[^>]*>Ext<\/a>/)
|
||||
// The parent has no URL: one disclosure button; the active child is marked.
|
||||
assert.match(html, /<button type="button" class="menu-nav__link menu-nav__subtoggle" aria-expanded="false" aria-controls="m-0-sub">/)
|
||||
assert.match(html, /aria-current="page"[^>]*>Here</)
|
||||
assert.match(html, /class="menu-nav__item menu-nav__item--parent menu-nav__item--trail"/)
|
||||
assert.match(html, /<li class="menu-nav__divider" aria-hidden="true"><\/li>/)
|
||||
})
|
||||
|
||||
test('rendered: an entry with children and a URL keeps its link and gets a labelled toggle', async () => {
|
||||
const html = await renderNavItem({
|
||||
entry: entry('/blog', { title: 'Blog', items: [entry('/blog/a', { id: 9, title: 'A' })] }),
|
||||
routePath: '/',
|
||||
open: true,
|
||||
})
|
||||
assert.match(html, /<a href="\/blog" class="menu-nav__link"[^>]*>Blog<\/a>/)
|
||||
assert.match(html, /<button type="button" class="menu-nav__subtoggle" aria-expanded="true" aria-controls="m-0-sub">.*Show submenu: Blog/)
|
||||
assert.match(html, /menu-nav__item--open/)
|
||||
})
|
||||
60
tests/render.ts
Normal file
60
tests/render.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
// Test helper: compiles app/components/Menu/NavItem.vue with Vue's SFC
|
||||
// compiler and renders it with the server renderer. NuxtLink is stubbed as
|
||||
// a plain anchor (it renders one for a path in the app too), the component
|
||||
// resolves itself for the recursion, and the returned HTML has no hydration
|
||||
// comments.
|
||||
import { readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
import { compileScript, parse } from 'vue/compiler-sfc'
|
||||
import { createSSRApp, defineComponent, h, type Component } from 'vue'
|
||||
import { renderToString } from 'vue/server-renderer'
|
||||
import type { MenuEntry } from '../app/utils/types.ts'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const source = join(here, '..', 'app', 'components', 'Menu', 'NavItem.vue')
|
||||
|
||||
let compiled: Promise<Component> | null = null
|
||||
|
||||
async function compileNavItem(): Promise<Component> {
|
||||
const { descriptor } = parse(readFileSync(source, 'utf8'), { filename: source })
|
||||
const script = compileScript(descriptor, { id: 'navitem', inlineTemplate: true, genDefaultAs: '__sfc__' })
|
||||
// The compiled module keeps the relative imports, so it is written next to
|
||||
// the source, imported (Node strips the types) and removed.
|
||||
const out = join(dirname(source), `.navitem-${process.pid}.compiled.ts`)
|
||||
writeFileSync(out, `${script.content}\nexport default __sfc__\n`)
|
||||
try {
|
||||
const mod = (await import(pathToFileURL(out).href)) as { default: Component }
|
||||
return mod.default
|
||||
} finally {
|
||||
rmSync(out, { force: true })
|
||||
}
|
||||
}
|
||||
|
||||
const NuxtLink = defineComponent({
|
||||
props: { to: { type: String, required: true } },
|
||||
setup(props, { slots, attrs }) {
|
||||
return () => h('a', { href: props.to, ...attrs }, slots.default?.())
|
||||
},
|
||||
})
|
||||
|
||||
export async function renderNavItem(opts: { entry: MenuEntry; routePath: string; open?: boolean }): Promise<string> {
|
||||
compiled ??= compileNavItem()
|
||||
const NavItem = await compiled
|
||||
const app = createSSRApp({
|
||||
render: () =>
|
||||
h(NavItem, {
|
||||
entry: opts.entry,
|
||||
depth: 0,
|
||||
idBase: 'm-0',
|
||||
open: opts.open ?? false,
|
||||
routePath: opts.routePath,
|
||||
host: 'site.test',
|
||||
submenuLabel: 'Show submenu: :title',
|
||||
}),
|
||||
})
|
||||
app.component('NuxtLink', NuxtLink)
|
||||
app.component('MenuNavItem', NavItem)
|
||||
// Hydration markers (<!--[-->, <!--v-if-->) are dropped for readable assertions.
|
||||
return (await renderToString(app)).replace(/<!--[^>]*-->/g, '')
|
||||
}
|
||||
Reference in New Issue
Block a user