Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

8.6 KB
Raw Blame
---
// Phone-only off-canvas drawer. The shell (scrim + sliding panel + close
// header) and the open/close behavior come from the shared
// @cocoindex/brand/MobileSheet; this component fills its slot with the docs
// content: a search box + two segmented tabs β€”
//   - Pages        : the full sidebar tree (mirrors Sidebar.astro)
//   - On this page : the current doc's H2/H3/H4 headings
// and adds the tab-switch script (open/close, scrim, Esc, scroll-lock, and
// close-on-link-tap all live in the shared controller). The tab/pane/group/
// search styling stays in globals.css; the shell styling is brand nav.css.
import type { MarkdownHeading } from 'astro';
import { sidebar, type SidebarItem } from '../data/docs-sidebar';
import { SITE_MAIN, SITE_BLOG, SITE_EXAMPLES } from '../consts';
import Search from './Search.astro';
import LangSwitch from './LangSwitch.astro';
import { DEFAULT_LANG, langHref, pageRegistry, sidebarFor, type Lang } from '../lib/lang';
import MobileSheet from '@cocoindex/brand/MobileSheet.astro';

export interface Props {
  /** Slug of the currently-rendered doc. Drives the `aria-current` row in the Pages tab. */
  currentSlug?: string;
  /** Page headings (already filtered to H2/H3/H4 by the layout, or raw β€” we re-filter here). */
  headings?: MarkdownHeading[];
  /** Sidebar tree to surface in the Pages pane before the Site links. Pass
   *  `null` to render no docs sidebar (e.g. on examples listing or 404).
   *  Defaults to the docs-sidebar tree (regular doc pages). */
  sidebarItems?: SidebarItem[] | null;
  /** SDK language of a docs page: shows the Python | Rust switch and links
   *  into that language's tree. Absent on non-docs pages. */
  lang?: Lang;
}

const {
  currentSlug = '',
  headings = [],
  sidebarItems: sidebarItemsRaw,
  lang,
} = Astro.props;
// Default: the docs sidebar of the page's language (the Python tree on pages
// that are not docs pages, such as the home page and 404), so no link points
// at a page that exists only in the other tree.
const sidebarItems: SidebarItem[] | null =
  sidebarItemsRaw === undefined
    ? sidebarFor(sidebar, lang ?? DEFAULT_LANG, await pageRegistry())
    : sidebarItemsRaw;
const isDocsTree = sidebarItemsRaw === undefined || lang !== undefined;
// Put the current section first without changing the shared desktop order.
function containsCurrent(item: SidebarItem): boolean {
  return item.slug === currentSlug ||
    (item.type === 'category' && item.items.some(containsCurrent));
}
const mobileItems = sidebarItems ? [
  ...sidebarItems.filter(containsCurrent),
  ...sidebarItems.filter((item) => !containsCurrent(item)),
] : [];
const base = import.meta.env.BASE_URL.replace(/\/$/, '');

// Site-level nav β€” same set rendered inline in Topbar.astro at desktop
// width. Surfaced here so phones still have a path to Examples / Docs /
// Enterprise / Blog when `.nav-links` is hidden.
const SITE_LINKS: Array<{ href: string; label: string }> = [
  { href: `${SITE_MAIN}/cocoindex-code/`, label: 'CocoIndex Code' },
  { href: SITE_EXAMPLES,                 label: 'Examples'       },
  { href: `${base}/`,                    label: 'Documentation'  },
  { href: `${SITE_MAIN}/enterprise/`,     label: 'Enterprise'     },
  { href: SITE_BLOG,                     label: 'Blog'           },
];

// Same H2/H3/H4 filter as Toc.astro so the phone "On this page" list matches
// the desktop rail one-for-one. No numbering: the rail is a list, not an index.
const tocRows = headings.filter((h) => h.depth >= 2 && h.depth <= 4);

function href(slug: string): string {
  // Trailing slash matches the canonical URL Astro emits under
  // `build.format: 'directory'` β€” saves a 301 round-trip per click.
  if (lang) return langHref(lang, slug);
  return slug ? `${base}/${slug}/` : `${base}/`;
}
---

<MobileSheet id="mobileSheet" title="Menu" closeAbove={1120}>
  {lang && <LangSwitch lang={lang} route={currentSlug} />}
  <div class="mobile-search">
    <Search />
  </div>

  {tocRows.length > 0 && (
    <div class="mobile-tabs" role="tablist" aria-label="Menu sections">
      <button id="tabPages" type="button" role="tab" aria-selected="true" aria-controls="panePages">
        Pages
      </button>
      <button id="tabToc" type="button" role="tab" aria-selected="false" tabindex="-1" aria-controls="paneToc">
        On this page
      </button>
    </div>
  )}

  {tocRows.length > 0 && (
    <div class="mobile-pane" id="paneToc" role="tabpanel" aria-labelledby="tabToc" hidden>
      <nav class="mobile-list" aria-label="On this page">
        {tocRows.map((h) => (
          <a
            href={`#${h.slug}`}
            data-mobile-toc-link={h.slug}
            class={h.depth === 3 ? 'sub' : h.depth === 4 ? 'sub-sub' : ''}
          >
            <span class="lbl">{h.text}</span>
          </a>
        ))}
      </nav>
    </div>
  )}

  <div class="mobile-pane" id="panePages" role={tocRows.length > 0 ? 'tabpanel' : undefined} aria-labelledby={tocRows.length > 0 ? 'tabPages' : undefined}>
    {isDocsTree && (
      <div class="mobile-group">
        <nav class="mobile-list" aria-label="Documentation home">
          <a href={href('')} aria-current={currentSlug === '' ? 'page' : undefined}>
            <span class="lbl">About CocoIndex</span>
          </a>
        </nav>
      </div>
    )}
    {mobileItems.map((item) => (
      item.type === 'doc' ? (
        <div class="mobile-group">
          <nav class="mobile-list" aria-label={item.label ?? item.slug}>
            <a
              href={href(item.slug)}
              aria-current={currentSlug === item.slug ? 'page' : undefined}
            >
              <span class="lbl">{item.label ?? item.slug}</span>
            </a>
          </nav>
        </div>
      ) : (
        <div class="mobile-group">
          <p class="mobile-h">
            {item.slug ? (
              <a href={href(item.slug)}>{item.label}</a>
            ) : (
              <span>{item.label}</span>
            )}
          </p>
          <nav class="mobile-list" aria-label={item.label}>
            {item.items.map((child) => (
              child.type === 'doc' ? (
                <a
                  href={href(child.slug)}
                  aria-current={currentSlug === child.slug ? 'page' : undefined}
                >
                  <span class="lbl">{child.label ?? child.slug}</span>
                </a>
              ) : null
            ))}
          </nav>
        </div>
      )
    ))}
    {mobileItems.length > 0 && <hr class="mobile-divider" />}
    <div class="mobile-group">
      <p class="mobile-h"><span>Site</span></p>
      <nav class="mobile-list" aria-label="Site">
        {SITE_LINKS.map((l) => (
          <a href={l.href} aria-current={l.label === 'Documentation' && !Astro.url.pathname.startsWith(`${base}/examples/`) ? 'location' : l.label === 'Examples' && Astro.url.pathname.startsWith(`${base}/examples/`) ? 'location' : undefined}><span class="lbl">{l.label}</span></a>
        ))}
      </nav>
    </div>

  </div>
</MobileSheet>

<script>
  // Tab switch only β€” open/close, scrim, Esc, scroll-lock, and close-on-link-tap
  // are all handled by the shared MobileSheet controller (@cocoindex/brand).
  // Tabs render only when the page has headings; bail cleanly otherwise.
  (() => {
    const tabToc   = document.getElementById('tabToc')   as HTMLButtonElement | null;
    const tabPages = document.getElementById('tabPages') as HTMLButtonElement | null;
    const paneToc   = document.getElementById('paneToc')   as HTMLElement | null;
    const panePages = document.getElementById('panePages') as HTMLElement | null;
    if (!tabToc || !tabPages || !paneToc || !panePages) return;

    const setTab = (which: 'toc' | 'pages') => {
      const onToc = which === 'toc';
      tabToc.setAttribute('aria-selected', onToc ? 'true' : 'false');
      tabPages.setAttribute('aria-selected', onToc ? 'false' : 'true');
      tabToc.tabIndex = onToc ? 0 : -1;
      tabPages.tabIndex = onToc ? -1 : 0;
      paneToc.hidden = !onToc;
      panePages.hidden = onToc;
    };

    tabToc  .addEventListener('click', () => setTab('toc'));
    tabPages.addEventListener('click', () => setTab('pages'));

    // Arrow-key tab navigation (a11y).
    const tabsArr = [tabPages, tabToc];
    tabsArr.forEach((t, i, arr) => {
      t.addEventListener('keydown', (e) => {
        if (['ArrowRight', 'ArrowLeft', 'Home', 'End'].includes(e.key)) {
          e.preventDefault();
          const target = e.key === 'Home' ? arr[0] : e.key === 'End' ? arr[arr.length - 1]
            : arr[(i + (e.key === 'ArrowRight' ? 1 : -1) + arr.length) % arr.length];
          target.focus();
          setTab(target === tabToc ? 'toc' : 'pages');
        }
      });
    });
  })();
</script>