commit
1d34d1b3b1
18 files changed
+1500
-98
No files matched your search
@@ -0,0 +1,170 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { buildPageLinks, mergeLinks, adoptPageLinks, rewriteHeaderLinks, pageHref, NavLink } from './nav-links';
|
||||
import { PageData } from '../types';
|
||||
import { DEFAULT_HEADER_STATE } from '../state/PageContext';
|
||||
|
||||
const pg = (id: string, name: string, slug: string, nav?: PageData['nav']): PageData =>
|
||||
({ id, name, slug, craftState: null, ...(nav ? { nav } : {}) });
|
||||
|
||||
const home = pg('home', 'Home', 'index');
|
||||
const about = pg('about', 'About', 'about');
|
||||
const services = pg('services', 'Services', 'services');
|
||||
|
||||
describe('pageHref', () => {
|
||||
test('landing page is "/", others "/slug"', () => {
|
||||
expect(pageHref(home, 0)).toBe('/');
|
||||
expect(pageHref(about, 1)).toBe('/about');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildPageLinks', () => {
|
||||
test('landing first, page order, label override, source/pageId', () => {
|
||||
const links = buildPageLinks([home, pg('about', 'About', 'about', { label: 'Our story' }), services]);
|
||||
expect(links).toEqual([
|
||||
{ text: 'Home', href: '/', source: 'page', pageId: 'home' },
|
||||
{ text: 'Our story', href: '/about', source: 'page', pageId: 'about' },
|
||||
{ text: 'Services', href: '/services', source: 'page', pageId: 'services' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('hidden pages are left out', () => {
|
||||
const links = buildPageLinks([home, pg('about', 'About', 'about', { show: false }), services]);
|
||||
expect(links.map((l) => l.pageId)).toEqual(['home', 'services']);
|
||||
});
|
||||
|
||||
test('nests by parentId (one level), children in page order', () => {
|
||||
const pages = [
|
||||
home,
|
||||
services,
|
||||
pg('web', 'Web', 'web', { parentId: 'services' }),
|
||||
about,
|
||||
pg('seo', 'SEO', 'seo', { parentId: 'services' }),
|
||||
];
|
||||
const links = buildPageLinks(pages);
|
||||
expect(links.map((l) => l.pageId)).toEqual(['home', 'services', 'about']);
|
||||
expect(links[1].children).toEqual([
|
||||
{ text: 'Web', href: '/web', source: 'page', pageId: 'web' },
|
||||
{ text: 'SEO', href: '/seo', source: 'page', pageId: 'seo' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('a child of a hidden / missing / nested parent, and the landing page, stay top-level', () => {
|
||||
const pages = [
|
||||
pg('home', 'Home', 'index', { parentId: 'about' }),
|
||||
pg('about', 'About', 'about', { show: false }),
|
||||
pg('a', 'A', 'a', { parentId: 'about' }),
|
||||
pg('b', 'B', 'b', { parentId: 'gone' }),
|
||||
pg('c', 'C', 'c', { parentId: 'd' }),
|
||||
pg('d', 'D', 'd', { parentId: 'c' }),
|
||||
];
|
||||
const links = buildPageLinks(pages);
|
||||
expect(links.map((l) => l.pageId)).toEqual(['home', 'a', 'b', 'c', 'd']);
|
||||
expect(links.every((l) => !l.children)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mergeLinks', () => {
|
||||
const cta: NavLink = { text: 'Get Started', href: '#signup', isCta: true };
|
||||
const blog: NavLink = { text: 'Blog', href: 'https://blog.example.com', isExternal: true };
|
||||
|
||||
test('keeps manual links and the CTA (CTA last), rebuilds page links', () => {
|
||||
const existing: NavLink[] = [
|
||||
{ text: 'Home', href: '/', source: 'page', pageId: 'home' },
|
||||
cta,
|
||||
blog,
|
||||
];
|
||||
expect(mergeLinks(existing, [home, about])).toEqual([
|
||||
{ text: 'Home', href: '/', source: 'page', pageId: 'home' },
|
||||
{ text: 'About', href: '/about', source: 'page', pageId: 'about' },
|
||||
blog,
|
||||
cta,
|
||||
]);
|
||||
});
|
||||
|
||||
test('manual links that sat before the page links stay before them', () => {
|
||||
const shop: NavLink = { text: 'Shop', href: 'https://shop.example.com' };
|
||||
const existing: NavLink[] = [shop, { text: 'Home', href: '/', source: 'page', pageId: 'home' }, blog];
|
||||
expect(mergeLinks(existing, [home]).map((l) => l.text)).toEqual(['Shop', 'Home', 'Blog']);
|
||||
});
|
||||
|
||||
test("drops a deleted page's link", () => {
|
||||
const existing: NavLink[] = [
|
||||
{ text: 'Home', href: '/', source: 'page', pageId: 'home' },
|
||||
{ text: 'About', href: '/about', source: 'page', pageId: 'about' },
|
||||
cta,
|
||||
];
|
||||
expect(mergeLinks(existing, [home])).toEqual([
|
||||
{ text: 'Home', href: '/', source: 'page', pageId: 'home' },
|
||||
cta,
|
||||
]);
|
||||
});
|
||||
|
||||
test('dedupes page links by pageId', () => {
|
||||
const existing: NavLink[] = [
|
||||
{ text: 'About', href: '/about', source: 'page', pageId: 'about' },
|
||||
{ text: 'About again', href: '/about', source: 'page', pageId: 'about' },
|
||||
];
|
||||
expect(mergeLinks(existing, [home, about]).filter((l) => l.pageId === 'about')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('adoptPageLinks', () => {
|
||||
test('converts a manual "/about" (and "/") into page links; leaves CTA and externals', () => {
|
||||
const links: NavLink[] = [
|
||||
{ text: 'Home', href: '/' },
|
||||
{ text: 'About', href: '/about' },
|
||||
{ text: 'Blog', href: 'https://blog.example.com' },
|
||||
{ text: 'About CTA', href: '/about', isCta: true },
|
||||
];
|
||||
expect(adoptPageLinks(links, [home, about])).toEqual([
|
||||
{ text: 'Home', href: '/', source: 'page', pageId: 'home' },
|
||||
{ text: 'About', href: '/about', source: 'page', pageId: 'about' },
|
||||
{ text: 'Blog', href: 'https://blog.example.com' },
|
||||
{ text: 'About CTA', href: '/about', isCta: true },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
/** A serialized header holding a follow-pages Navbar, a non-following Menu and a Container. */
|
||||
function headerState(navProps: Record<string, unknown>, menuLinks: NavLink[] = [{ text: 'Legacy', href: '/about' }]): string {
|
||||
return JSON.stringify({
|
||||
ROOT: { type: { resolvedName: 'Container' }, isCanvas: true, props: { tag: 'header' }, displayName: 'Container', custom: {}, hidden: false, nodes: ['nav', 'menu'], linkedNodes: {} },
|
||||
nav: { type: { resolvedName: 'Navbar' }, isCanvas: false, props: navProps, displayName: 'Navbar', parent: 'ROOT', custom: {}, hidden: false, nodes: [], linkedNodes: {} },
|
||||
menu: { type: { resolvedName: 'Menu' }, isCanvas: false, props: { links: menuLinks }, displayName: 'Menu', parent: 'ROOT', custom: {}, hidden: false, nodes: [], linkedNodes: {} },
|
||||
});
|
||||
}
|
||||
|
||||
describe('rewriteHeaderLinks', () => {
|
||||
test('returns the IDENTICAL string when nothing changed', () => {
|
||||
const pages = [home, about];
|
||||
const state = headerState({ followPages: true, links: mergeLinks([], pages) });
|
||||
expect(rewriteHeaderLinks(state, pages)).toBe(state);
|
||||
});
|
||||
|
||||
test('the default header seed is already materialised for the default Home page', () => {
|
||||
expect(rewriteHeaderLinks(DEFAULT_HEADER_STATE, [home])).toBe(DEFAULT_HEADER_STATE);
|
||||
});
|
||||
|
||||
test('renaming a page updates href AND text of the follow-pages nav only', () => {
|
||||
const before = [home, about];
|
||||
const state = headerState({ followPages: true, links: [...mergeLinks([], before), { text: 'Go', href: '#', isCta: true }] });
|
||||
const after = [home, pg('about', 'Team', 'team')];
|
||||
const next = JSON.parse(rewriteHeaderLinks(state, after));
|
||||
expect(next.nav.props.links).toEqual([
|
||||
{ text: 'Home', href: '/', source: 'page', pageId: 'home' },
|
||||
{ text: 'Team', href: '/team', source: 'page', pageId: 'about' },
|
||||
{ text: 'Go', href: '#', isCta: true },
|
||||
]);
|
||||
// The non-following Menu is never touched -- legacy manual links survive exactly.
|
||||
expect(next.menu.props.links).toEqual([{ text: 'Legacy', href: '/about' }]);
|
||||
});
|
||||
|
||||
test('a legacy nav without followPages is returned unchanged even when pages differ', () => {
|
||||
const legacy = headerState({ links: [{ text: 'Home', href: '/' }, { text: 'Old', href: '/old' }] });
|
||||
expect(rewriteHeaderLinks(legacy, [home, about, services])).toBe(legacy);
|
||||
});
|
||||
|
||||
test('unreadable state is returned as-is', () => {
|
||||
expect(rewriteHeaderLinks('not json', [home])).toBe('not json');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
import type { PageData } from '../types';
|
||||
|
||||
/**
|
||||
* Shared link shape for Navbar and Menu (#53). `source` absent = a manual
|
||||
* link (every link saved before #53 is manual and is never rewritten). A
|
||||
* `source: 'page'` link is owned by its page: on a nav with `followPages`
|
||||
* on, its text/href/children are rebuilt from the pages list whenever pages
|
||||
* change (see `mergeLinks` / `rewriteHeaderLinks`).
|
||||
*/
|
||||
export interface NavLink {
|
||||
text: string;
|
||||
href: string;
|
||||
isExternal?: boolean;
|
||||
isCta?: boolean;
|
||||
/** Adds the `download` attribute to the exported anchor (F3: links to files). */
|
||||
download?: boolean;
|
||||
source?: 'page' | 'manual';
|
||||
pageId?: string;
|
||||
/** One level of nesting, rendered as a dropdown. */
|
||||
children?: NavLink[];
|
||||
}
|
||||
|
||||
/** Resolver names of the components that carry a `links` array + `followPages`. */
|
||||
const NAV_COMPONENTS = new Set(['Navbar', 'Menu']);
|
||||
|
||||
/* Mirrors the export convention: the first page is always the landing page
|
||||
and publishes to '/', every other page publishes to '/{slug}' (the
|
||||
published .htaccess rewrites /slug -> slug.html). Single source of truth
|
||||
for page hrefs -- NavStylePanel re-exports it. */
|
||||
export function pageHref(page: PageData, index: number): string {
|
||||
return index === 0 ? '/' : `/${page.slug}`;
|
||||
}
|
||||
|
||||
function isShown(page: PageData): boolean {
|
||||
return page.nav?.show !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The parent a page nests under, or null when it is top-level. One level
|
||||
* only: a parent that is itself nested makes the child top-level (this also
|
||||
* breaks A<->B cycles). The landing page never nests; a missing, hidden or
|
||||
* self parent is ignored.
|
||||
*/
|
||||
function parentOf(pages: PageData[], index: number): PageData | null {
|
||||
const raw = (i: number): PageData | null => {
|
||||
if (i <= 0) return null;
|
||||
const pid = pages[i].nav?.parentId;
|
||||
if (!pid || pid === pages[i].id) return null;
|
||||
const parent = pages.find((p) => p.id === pid);
|
||||
return parent && isShown(parent) ? parent : null;
|
||||
};
|
||||
const parent = raw(index);
|
||||
if (!parent) return null;
|
||||
return raw(pages.indexOf(parent)) ? null : parent;
|
||||
}
|
||||
|
||||
function pageLink(page: PageData, index: number): NavLink {
|
||||
return {
|
||||
text: page.nav?.label || page.name,
|
||||
href: pageHref(page, index),
|
||||
source: 'page',
|
||||
pageId: page.id,
|
||||
};
|
||||
}
|
||||
|
||||
/** One link per shown page, in page order (landing first), children nested by `nav.parentId`. */
|
||||
export function buildPageLinks(pages: PageData[]): NavLink[] {
|
||||
const top: NavLink[] = [];
|
||||
const byId = new Map<string, NavLink>();
|
||||
pages.forEach((page, i) => {
|
||||
if (!isShown(page) || parentOf(pages, i)) return;
|
||||
const link = pageLink(page, i);
|
||||
byId.set(page.id, link);
|
||||
top.push(link);
|
||||
});
|
||||
pages.forEach((page, i) => {
|
||||
if (!isShown(page)) return;
|
||||
const parent = parentOf(pages, i);
|
||||
if (!parent) return;
|
||||
const host = byId.get(parent.id);
|
||||
if (!host) return;
|
||||
host.children = [...(host.children || []), pageLink(page, i)];
|
||||
});
|
||||
return top;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuilds the page-sourced links of `existing` from `pages`, keeping every
|
||||
* manual link. Order: manual links that sat before the first page link,
|
||||
* then the page links (page order), then the remaining manual links, then
|
||||
* every CTA. Page links are deduped by pageId simply by being rebuilt -- any
|
||||
* stale page link (deleted/hidden page) drops out.
|
||||
*/
|
||||
export function mergeLinks(existing: NavLink[], pages: PageData[]): NavLink[] {
|
||||
const leading: NavLink[] = [];
|
||||
const trailing: NavLink[] = [];
|
||||
const ctas: NavLink[] = [];
|
||||
const hasPageLinks = existing.some((l) => l.source === 'page' && !l.isCta);
|
||||
let seenPage = false;
|
||||
for (const link of existing) {
|
||||
if (link.isCta) { ctas.push(link); continue; }
|
||||
if (link.source === 'page') { seenPage = true; continue; }
|
||||
(hasPageLinks && !seenPage ? leading : trailing).push(link);
|
||||
}
|
||||
return [...leading, ...buildPageLinks(pages), ...trailing, ...ctas];
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts manual links whose href is exactly a page's href into page links
|
||||
* (used once, when the owner switches Follow pages on). CTAs stay manual.
|
||||
*/
|
||||
export function adoptPageLinks(links: NavLink[], pages: PageData[]): NavLink[] {
|
||||
const byHref = new Map<string, PageData>();
|
||||
pages.forEach((p, i) => { if (!byHref.has(pageHref(p, i))) byHref.set(pageHref(p, i), p); });
|
||||
return links.map((link) => {
|
||||
if (link.isCta || link.source === 'page') return link;
|
||||
const page = byHref.get(link.href);
|
||||
return page ? { ...link, source: 'page', pageId: page.id } : link;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Materialises page-following links into a serialized Craft state: every
|
||||
* Navbar/Menu node with `followPages` gets `props.links = mergeLinks(...)`.
|
||||
* Returns the IDENTICAL string when nothing changed (callers use string
|
||||
* equality to avoid marking the editor dirty) or when the state is unreadable.
|
||||
*/
|
||||
export function rewriteHeaderLinks(serializedState: string, pages: PageData[]): string {
|
||||
let nodes: Record<string, any>;
|
||||
try {
|
||||
nodes = JSON.parse(serializedState);
|
||||
} catch {
|
||||
return serializedState;
|
||||
}
|
||||
if (!nodes || typeof nodes !== 'object') return serializedState;
|
||||
let changed = false;
|
||||
for (const node of Object.values(nodes)) {
|
||||
if (!node || !NAV_COMPONENTS.has(node.type?.resolvedName) || !node.props?.followPages) continue;
|
||||
const current: NavLink[] = Array.isArray(node.props.links) ? node.props.links : [];
|
||||
const merged = mergeLinks(current, pages);
|
||||
if (JSON.stringify(merged) !== JSON.stringify(current)) {
|
||||
node.props.links = merged;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed ? JSON.stringify(nodes) : serializedState;
|
||||
}
|
||||
|
||||
/** True when the node (Craft resolver name) is a page-following nav. */
|
||||
export function isFollowPagesNav(resolvedName: string | undefined, props: any): boolean {
|
||||
return !!resolvedName && NAV_COMPONENTS.has(resolvedName) && !!props?.followPages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline click handler for an exported dropdown toggle button (same inline
|
||||
* pattern as the Navbar hamburger): flips `is-open` on the wrapper and keeps
|
||||
* `aria-expanded` in sync. Self-contained per button, so several navs on one
|
||||
* page never interfere and nothing global is installed. No double quotes --
|
||||
* it sits inside a double-quoted attribute.
|
||||
*/
|
||||
export const DROPDOWN_TOGGLE_ONCLICK =
|
||||
"var o=this.parentNode.classList.toggle('is-open');this.setAttribute('aria-expanded',o?'true':'false')";
|
||||
|
||||
/** True when some non-CTA link has children (i.e. the dropdown CSS is needed). */
|
||||
export function hasDropdown(links: NavLink[]): boolean {
|
||||
return links.some((l) => !l.isCta && !!l.children?.length);
|
||||
}
|
||||
Reference in new issue
Block a user