Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(website): add markdown docs export (#1499)

Corentin Thomasset57e3ff8e61c5
diff --git a/apps/website/public/_headers b/apps/website/public/_headers
index ce9f1c1e..1345795d 100644
--- a/apps/website/public/_headers
+++ b/apps/website/public/_headers
@@ -1,3 +1,7 @@
/*
X-Frame-Options: DENY
- X-Content-Type-Options: nosniff
\ No newline at end of file
+ X-Content-Type-Options: nosniff
+
+# Static endpoint response headers aren't preserved in the generated files.
+/*.md
+ Content-Type: text/markdown; charset=utf-8
diff --git a/apps/website/src/docs/components/DocMarkdownActions.astro b/apps/website/src/docs/components/DocMarkdownActions.astro
new file mode 100644
index 00000000..4d4c8fb9
--- /dev/null
+++ b/apps/website/src/docs/components/DocMarkdownActions.astro
@@ -0,0 +1,214 @@
+---
+import type { Locale } from "../../i18n/i18n.constants";
+import { useI18n } from "../../i18n/i18n";
+import { getDocUrl } from "../docs.models";
+
+type Props = { docId: string; locale: Locale };
+const { docId, locale } = Astro.props;
+const { t } = useI18n({ locale });
+const markdownUrl = `${getDocUrl({ docId, locale })}.md`;
+---
+
+<docs-markdown-actions
+ class="relative ml-auto shrink-0 text-sm"
+ data-url={markdownUrl}
+ data-copied={t("docs.markdown.copied")}
+ data-error={t("docs.markdown.error")}
+>
+ <div class="inline-flex items-stretch rounded-md border text-muted-foreground">
+ <button
+ type="button"
+ data-copy
+ class="rounded-l-md px-3 py-1.5 hover:bg-muted hover:text-foreground transition"
+ >
+ <span data-copy-label>{t("docs.markdown.copy-short")}</span>
+ </button>
+ <details class="relative flex">
+ <summary
+ aria-label={t("docs.markdown.options")}
+ aria-controls="docs-markdown-options"
+ class="flex h-full items-center border-l rounded-r-md px-2 cursor-pointer hover:bg-muted hover:text-foreground transition"
+ >
+ <span
+ class="i-tabler-chevron-down size-4"
+ aria-hidden="true"
+ ></span>
+ </summary>
+ <div
+ id="docs-markdown-options"
+ class="absolute right-0 top-full mt-2 z-20 w-52 rounded-md border bg-background p-1 shadow-lg"
+ >
+ <button
+ type="button"
+ data-copy
+ class="flex w-full items-center gap-2 rounded px-3 py-2 text-left hover:bg-muted hover:text-foreground transition"
+ >
+ <span
+ class="i-tabler-copy size-4"
+ aria-hidden="true"
+ ></span>
+ {t("docs.markdown.copy")}
+ </button>
+ <a
+ href={markdownUrl}
+ class="flex items-center gap-2 rounded px-3 py-2 hover:bg-muted hover:text-foreground transition"
+ >
+ <span
+ class="i-tabler-file-text size-4"
+ aria-hidden="true"
+ ></span>
+ {t("docs.markdown.view")}
+ </a>
+ </div>
+ </details>
+ </div>
+ <span role="status" class="sr-only"></span>
+</docs-markdown-actions>
+
+<script>
+ class DocsMarkdownActions extends HTMLElement {
+ private controller?: AbortController;
+ private resetTimer?: ReturnType<typeof setTimeout>;
+
+ connectedCallback() {
+ this.controller?.abort();
+ this.controller = new AbortController();
+ const { signal } = this.controller;
+ const details = this.querySelector("details")!;
+ const summary = this.querySelector("summary")!;
+ const buttons = [
+ ...this.querySelectorAll<HTMLButtonElement>("[data-copy]"),
+ ];
+ const label = this.querySelector("[data-copy-label]")!;
+ const defaultLabel = label.textContent;
+ const status = this.querySelector('[role="status"]')!;
+
+ const close = () => {
+ if (details.open && details.contains(document.activeElement)) {
+ summary.focus();
+ }
+ details.open = false;
+ };
+
+ const copy = async () => {
+ close();
+ clearTimeout(this.resetTimer);
+ buttons.forEach((button) => {
+ button.disabled = true;
+ });
+ status.textContent = "";
+
+ try {
+ if (!navigator.clipboard) {
+ throw new Error("Clipboard is unavailable");
+ }
+
+ const content = fetch(this.dataset.url!, { signal }).then(
+ async (response) => {
+ if (!response.ok) {
+ throw new Error(
+ `Failed to fetch Markdown: ${response.status}`,
+ );
+ }
+ return response.text();
+ },
+ );
+
+ // Start the clipboard write during the click's user activation, even
+ // while fetching, for browsers such as Safari that require it.
+ if (
+ typeof ClipboardItem !== "undefined" &&
+ navigator.clipboard.write
+ ) {
+ const blob = content.then(
+ (text) => new Blob([text], { type: "text/plain" }),
+ );
+ await Promise.all([
+ blob,
+ navigator.clipboard.write([
+ new ClipboardItem({ "text/plain": blob }),
+ ]),
+ ]);
+ } else {
+ const text = await content;
+ await navigator.clipboard.writeText(text);
+ }
+ label.textContent = this.dataset.copied!;
+ } catch {
+ label.textContent = this.dataset.error!;
+ } finally {
+ buttons.forEach((button) => {
+ button.disabled = false;
+ });
+ status.textContent = label.textContent;
+ if (!signal.aborted) {
+ this.resetTimer = setTimeout(() => {
+ label.textContent = defaultLabel;
+ status.textContent = "";
+ }, 3000);
+ }
+ }
+ };
+
+ buttons.forEach((button) =>
+ button.addEventListener("click", copy, { signal }),
+ );
+ this.addEventListener(
+ "keydown",
+ (event) => {
+ if (event.key === "Escape" && details.open) {
+ event.preventDefault();
+ close();
+ }
+ },
+ { signal },
+ );
+ this.addEventListener(
+ "focusout",
+ (event) => {
+ if (
+ !(event.relatedTarget instanceof Node) ||
+ !this.contains(event.relatedTarget)
+ ) {
+ details.open = false;
+ }
+ },
+ { signal },
+ );
+ document.addEventListener(
+ "click",
+ (event) => {
+ if (
+ event.target instanceof Node &&
+ !this.contains(event.target)
+ ) {
+ details.open = false;
+ }
+ },
+ { signal },
+ );
+ }
+
+ disconnectedCallback() {
+ this.controller?.abort();
+ clearTimeout(this.resetTimer);
+ }
+ }
+
+ customElements.define("docs-markdown-actions", DocsMarkdownActions);
+</script>
+
+<style>
+ summary {
+ list-style: none;
+ }
+
+ summary::-webkit-details-marker {
+ display: none;
+ }
+
+ :is(button, summary, a):focus-visible {
+ outline: 2px solid hsl(var(--ring));
+ outline-offset: 2px;
+ }
+</style>
diff --git a/apps/website/src/docs/docs.markdown.test.ts b/apps/website/src/docs/docs.markdown.test.ts
new file mode 100644
index 00000000..289d6d4a
--- /dev/null
+++ b/apps/website/src/docs/docs.markdown.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, test } from 'vitest';
+import { formatDocMarkdown } from './docs.markdown';
+
+describe('docs.markdown', () => {
+ describe('formatDocMarkdown', () => {
+ test('appends the title as a markdown heading and the body below it', () => {
+ expect(
+ formatDocMarkdown({
+ body: 'Lorem ipsum',
+ data: { title: 'Title' },
+ }),
+ ).to.eql('# Title\n\nLorem ipsum');
+ });
+
+ test('trims the body', () => {
+ expect(
+ formatDocMarkdown({
+ body: ' Lorem ipsum \n\t ',
+ data: { title: 'Title' },
+ }),
+ ).to.eql('# Title\n\nLorem ipsum');
+ });
+
+ test.each(["'", '"'])('preserves quoted content after imports using %s', (quote) => {
+ const content = `Use "Tabs" for navigation and don't remove this text.`;
+
+ expect(
+ formatDocMarkdown({
+ body: `import Tabs from ${quote}./Tabs.astro${quote}\n\n${content}`,
+ data: { title: 'Title' },
+ }),
+ ).to.eql(`# Title\n\n${content}`);
+ });
+
+ test('preserves inline mentions of imports', () => {
+ const body = `You can import { Tabs } from './Tabs.astro';\nMore content.`;
+
+ expect(formatDocMarkdown({ body, data: { title: 'Title' } })).to.eql(`# Title\n\n${body}`);
+ });
+
+ test('removes imports with trailing whitespace and CRLF line endings', () => {
+ expect(
+ formatDocMarkdown({
+ body: `Before\r\n\r\nimport Tabs from './Tabs.astro'; \t\r\nAfter`,
+ data: { title: 'Title' },
+ }),
+ ).to.eql('# Title\n\nBefore\r\n\r\nAfter');
+ });
+
+ test('removes imports from the body', () => {
+ expect(
+ formatDocMarkdown({
+ body: `
+import Steps from './Steps.astro';
+
+Some content
+
+import { Button } from './Button.astro';
+import { Link } from './Link.astro';
+Lorem ipsum
+
+import {
+ Card,
+ CardHeader,
+ CardBody,
+ CardFooter,
+} from './Card.astro';
+
+Stuff
+
+ `,
+ data: { title: 'Title' },
+ }),
+ ).to.eql('# Title\n\nSome content\n\nLorem ipsum\n\nStuff');
+ });
+ });
+});
diff --git a/apps/website/src/docs/docs.markdown.ts b/apps/website/src/docs/docs.markdown.ts
new file mode 100644
index 00000000..5f05fe56
--- /dev/null
+++ b/apps/website/src/docs/docs.markdown.ts
@@ -0,0 +1,17 @@
+export function formatDocMarkdown(entry: { body?: string; data: { title: string } }) {
+ const {
+ body,
+ data: { title },
+ } = entry;
+
+ // Remove imports and their trailing blank lines without consuming quoted markdown content.
+ const bodyWithoutImports =
+ body
+ ?.replace(
+ /^[ \t]*import\s+.*?\s+from\s+(['"])[^\r\n]*?\1;?[ \t]*(?:\r?\n|$)(?:[ \t]*\r?\n)*/gms,
+ '',
+ )
+ .trim() ?? '';
+
+ return `# ${title}\n\n${bodyWithoutImports}`;
+}
diff --git a/apps/website/src/layouts/DocsLayout.astro b/apps/website/src/layouts/DocsLayout.astro
index 1b8d5375..876215a6 100644
--- a/apps/website/src/layouts/DocsLayout.astro
+++ b/apps/website/src/layouts/DocsLayout.astro
@@ -1,221 +1,321 @@
---
-import type { MarkdownHeading } from 'astro';
-import { cn } from '../utils/cn';
-import Layout from './Layout.astro';
-import { docCategories } from '../docs/docs.navigations';
-import type { DocsItem, DocsCategory } from '../docs/docs.types';
-import { getSocials } from '../socials';
-import { getDocContext, getDocUrl } from '../docs/docs.models';
-import { DOCS_LOCALES } from '../docs/docs.constants';
-import type { Locale } from '../i18n/i18n.constants';
-import { useI18n } from '../i18n/i18n';
-import DocSidenav from '../docs/components/DocSidenav.astro';
-import DocSearch from '../docs/components/DocSearch.astro';
-import DocMobileNav from '../docs/components/DocMobileNav.astro';
+import type { MarkdownHeading } from "astro";
+import { cn } from "../utils/cn";
+import Layout from "./Layout.astro";
+import { docCategories } from "../docs/docs.navigations";
+import type { DocsItem, DocsCategory } from "../docs/docs.types";
+import { getSocials } from "../socials";
+import { getDocContext, getDocUrl } from "../docs/docs.models";
+import { DOCS_LOCALES } from "../docs/docs.constants";
+import type { Locale } from "../i18n/i18n.constants";
+import { useI18n } from "../i18n/i18n";
+import DocSidenav from "../docs/components/DocSidenav.astro";
+import DocSearch from "../docs/components/DocSearch.astro";
+import DocMobileNav from "../docs/components/DocMobileNav.astro";
+import DocMarkdownActions from "../docs/components/DocMarkdownActions.astro";
type Props = {
- title?: string;
- rawTitle?: string;
- description?: string;
- docId?: string;
- locale: Locale;
- contentLocale?: Locale;
- alternateLocales?: readonly Locale[];
- headings?: MarkdownHeading[];
+ title?: string;
+ rawTitle?: string;
+ description?: string;
+ docId?: string;
+ locale: Locale;
+ contentLocale?: Locale;
+ alternateLocales?: readonly Locale[];
+ headings?: MarkdownHeading[];
};
function getFirstItem(category: DocsCategory): DocsItem | null {
- for (const section of category.sections) {
- if (section.items.length > 0) {
- return section.items[0];
+ for (const section of category.sections) {
+ if (section.items.length > 0) {
+ return section.items[0];
+ }
}
- }
- return null;
+ return null;
}
-const { title, rawTitle, description, docId, locale, contentLocale = locale, alternateLocales = DOCS_LOCALES, headings = [] } = Astro.props;
+const {
+ title,
+ rawTitle,
+ description,
+ docId,
+ locale,
+ contentLocale = locale,
+ alternateLocales = DOCS_LOCALES,
+ headings = [],
+} = Astro.props;
const { t } = useI18n({ locale });
const isFallback = contentLocale !== locale;
const context = getDocContext(docId);
-const tocHeadings = headings.filter((heading) => heading.depth >= 2 && heading.depth <= 3);
-
+const tocHeadings = headings.filter(
+ (heading) => heading.depth >= 2 && heading.depth <= 3,
+);
const socials = [
- ...getSocials().filter(social => ['github', 'bluesky', 'discord'].includes(social.id)),
-]
+ ...getSocials().filter((social) =>
+ ["github", "bluesky", "discord"].includes(social.id),
+ ),
+];
-
-const titleSuffix = 'Papra Docs';
+const titleSuffix = "Papra Docs";
const fullTitle = title ? `${title} - ${titleSuffix}` : titleSuffix;
-
---
<Layout
- rawTitle={rawTitle ?? fullTitle}
- description={description}
- locale={contentLocale}
- canonicalUrl={new URL(getDocUrl({ docId, locale: contentLocale }), Astro.site)}
- alternateLocales={alternateLocales}
- excludeFromSearch={isFallback}
- class="bg-#121212 relative"
+ rawTitle={rawTitle ?? fullTitle}
+ description={description}
+ locale={contentLocale}
+ canonicalUrl={
+ new URL(getDocUrl({ docId, locale: contentLocale }), Astro.site)
+ }
+ alternateLocales={alternateLocales}
+ excludeFromSearch={isFallback}
+ class="bg-#121212 relative"
>
- <a href="#docs-content" class="docs-skip-link rounded bg-primary text-primary-foreground px-4 py-2 font-medium">{t('docs.skip-to-content')}</a>
-
- <div class="absolute top-0 left-50% transform -translate-x-50% w-400px h-250px sm:w-700px sm:h-300px rounded-full bg-gradient-to-b from-primary/50 to-transparent blur-3xl opacity-30 z-0 pointer-events-none"></div>
+ <a
+ href="#docs-content"
+ class="docs-skip-link rounded bg-primary text-primary-foreground px-4 py-2 font-medium"
+ >
+ {t("docs.skip-to-content")}
+ </a>
- <header class="border-b sticky top-0 left-0 right-0 z-100 bg-#121212">
- <div class="h-64px border-b">
- <div class="max-w-1400px mx-auto px-6 h-full flex items-center justify-between">
- <a href={getDocUrl({ locale })} class="text-lg font-semibold group flex items-center gap-2 transition">
- <div class="i-tabler-file-text size-6 group-hover:rotate-25deg text-primary transition transform rotate-12deg"></div>
- Papra
- <span class="text-muted-foreground text-base font-light uppercase">Docs</span>
- </a>
+ <div class="absolute top-0 left-50% transform -translate-x-50% w-400px h-250px sm:w-700px sm:h-300px rounded-full bg-gradient-to-b from-primary/50 to-transparent blur-3xl opacity-30 z-0 pointer-events-none"></div>
+ <header class="border-b sticky top-0 left-0 right-0 z-100 bg-#121212">
+ <div class="h-64px border-b">
+ <div class="max-w-1400px mx-auto px-6 h-full flex items-center justify-between">
+ <a
+ href={getDocUrl({ locale })}
+ class="text-lg font-semibold group flex items-center gap-2 transition"
+ >
+ <div class="i-tabler-file-text size-6 group-hover:rotate-25deg text-primary transition transform rotate-12deg"></div>
+ Papra
+ <span class="text-muted-foreground text-base font-light uppercase">
+ Docs
+ </span>
+ </a>
- <div class="flex items-center gap-3 sm:gap-4">
- <DocSearch locale={locale} />
- {
- socials.map((social) => (
- <a href={social.url} target="_blank" rel="noopener noreferrer" class="text-muted-foreground hover:text-primary transition" aria-label={social.name}>
+ <div class="flex items-center gap-3 sm:gap-4">
+ <DocSearch locale={locale} />
+ {socials.map((social) => (
+ <a
+ href={social.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ class="text-muted-foreground hover:text-primary transition"
+ aria-label={social.name}
+ >
<div class={`${social.icon} size-5`}></div>
</a>
- ))
- }
-
+ ))}
+ </div>
</div>
</div>
- </div>
- <DocMobileNav currentDocId={docId} locale={locale} />
-
- <nav aria-label={t('docs.categories-label')} class="hidden md:block max-w-1400px mx-auto px-6 overflow-x-auto">
- <div class="flex items-center gap-8 overflow-x-auto">
- {
- docCategories.map((category) => {
- const firstItem = getFirstItem(category);
- if (!firstItem) return null;
- return (
- <a href={getDocUrl({ ...firstItem, locale })} aria-current={category === context?.category ? 'true' : undefined} class={cn("text-14px text-muted-foreground font-medium border-b border-transparent hover:border-muted-foreground transition py-2 block whitespace-nowrap h-48px flex items-center", category === context?.category ? 'border-primary text-foreground' : '')}>
- {t(category.titleKey)}
- </a>
- );
- })
- }
- </div>
- </nav>
- </header>
+ <DocMobileNav currentDocId={docId} locale={locale} />
- <div class="max-w-1400px mx-auto flex">
- {context && <DocSidenav sections={context.category.sections} currentDocId={context.item.docId} locale={locale} />}
+ <nav
+ aria-label={t("docs.categories-label")}
+ class="hidden md:block max-w-1400px mx-auto px-6 overflow-x-auto"
+ >
+ <div class="flex items-center gap-8 overflow-x-auto">
+ {docCategories.map((category) => {
+ const firstItem = getFirstItem(category);
+ if (!firstItem) return null;
+ return (
+ <a
+ href={getDocUrl({ ...firstItem, locale })}
+ aria-current={
+ category === context?.category
+ ? "true"
+ : undefined
+ }
+ class={cn(
+ "text-14px text-muted-foreground font-medium border-b border-transparent hover:border-muted-foreground transition py-2 block whitespace-nowrap h-48px flex items-center",
+ category === context?.category
+ ? "border-primary text-foreground"
+ : "",
+ )}
+ >
+ {t(category.titleKey)}
+ </a>
+ );
+ })}
+ </div>
+ </nav>
+ </header>
- <div class="flex-1 min-w-0">
- <main id="docs-content" tabindex="-1" class="max-w-728px mx-auto px-6 py-6 scroll-mt-150px">
+ <div class="max-w-1400px mx-auto flex">
{context && (
- <div class="text-sm font-bold mb-2 text-primary">
- {t(context.section.titleKey)}
- </div>
+ <DocSidenav
+ sections={context.category.sections}
+ currentDocId={context.item.docId}
+ locale={locale}
+ />
)}
- <slot />
- </main>
- </div>
- {/* Reserve the TOC column only when it has content or balances the sidenav. */}
- {(context || tocHeadings.length > 0) && (
- <aside class="max-w-300px w-full hidden xl:block flex-shrink-0 sticky top-113px h-[calc(100vh-113px)] overflow-y-auto px-6 py-6">
- {
- tocHeadings.length > 0 && (
- <nav aria-labelledby="docs-toc-heading">
- <div id="docs-toc-heading" class="text-13px font-medium mb-2">{t('docs.on-this-page')}</div>
- <ul class="border-l">
- {tocHeadings.map((heading) => (
- <li>
- <a
- href={`#${heading.slug}`}
- data-toc-link
- data-toc-slug={heading.slug}
- class={cn(
- 'block text-sm text-muted-foreground hover:text-foreground border-l border-transparent -ml-1px py-1 transition',
- heading.depth === 3 ? 'pl-7' : 'pl-4',
- )}
- >
- {heading.text}
- </a>
- </li>
- ))}
- </ul>
- </nav>
- )
- }
- </aside>
- )}
- </div>
+ <div class="flex-1 min-w-0">
+ <main
+ id="docs-content"
+ tabindex="-1"
+ class="max-w-728px mx-auto px-6 py-6 scroll-mt-150px"
+ >
+ {docId && (
+ <div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 mb-6">
+ {context && (
+ <nav
+ aria-label={t("docs.breadcrumb-label")}
+ class="min-w-0 text-sm text-muted-foreground"
+ >
+ <ol class="flex flex-wrap items-center gap-1.5">
+ <li>
+ <a
+ href={getDocUrl({
+ docId: getFirstItem(
+ context.category,
+ )?.docId,
+ locale,
+ })}
+ class="hover:text-foreground transition"
+ >
+ {t(context.category.titleKey)}
+ </a>
+ </li>
+ <li
+ aria-hidden="true"
+ class="i-tabler-chevron-right size-3"
+ ></li>
+ <li class="text-primary font-medium">
+ {t(context.section.titleKey)}
+ </li>
+ </ol>
+ </nav>
+ )}
+ <DocMarkdownActions docId={docId} locale={locale} />
+ </div>
+ )}
+ <slot />
+ </main>
+ </div>
+
+ {/* Reserve the TOC column only when it has content or balances the sidenav. */}
+ {(context || tocHeadings.length > 0) && (
+ <aside class="max-w-300px w-full hidden xl:block flex-shrink-0 sticky top-113px h-[calc(100vh-113px)] overflow-y-auto px-6 py-6">
+ {tocHeadings.length > 0 && (
+ <nav aria-labelledby="docs-toc-heading">
+ <div
+ id="docs-toc-heading"
+ class="text-13px font-medium mb-2"
+ >
+ {t("docs.on-this-page")}
+ </div>
+ <ul class="border-l">
+ {tocHeadings.map((heading) => (
+ <li>
+ <a
+ href={`#${heading.slug}`}
+ data-toc-link
+ data-toc-slug={heading.slug}
+ class={cn(
+ "block text-sm text-muted-foreground hover:text-foreground border-l border-transparent -ml-1px py-1 transition",
+ heading.depth === 3
+ ? "pl-7"
+ : "pl-4",
+ )}
+ >
+ {heading.text}
+ </a>
+ </li>
+ ))}
+ </ul>
+ </nav>
+ )}
+ </aside>
+ )}
+ </div>
</Layout>
<script>
- const HEADER_OFFSET = 150;
+ const HEADER_OFFSET = 150;
- const links = [...document.querySelectorAll<HTMLAnchorElement>('[data-toc-link]')];
- const headings = links
- .map((link) => ({ link, heading: document.getElementById(link.dataset.tocSlug ?? '') }))
- .filter((entry): entry is { link: HTMLAnchorElement; heading: HTMLElement } => entry.heading !== null);
+ const links = [
+ ...document.querySelectorAll<HTMLAnchorElement>("[data-toc-link]"),
+ ];
+ const headings = links
+ .map((link) => ({
+ link,
+ heading: document.getElementById(link.dataset.tocSlug ?? ""),
+ }))
+ .filter(
+ (
+ entry,
+ ): entry is { link: HTMLAnchorElement; heading: HTMLElement } =>
+ entry.heading !== null,
+ );
- function setActive() {
- if (headings.length === 0) {
- return;
- }
+ function setActive() {
+ if (headings.length === 0) {
+ return;
+ }
+
+ const isAtBottom =
+ window.innerHeight + window.scrollY >=
+ document.body.scrollHeight - 2;
+ const lastPassed = headings.findLast(
+ ({ heading }) =>
+ heading.getBoundingClientRect().top <= HEADER_OFFSET,
+ );
+ const active = isAtBottom
+ ? headings[headings.length - 1]
+ : (lastPassed ?? headings[0]);
- const isAtBottom = window.innerHeight + window.scrollY >= document.body.scrollHeight - 2;
- const lastPassed = headings.findLast(({ heading }) => heading.getBoundingClientRect().top <= HEADER_OFFSET);
- const active = isAtBottom ? headings[headings.length - 1] : (lastPassed ?? headings[0]);
-
- for (const { link } of headings) {
- const isActive = link === active.link;
- if (isActive) {
- link.setAttribute('aria-current', 'location');
- } else {
- link.removeAttribute('aria-current');
- }
- link.classList.toggle('border-primary', isActive);
- link.classList.toggle('text-foreground', isActive);
- link.classList.toggle('border-transparent', !isActive);
- link.classList.toggle('text-muted-foreground', !isActive);
+ for (const { link } of headings) {
+ const isActive = link === active.link;
+ if (isActive) {
+ link.setAttribute("aria-current", "location");
+ } else {
+ link.removeAttribute("aria-current");
+ }
+ link.classList.toggle("border-primary", isActive);
+ link.classList.toggle("text-foreground", isActive);
+ link.classList.toggle("border-transparent", !isActive);
+ link.classList.toggle("text-muted-foreground", !isActive);
+ }
}
- }
- if (headings.length > 0) {
- let ticking = false;
+ if (headings.length > 0) {
+ let ticking = false;
- const onScroll = () => {
- if (ticking) {
- return;
- }
+ const onScroll = () => {
+ if (ticking) {
+ return;
+ }
- ticking = true;
- requestAnimationFrame(() => {
- ticking = false;
- setActive();
- });
- };
+ ticking = true;
+ requestAnimationFrame(() => {
+ ticking = false;
+ setActive();
+ });
+ };
- setActive();
- window.addEventListener('scroll', onScroll, { passive: true });
- window.addEventListener('resize', onScroll, { passive: true });
- }
+ setActive();
+ window.addEventListener("scroll", onScroll, { passive: true });
+ window.addEventListener("resize", onScroll, { passive: true });
+ }
</script>
<style>
- .docs-skip-link {
- position: fixed;
- top: 1rem;
- left: 1rem;
- z-index: 101;
- transform: translateY(calc(-100% - 2rem));
- }
-
- .docs-skip-link:focus {
- transform: translateY(0);
- outline: 2px solid hsl(var(--ring));
- outline-offset: 2px;
- }
+ .docs-skip-link {
+ position: fixed;
+ top: 1rem;
+ left: 1rem;
+ z-index: 101;
+ transform: translateY(calc(-100% - 2rem));
+ }
+
+ .docs-skip-link:focus {
+ transform: translateY(0);
+ outline: 2px solid hsl(var(--ring));
+ outline-offset: 2px;
+ }
</style>
diff --git a/apps/website/src/locales/en.ts b/apps/website/src/locales/en.ts
index 7c503cef..e13e446a 100644
--- a/apps/website/src/locales/en.ts
+++ b/apps/website/src/locales/en.ts
@@ -364,6 +364,13 @@ export const translations = {
'docs.skip-to-content': 'Skip to content',
'docs.categories-label': 'Documentation categories',
'docs.sidebar-label': 'Documentation sidebar',
+ 'docs.breadcrumb-label': 'Breadcrumb',
+ 'docs.markdown.copy-short': 'Copy as MD',
+ 'docs.markdown.options': 'Markdown options',
+ 'docs.markdown.copy': 'Copy as Markdown',
+ 'docs.markdown.view': 'View as Markdown',
+ 'docs.markdown.copied': 'Copied!',
+ 'docs.markdown.error': 'Copy failed',
'docs.menu-label': 'Documentation menu',
'docs.on-this-page': 'On this page',
'docs.pagination-label': 'Previous and next pages',
diff --git a/apps/website/src/pages/[locale]/docs/[...slug].md.ts b/apps/website/src/pages/[locale]/docs/[...slug].md.ts
new file mode 100644
index 00000000..7571fa67
--- /dev/null
+++ b/apps/website/src/pages/[locale]/docs/[...slug].md.ts
@@ -0,0 +1,16 @@
+import type { APIRoute, InferGetStaticPropsType } from 'astro';
+import { getCollection } from 'astro:content';
+import { getDocStaticPaths } from '../../../docs/docs.models';
+import { formatDocMarkdown } from '../../../docs/docs.markdown';
+
+export async function getStaticPaths() {
+ return getDocStaticPaths(await getCollection('docs'));
+}
+
+type Props = InferGetStaticPropsType<typeof getStaticPaths>;
+
+export const GET: APIRoute<Props> = ({ props: { entry } }) =>
+ new Response(formatDocMarkdown(entry), {
+ // Display the source in browsers instead of downloading an unknown MIME type.
+ headers: { 'Content-Type': 'text/markdown; charset=utf-8' },
+ });