# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors
"""Render the main site's nav partial as the docs header.
The markup stays the main site's own, with three changes:
- root-relative links point at the main site's origin (an empty origin keeps them
root-relative, for a local preview served next to the main site);
- the "Docs" item is marked current: an existing link to the docs site is reused, otherwise
an item is added after Platform;
- the main site's theme switch follows the nav, unless the partial carries it already.
The docs search is not part of the header: it sits above the tree (overrides/main.html).
The output is a Jinja partial for the Zensical theme override.
"""
import re
GENERATED_MARK = "{#- generated by docsite from the main site's partials/nav.html -#}\n"
DOCS_ITEM = '
\n'
# Same markup as the switch on the main site's pages.
THEME_SWITCH = """\
"""
_CURRENT = ' aria-current="page"'
_ROOT_HREF = re.compile(r'href="/(?!/)')
class NavMarkupError(ValueError):
"""The nav partial lacks an anchor the docs header depends on."""
def render_header(nav_html: str, site_origin: str, docs_origin: str) -> str:
"""Return the docs header partial for the given main-site nav markup.
The theme switch is appended only when the partial does not carry one itself.
"""
switch = "" if 'id="theme-switch"' in nav_html else THEME_SWITCH
return GENERATED_MARK + docs_nav(nav_html, site_origin, docs_origin) + switch
def docs_nav(nav_html: str, site_origin: str, docs_origin: str) -> str:
"""Rewrite the main site's nav for the docs site at `docs_origin`."""
html = nav_html.replace(_CURRENT, "")
html = _ROOT_HREF.sub(f'href="{site_origin}/', html)
return _mark_docs_item(html, site_origin, docs_origin)
def _mark_docs_item(html: str, site_origin: str, docs_origin: str) -> str:
"""Mark the nav's link to `docs_origin` current, or add a Docs item after Platform."""
existing = re.search(rf'href="{re.escape(docs_origin)}/?"', html)
if existing:
end = existing.end()
return html[:end] + _CURRENT + html[end:]
platform = rf'.*href="{re.escape(site_origin)}/platform/".*\n'
return _insert_after(html, platform, DOCS_ITEM, "Platform item")
def _insert_after(html: str, line_pattern: str, insert: str, what: str) -> str:
"""Insert `insert` after the first line matching `line_pattern`."""
match = re.search(line_pattern, html)
if not match:
raise NavMarkupError(f"no {what} in the main site's nav")
return html[: match.end()] + insert + html[match.end() :]