/* ═══════════════════════════════════════════════════════════════ SITE NAV: the site's pages, the header's and footer's links, and the hidden pages Pages → Page management and Pages → Navigation, for this visitor (server/src/siteNav.js): a hidden page, and links to it, are only sent to a viewer and up; a disabled page's links to no one. The page HTML carries it (window.__SITE__.nav), so the menus draw on the first paint; GET /api/nav asks again, which is also how the dev server (no page metadata) and a sign-in in another tab get it. Until either answers, navConfig.ts's links, and no pages yet (`ready` false). ═══════════════════════════════════════════════════════════════ */ import { useMemo } from 'react' import { NAV_DEFAULTS, type NavLink } from '../navConfig.ts' import { useRecord } from './useRecord.ts' /** A page of the site (site_pages). */ export type SitePageInfo = { id: string path: string title: string description: string | null hidden: boolean disabled: boolean } export type SiteNav = { links: NavLink[] pages: SitePageInfo[] /** Paths of hidden pages, eg. '/shop' (sent to a viewer and up only). */ hidden: string[] /** This visitor sees hidden pages (signed in, viewer and up). */ seesHidden: boolean } const fromPage: SiteNav | undefined = typeof window !== 'undefined' ? (window as unknown as { __SITE__?: { nav?: SiteNav } }).__SITE__?.nav : undefined const DEFAULTS: SiteNav = { links: NAV_DEFAULTS, pages: [], hidden: [], seesHidden: false } /** A path's page: no #section or ?query, no trailing slash. */ export const pageOf = (path: string): string => path.split(/[?#]/)[0].replace(/(.)\/+$/, '$1') || '/' export function useSiteNav() { const { data } = useRecord('/nav', 'nav') const nav = data ?? fromPage ?? DEFAULTS return useMemo(() => { const main = nav.links.filter((l) => l.place === 'main') const top = main.filter((l) => !l.parent) const tops = new Set(top.map((l) => pageOf(l.path))) const byPath = new Map(nav.pages.map((page) => [page.path, page])) return { ...nav, /** Whether the pages have arrived (else a page can't be told from a missing one). */ ready: Boolean(data ?? fromPage), /** The header's pages, each with the links set under it. */ main: top.map((page) => ({ ...page, children: main.filter((l) => l.parent && l.parent === pageOf(page.path)), })), /** Every main link, children included, for lists of the site's pages. */ pageLinks: main.filter((l) => !l.parent || tops.has(l.parent)), actions: nav.links.filter((l) => l.place === 'action'), footer: nav.links.filter((l) => l.place === 'footer'), legal: nav.links.filter((l) => l.place === 'legal'), isHidden: (path: string) => nav.hidden.includes(pageOf(path)), /** The page at this path, or null. */ pageAt: (path: string): SitePageInfo | null => byPath.get(pageOf(path)) ?? null, } }, [nav, data]) }