Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions packages/docs-next/src/copy-markdown-button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"use client";

import { buttonVariants } from "fumadocs-ui/components/ui/button";
import { useCopyButton } from "fumadocs-ui/utils/use-copy-button";
import { Check, Copy } from "lucide-react";
import { type ReactElement, useState } from "react";

// Matches the Open trigger beside it: secondary text, no outline, a filled hover.
const BUTTON_CLASS = `${buttonVariants({ variant: "ghost", size: "sm" })} gap-2 bg-transparent text-fd-muted-foreground [&_svg]:size-3.5 [&_svg]:text-fd-muted-foreground`;

const cache = new Map<string, string>();

/**
* Copies the page's markdown twin to the clipboard, fetching `markdownUrl`
* exactly as given.
*/
// Fork of fumadocs-ui 16.17.9 MarkdownCopyButton (layouts/shared/page-actions.tsx) without its BASE_URL prefix.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: #370 moves fumadocs-ui to 16.19.0, and the other fork notes there were rechecked against it. Whichever of the two lands second should update this provenance note to 16.19.0 after diffing against 16.19.0's MarkdownCopyButton. That way the next audit has an accurate baseline. I found no behaviour change in the copy path between the two versions.

export function CopyMarkdownButton({
markdownUrl,
}: {
/** The page's markdown twin, root-relative and carrying the base path. */
markdownUrl: string;
}): ReactElement {
const [isLoading, setLoading] = useState(false);
const [checked, onClick] = useCopyButton(async () => {
const cached = cache.get(markdownUrl);
if (cached !== undefined) return navigator.clipboard.writeText(cached);
setLoading(true);
try {
await navigator.clipboard.write([
new ClipboardItem({
"text/plain": fetch(markdownUrl).then(async (res) => {
if (!res.ok) throw new Error(`Failed to fetch ${markdownUrl}: ${res.status}`);
const content = await res.text();
if (process.env.NODE_ENV === "production") cache.set(markdownUrl, content);
return content;
}),
}),
]);
} finally {
setLoading(false);
}
});

return (
<button
type="button"
disabled={isLoading}
aria-live="polite"
onClick={onClick}
className={BUTTON_CLASS}
>
{checked ? <Check /> : <Copy />}
{checked ? "Copied Markdown" : "Copy Markdown"}
</button>
);
}
12 changes: 7 additions & 5 deletions packages/docs-next/src/page-actions.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import { renderToFragment } from "../test/dom.js";
import { PageActions } from "./page-actions.js";
import { ViewOptions } from "./view-options.js";

const MARKDOWN_URL = "/beta-docs/v2.36/admin/users.md";
const PAGE_PATH = "/beta-docs/v2.36/admin/users/";
const MARKDOWN_URL = "/docs/v2.36/admin/users.md";
const PAGE_PATH = "/docs/v2.36/admin/users/";
const PAGE_URL = `https://coder.com${PAGE_PATH}`;

// fumadocs' copy button reads the current pathname through `fumadocs-core`'s
Expand Down Expand Up @@ -37,7 +37,9 @@ test("the row renders Copy Markdown and the Open dropdown trigger", () => {
assert.deepEqual(buttonLabels(root), ["Copy Markdown", "Open"]);
});

test("Copy Markdown copies the page's markdown twin", async (t) => {
test("Copy Markdown fetches the markdown twin under the base path exactly once", async (t) => {
// test/bundler-env.mjs gives fumadocs the bundle's BASE_URL, which its own
// copy button prefixed onto this already-prefixed URL.
const fetched: string[] = [];
t.mock.method(globalThis, "fetch", async (input: string) => {
fetched.push(input);
Expand Down Expand Up @@ -106,7 +108,7 @@ function pathsOf(root: ParentNode): (string | null)[] {
}

test("the Open trigger carries the shared dropdown caret, so it reads as a dropdown", () => {
const root = renderToFragment(<ViewOptions markdownUrl="/beta-docs/admin/users.md" />);
const root = renderToFragment(<ViewOptions markdownUrl="/docs/admin/users.md" />);
const trigger = root.querySelector("button");
assert.ok(trigger, "the trigger renders");
assert.equal(trigger.textContent, "Open");
Expand Down Expand Up @@ -177,7 +179,7 @@ test("opening the dropdown lists every item, addressed at the page the reader is
items.map((item) => item.getAttribute("href")),
[
// The twin resolves against the page, so it keeps the base path.
"https://coder.com/beta-docs/v2.36/admin/users.md",
"https://coder.com/docs/v2.36/admin/users.md",
`https://scira.ai/?q=${encoded}`,
`https://chatgpt.com/?prompt=${encoded}&hints=search`,
`https://claude.ai/new?q=${encoded}`,
Expand Down
18 changes: 9 additions & 9 deletions packages/docs-next/src/page-actions.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MarkdownCopyButton } from "fumadocs-ui/layouts/docs/page";
import type { ReactElement } from "react";
import { CopyMarkdownButton } from "./copy-markdown-button.js";
import { ViewOptions } from "./view-options.js";

/**
Expand All @@ -11,15 +11,18 @@ import { ViewOptions } from "./view-options.js";
export type PageActionsOption = false | { viewOptions?: boolean };

/**
* The row of page actions under the page description: fumadocs' Copy Markdown
* button and our own "Open in ..." dropdown, both pointed at the page's
* markdown twin.
* The row of page actions under the page description: our own Copy Markdown
* button and "Open in ..." dropdown, both pointed at the page's markdown twin.
*
* `markdownUrl` is root-relative and carries the site's base path.
* `MarkdownCopyButton` fetches it and the dropdown links to it as an anchor
* `CopyMarkdownButton` fetches it and the dropdown links to it as an anchor
* href, so the browser resolves it against the page's own origin and no
* hostname is ever baked into the build.
*
* The copy button is ours rather than fumadocs' `MarkdownCopyButton` because
* that one prefixes the bundler's `import.meta.env.BASE_URL`, which doubles a
* URL that already carries the base path.
*
* The dropdown is ours rather than fumadocs' `ViewOptionsPopover` because its
* assistant prompts name the page's Markdown twin rather than the HTML page,
* and it marks only the items that leave the docs (refer to
Expand All @@ -38,10 +41,7 @@ export function PageActions({
if (options === false) return null;
return (
<div className={["flex flex-row items-center gap-2", className].filter(Boolean).join(" ")}>
<MarkdownCopyButton
markdownUrl={markdownUrl}
className="border-0 bg-transparent text-fd-muted-foreground"
/>
<CopyMarkdownButton markdownUrl={markdownUrl} />
{options.viewOptions === false ? undefined : <ViewOptions markdownUrl={markdownUrl} />}
</div>
);
Expand Down
15 changes: 15 additions & 0 deletions packages/docs-next/test/bundler-env.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// ESM loader hook: give fumadocs' modules the `import.meta.env.BASE_URL` that
// Next's bundler inlines on the site (`"/docs/"` in production), so anything of
// theirs that prefixes it behaves here as it does in the browser. Set
// DOCS_NEXT_TEST_BASE_URL="/" to run a test as a root-served build, such as a
// preview or the offline export.
const FUMADOCS = /\/node_modules\/fumadocs-(?:ui|core)\/dist\/.+\.js$/;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: the hook injects BASE_URL into every fumadocs-ui and fumadocs-core module for every docs-next test, not just the page-actions test. That's the right default because it matches production. But a test that needs the root-served case (previews, offlinedocs, where BASE_URL is /) has no way to get it. You could read the value from an env var with /beta-docs/ as the default, so a future test can opt into /. It isn't needed for this PR.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied in 4e2949a. The hook now reads DOCS_NEXT_TEST_BASE_URL, so a test can opt into /. It defaults to /docs/ rather than /beta-docs/, because /docs/ is the base path production uses now, and the page-actions tests use /docs URLs to match. The regression test still fails on the old page-actions.tsx (/docs/docs/v2.36/admin/users.md). With DOCS_NEXT_TEST_BASE_URL=/, the old code passes, the same as a root-served build. docs-next 367/367, lint and typecheck clean.

const BASE_URL = process.env.DOCS_NEXT_TEST_BASE_URL ?? "/docs/";

export async function load(url, context, nextLoad) {
const result = await nextLoad(url, context);
if (result.format !== "module" || result.source === undefined || !FUMADOCS.test(url))
return result;
const env = `import.meta.env = { BASE_URL: ${JSON.stringify(BASE_URL)} };\n`;
return { ...result, source: env + String(result.source) };
}
1 change: 1 addition & 0 deletions packages/docs-next/test/setup.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ import { register } from "node:module";

register("./ignore-css.mjs", import.meta.url);
register("./mock-next-navigation.mjs", import.meta.url);
register("./bundler-env.mjs", import.meta.url);
Loading