Skip to content

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

9.1 KB
Raw Blame
---
// Per-example walkthrough at /docs/examples/<slug>. The head (title, lede,
// the "What you'll build" figure) comes from src/data/examples.ts; the body
// is the matching entry in the `examplePosts` content collection. The page
// uses the docs shell (.layout / aside.side / main.content / .prose), so a
// walkthrough reads like any other docs page, with the examples tree in the
// left rail instead of the docs tree.
import '../../styles/globals.css';
import '../../styles/examples.css';
import Topbar from '../../components/Topbar.astro';
import Toc from '../../components/Toc.astro';
import MobileSheet from '../../components/MobileSheet.astro';
import MermaidRenderer from '@cocoindex/brand/MermaidRenderer.astro';
import Analytics from '../../components/Analytics.astro';
import ScarfPixel from '../../components/ScarfPixel.astro';
import Foot from '../../components/Foot.astro';
import Scene from '../../components/examples/Scene.astro';
import RunIt from '../../components/examples/RunIt.astro';
import { sceneMeta } from '../../components/examples/scenes/meta';
import { THEME_COLOR, SITE_URL, GITHUB_REPO, DOCS_EDIT_BASE, titleText, SCARF_PIXEL_ID, OG_IMAGE_EXAMPLES, OG_IMAGE_WIDTH, OG_IMAGE_HEIGHT, OG_IMAGE_EXAMPLES_ALT } from '../../consts';
import { examples, findExample, byCategory, CATEGORY_META, timeOf, levelOf, type Category } from '../../data/examples';
import { reviewedDate } from '../../data/review-meta';
import type { SidebarItem } from '../../data/docs-sidebar';
import { getEntry, render } from 'astro:content';

export async function getStaticPaths() {
  return examples.map((e) => ({ params: { slug: e.slug } }));
}

const { slug } = Astro.params;
const ex = findExample(slug!);
if (!ex) throw new Error(`Unknown example slug: ${slug}`);

const base = import.meta.env.BASE_URL.replace(/\/$/, '') || '';
const examplesHref = `${base}/examples/`;

// Left rail and phone drawer: every example, grouped as on the catalog.
const CAT_ORDER: Category[] = ['search', 'image', 'llm', 'agents', 'ingest'];
const grouped = CAT_ORDER.map((c) => ({ cat: c, label: CATEGORY_META[c].label, items: byCategory(c) })).filter((g) => g.items.length > 0);
const examplesSidebar: SidebarItem[] = grouped.map((g) => ({
  type: 'category',
  label: g.label,
  items: g.items.map((it) => ({ type: 'doc', slug: `examples/${it.slug}`, label: titleText(it.title) })),
}));

const plainTitle = titleText(ex.title);
const fullTitle = `${plainTitle} Β· CocoIndex Examples`;
const canonical = new URL(`${base}/examples/${slug}/`, SITE_URL).toString();
const examplesHome = new URL(examplesHref, SITE_URL).toString();
const docsHome = new URL(`${base}/`, SITE_URL).toString();
const ogImage = OG_IMAGE_EXAMPLES;
// The repo directory usually matches the slug; sourceSlug overrides it.
const sourceUrl = `${GITHUB_REPO}/tree/main/examples/${ex.sourceSlug ?? slug}`;

const articleLd = {
  '@context': 'https://schema.org',
  '@type': 'TechArticle',
  headline: plainTitle,
  description: ex.description,
  url: canonical,
  inLanguage: 'en',
  image: ogImage,
  isPartOf: { '@type': 'WebSite', name: 'CocoIndex Docs', url: docsHome },
};
const breadcrumbLd = {
  '@context': 'https://schema.org',
  '@type': 'BreadcrumbList',
  itemListElement: [
    { '@type': 'ListItem', position: 1, name: 'Docs', item: docsHome },
    { '@type': 'ListItem', position: 2, name: 'Examples', item: examplesHome },
    { '@type': 'ListItem', position: 3, name: plainTitle, item: canonical },
  ],
};

// The walkthrough body. A listed example without one still gets its head and
// a pointer to the source, so the catalog can lead a write-up.
const entry = await getEntry('examplePosts', slug!);
const rendered = entry ? await render(entry) : null;
const Content = rendered?.Content;
const headings = rendered?.headings ?? [];

const lastReviewed = reviewedDate(`examples/${slug}`);
const facts = [timeOf(ex), levelOf(ex), lastReviewed ? `Reviewed ${lastReviewed}` : null].filter((f): f is string => !!f);
const runnable = (sceneMeta(ex.slug)?.run?.length ?? 0) > 0;
---
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="color-scheme" content="dark" />
    <meta name="theme-color" content={THEME_COLOR} />
    <title>{fullTitle}</title>
    <meta name="description" content={ex.description} />
    <link rel="canonical" href={canonical} />

    <meta property="og:type" content="article" />
    <meta property="og:site_name" content="CocoIndex Docs" />
    <meta property="og:title" content={fullTitle} />
    <meta property="og:description" content={ex.description} />
    <meta property="og:url" content={canonical} />
    <meta property="og:image" content={ogImage} />
    <meta property="og:image:width" content={OG_IMAGE_WIDTH} />
    <meta property="og:image:height" content={OG_IMAGE_HEIGHT} />
    <meta property="og:image:alt" content={OG_IMAGE_EXAMPLES_ALT} />
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content={fullTitle} />
    <meta name="twitter:description" content={ex.description} />
    <meta name="twitter:image" content={ogImage} />

    <script type="application/ld+json" set:html={JSON.stringify(articleLd)} />
    <script type="application/ld+json" set:html={JSON.stringify(breadcrumbLd)} />

    <link rel="icon" href={`${base}/img/favicon.ico`} />
  </head>
  <body class="ex-detail">
    <a class="skip-link" href="#main-content">Skip to content</a>
    <Topbar mobileSheetId="mobileSheet" />
    <MobileSheet currentSlug={`examples/${slug}`} headings={headings} sidebarItems={examplesSidebar} />
    <MermaidRenderer />

    <div class="layout">
      <aside class="side" aria-label="All examples">
        <div class="side-group side-back">
          <ul><li><a href={examplesHref}>All examples <span class="ct">{examples.length}</span></a></li></ul>
        </div>
        {grouped.map((g) => (
          <div class="side-group">
            <h5><span>{g.label}</span></h5>
            <ul>
              {g.items.map((it) => (
                <li>
                  <a href={`${base}/examples/${it.slug}/`} class={it.slug === slug ? 'on' : ''} data-current={it.slug === slug || null} aria-current={it.slug === slug ? 'page' : null}>
                    {titleText(it.title)}
                  </a>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </aside>

      <main class="content" id="main-content" tabindex="-1">
        <div class="page-head">
          <nav class="breadcrumb" aria-label="Breadcrumb">
            <a href={`${base}/`}>Docs</a>
            <span class="sep" aria-hidden="true">/</span>
            <a href={examplesHref}>Examples</a>
            <span class="sep" aria-hidden="true">/</span>
            <span class="now" aria-current="page">{plainTitle}</span>
          </nav>
        </div>

        <header class="ex-head">
          <h1 class="ex-h1">{plainTitle}</h1>
          <p class="ex-lede">{ex.description}</p>

          <div class="ex-cta">
            <a class="btn btn-primary" href={sourceUrl}>View source
              <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true"><path d="M3.5 8.5l5-5M4.5 3.5h4v4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </a>
            {runnable && <a class="btn btn-outline-muted" href="#run">Run it locally</a>}
            <p class="ex-facts">{facts.map((f, i) => <>{i > 0 && <span class="sep" aria-hidden="true">Β·</span>}<span>{f}</span></>)}</p>
          </div>

          <div class="ex-scene">
            <Scene slug={ex.slug} size="hero" />
          </div>

          <RunIt slug={ex.slug} />
        </header>

        <article class="prose ex-prose" id="walkthrough">

          {Content ? (
            <Content />
          ) : (
            <div class="ex-missing">
              <h2>Write-up in progress</h2>
              <p>The step-by-step walkthrough for this example is not published yet. The code is complete on GitHub: open the source above, clone it, and run it today.</p>
            </div>
          )}
        </article>

        <div class="doc-foot">
          <span>CocoIndex Examples</span>
          <span style="display:flex; gap:8px;">
            {entry && <a href={`${DOCS_EDIT_BASE}/src/content/example-posts/${slug}.md`} target="_blank" rel="noopener">Edit this page</a>}
            <a href={`${GITHUB_REPO}/issues/new`} target="_blank" rel="noopener">Report issue</a>
          </span>
        </div>
      </main>

      <Toc headings={headings} lastReviewed={lastReviewed} />
    </div>

    <script>
      // Centre the active example in the rail. Scroll the rail itself, never
      // the window (scrollIntoView would move the page past its head).
      const rail = document.querySelector<HTMLElement>('aside.side');
      const current = rail?.querySelector<HTMLAnchorElement>('a[data-current]');
      if (rail && current && rail.scrollHeight > rail.clientHeight) {
        rail.scrollTop = current.offsetTop - rail.offsetTop - rail.clientHeight / 2 + current.offsetHeight / 2;
      }
    </script>

    <Foot />
    <Analytics />
    <ScarfPixel pxid={SCARF_PIXEL_ID} />
  </body>
</html>