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
1 change: 1 addition & 0 deletions apps/docs/scripts/a11y-axe-helpers.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const DEFAULT_PAGES = [
"/reference/api",
"/reference/api/schemas",
"/reference/api/users",
"/reference/api/workspaces",
"/reference/api/users/create-new-user",
"/reference/api/workspaces/list-workspaces",
"/reference/api/workspaces/create-user-workspace-by-organization",
Expand Down
57 changes: 55 additions & 2 deletions packages/docs-build/src/openapi-reference.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,19 +266,33 @@ test("the landing sections follow the sidebar's tag order, one card per operatio
{
title: "Users",
id: "users",
route: "reference/api/users",
operations: [
{ route: "reference/api/users/create-new-user", title: "Create new user", method: "post" },
{ route: "reference/api/users/get-user-by-name", title: "Get user by name", method: "get" },
{
route: "reference/api/users/create-new-user",
title: "Create new user",
method: "post",
path: "/api/v2/users",
},
{
route: "reference/api/users/get-user-by-name",
title: "Get user by name",
method: "get",
path: "/api/v2/users/{user}",
},
],
},
{
title: "Workspaces",
id: "workspaces",
route: "reference/api/workspaces",
description: "Create, list, and manage workspaces.",
operations: [
{
route: "reference/api/workspaces/list-workspaces",
title: "List workspaces",
method: "get",
path: "/api/v2/workspaces",
description: "Returns the workspaces the caller can read, filtered by the search query.",
},
],
Expand Down Expand Up @@ -462,3 +476,42 @@ test("only a deprecated operation page and card carry the deprecated flag", asyn
}
}
});

test("a tag page's source keeps its Markdown list of operations, and its section names the page", async () => {
const { source: out, reference } = await applyOpenApiReference(source, fixture);
const lines = pageContent(out.files, "reference/api/workspaces.md").split("\n");
assert.deepEqual(
lines.filter((line) => line.startsWith("- [")),
[
"- [List workspaces](./workspaces/list-workspaces.md): `GET /api/v2/workspaces`",
`- [Create user workspace by organization](./workspaces/create-user-workspace-by-organization.md): \`POST ${DEPRECATED_PATH}\``,
],
);
const section = reference.landing.sections.find((s) => s.title === "Workspaces");
assert.equal(section?.route, "reference/api/workspaces");
assert.deepEqual(
section?.operations.map((op) => op.path),
["/api/v2/workspaces", DEPRECATED_PATH],
);
});

test("a tag's description reaches its section as plain text, paragraph by paragraph", async () => {
const doc = structuredClone(swagger);
doc.tags[0].description =
"Manage [workspaces](https://example.com) with `q`.\n\nSecond *paragraph*.";
const { reference } = await applyOpenApiReference(source, doc);
const section = reference.landing.sections.find((s) => s.title === "Workspaces");
assert.equal(section?.description, "Manage workspaces with q.\n\nSecond paragraph.");
const users = reference.landing.sections.find((s) => s.title === "Users");
assert.ok(!("description" in (users ?? {})));
});

test("a tag's description is bounded before its link patterns run", async () => {
const doc = structuredClone(swagger);
doc.tags[0].description = `${"[".repeat(50_000)}\n\n${Array.from({ length: 30 }, (_, i) => `P${i}`).join("\n\n")}`;
const { reference } = await applyOpenApiReference(source, doc);
const section = reference.landing.sections.find((s) => s.title === "Workspaces");
const paragraphs = section?.description?.split("\n\n") ?? [];
assert.equal(paragraphs[0]?.length, 2000);
assert.equal(paragraphs.length, 20);
});
19 changes: 18 additions & 1 deletion packages/docs-build/src/openapi-reference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,15 +389,19 @@ export async function applyOpenApiReference(
const tag = child.path === undefined ? undefined : tagByFile.get(child.path);
const group = tag === undefined ? undefined : byTag.get(tag);
if (tag === undefined || !group) continue;
const tagText = plainParagraphs(tagInfo.get(tag));
sections.push({
title: tag,
id: landing.slugger.slug(safeHeadingId(slugify(tag))),
route: routeOf(tagFile(tag)),
...(tagText ? { description: tagText } : {}),
operations: group.ops.map((op) => {
const description = firstSentence(op.description);
return {
route: routeOf(op.file),
title: op.summary,
method: op.method,
path: op.path,
...(op.deprecated ? { deprecated: true as const } : {}),
...(description ? { description } : {}),
};
Expand Down Expand Up @@ -498,12 +502,15 @@ const inlineMarkdownText = (markdown: string): string =>
.replace(/\s+/g, " ")
.trim();

const MAX_MARKDOWN_CHARS = 2000;
const MAX_PARAGRAPHS = 20;

/** The first sentence of an operation's Markdown description, as plain text for its card. */
function firstSentence(markdown: string | undefined): string | undefined {
// The link pattern below is quadratic, and only the first 200 characters are kept.
const paragraph = markdown
?.trim()
.slice(0, 2000)
.slice(0, MAX_MARKDOWN_CHARS)
.split(/\n\s*\n/)[0];
if (!paragraph) return undefined;
const text = inlineMarkdownText(paragraph);
Expand All @@ -512,3 +519,13 @@ function firstSentence(markdown: string | undefined): string | undefined {
const space = sentence.lastIndexOf(" ", 199);
return `${sentence.slice(0, space > 0 ? space : 199)}…`;
}

/** Markdown as plain paragraphs separated by blank lines. */
function plainParagraphs(markdown: string | undefined): string | undefined {
const text = markdown
?.split(/\n\s*\n/, MAX_PARAGRAPHS)
.map((paragraph) => inlineMarkdownText(paragraph.slice(0, MAX_MARKDOWN_CHARS)))
.filter(Boolean)
.join("\n\n");
return text || undefined;
}
6 changes: 6 additions & 0 deletions packages/docs-config/src/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ export interface OpenApiLandingOperation {
route: string;
title: string;
method: HttpMethod;
/** The OpenAPI path, shown as the card's route. */
path: string;
/** Set only on a deprecated operation; the cards sort it last and mark it. */
deprecated?: true;
description?: string;
Expand All @@ -66,6 +68,10 @@ export interface OpenApiLandingOperation {
export interface OpenApiLandingSection {
title: string;
id: string;
/** The tag page's route, which shows the same cards. */
route: string;
/** The tag's description as plain paragraphs separated by blank lines, shown above its cards on the tag page. */
description?: string;
operations: OpenApiLandingOperation[];
}

Expand Down
22 changes: 19 additions & 3 deletions packages/docs-next/src/openapi/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type { RenderBody } from "../types.js";
import { AnchorRedirect } from "./anchor-redirect.js";
import { ApiPage } from "./api-page-lazy.js";
import { withCodeSamples } from "./code-samples.js";
import { ApiLanding } from "./landing.js";
import { ApiLanding, OperationCards } from "./landing.js";
import { SetupHrefProvider } from "./samples-note.js";
import { SchemaTables } from "./schemas.js";

Expand Down Expand Up @@ -124,13 +124,29 @@ export function createOpenApiRenderBody(
};
}
const anchors = data.anchors[route];
if (!anchors) return undefined;
const tag = landing.sections.find((section) => section.route === route);
if (!anchors && !tag) return undefined;
const targets: Record<string, string> = {};
for (const [anchor, target] of Object.entries(anchors)) {
for (const [anchor, target] of Object.entries(anchors ?? {})) {
const href = hrefFor(target);
if (href) targets[anchor] = href;
}
const redirect = <AnchorRedirect targets={targets} />;
if (tag) {
return {
replace: (
<>
{tag.description?.split("\n\n").map((paragraph, index) => (
// oxlint-disable-next-line react/no-array-index-key -- paragraphs can repeat and the list is static.
<p key={index}>{paragraph}</p>
))}
<h2 className="sr-only">Endpoints</h2>
<OperationCards operations={tag.operations} hrefFor={hrefFor} />
</>
),
after: redirect,
};
}
if (route !== data.schemas.route) return { after: redirect };
return {
replace: (
Expand Down
100 changes: 96 additions & 4 deletions packages/docs-next/src/openapi/landing.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,34 @@ const landing: OpenApiLanding = {
{
title: "Users",
id: "users",
route: "reference/api/users",
operations: [
{ route: "reference/api/users/create-new-user", title: "Create new user", method: "post" },
{
route: "reference/api/users/create-new-user",
title: "Create new user",
method: "post",
path: "/api/v2/users",
},
{
route: "reference/api/users/get-user-by-name",
title: "Get user by name",
method: "get",
path: "/api/v2/users/{user}",
description: "Returns one user.",
},
],
},
{
title: "Workspaces",
id: "workspaces",
route: "reference/api/workspaces",
operations: [
{ route: "reference/api/workspaces/delete", title: "Delete workspace", method: "delete" },
{
route: "reference/api/workspaces/delete",
title: "Delete workspace",
method: "delete",
path: "/api/v2/workspaces/{workspace}",
},
],
},
],
Expand All @@ -53,7 +66,7 @@ test("each tag is a section heading with a card per operation, in order", () =>
href: link?.getAttribute("href"),
name: link?.textContent,
badge: link?.querySelector("span.font-mono")?.textContent,
description: card.querySelector("p")?.textContent ?? null,
description: card.querySelector("p .coder-api-card-text")?.textContent ?? null,
};
}),
[
Expand Down Expand Up @@ -111,7 +124,14 @@ test("the landing route gets the cards after its body and their headings in its
test("a protected section id is the heading id and the TOC link, unchanged", async () => {
const reserved: OpenApiLanding = {
...landing,
sections: [{ title: "__next_f", id: "user-content-__next_f", operations: [] }],
sections: [
{
title: "__next_f",
id: "user-content-__next_f",
route: "reference/api/next",
operations: [],
},
],
};
const renderBody = createOpenApiRenderBody(async () => ({
document: {},
Expand All @@ -136,16 +156,20 @@ const deprecatedSections: OpenApiLanding["sections"] = [
{
title: "Workspaces",
id: "workspaces",
route: "reference/api/workspaces",
description: "Create, list, and manage workspaces.",
operations: [
{
route: "reference/api/workspaces/list-workspaces",
title: "List workspaces",
method: "get",
path: "/api/v2/workspaces",
},
{
route: "reference/api/workspaces/create-user-workspace-by-organization",
title: "Create user workspace by organization",
method: "post",
path: "/api/v2/organizations/{organization}/members/{user}/workspaces",
deprecated: true,
},
],
Expand All @@ -168,3 +192,71 @@ test("a deprecated operation's card is last and carries a visible Deprecated lab
);
assert.equal(last?.querySelector(".docs-deprecated-pill .sr-only")?.textContent, " endpoint");
});

test("every landing card shows its route as code beside the description", () => {
const page = renderToFragment(<ApiLanding sections={landing.sections} hrefFor={hrefFor} />);
const routes = [...page.querySelectorAll(`${CARDS} code`)].map((code) => code.textContent);
assert.deepEqual(routes, [
"/api/v2/users",
"/api/v2/users/{user}",
"/api/v2/workspaces/{workspace}",
]);
const described = page.querySelectorAll(CARDS)[1];
assert.equal(
described?.querySelector("p")?.textContent,
"/api/v2/users/{user} Returns one user.",
);
});

const tagRoute = "reference/api/workspaces";

const tagBody = async (slugs = tagRoute.split("/")) => {
const renderBody = createOpenApiRenderBody(async () => ({
document: {},
operations: {},
anchors: {},
schemas: { route: "reference/api/schemas", rows: [] },
landing: { ...landing, sections: [...landing.sections.slice(0, 1), ...deprecatedSections] },
}));
return renderBody({ versionId: undefined, slugs, hrefFor });
};

test("a tag page replaces its Markdown list with the landing's cards, deprecated last", async () => {
const result = await tagBody();
const body = renderToFragment(result?.replace);
assert.equal(body.querySelector("p")?.textContent, "Create, list, and manage workspaces.");
const cards = [...body.querySelectorAll(CARDS)];
assert.equal(cards.length, 2);
const outline = [...body.querySelectorAll("h2, [data-card]")];
assert.equal(outline[0]?.tagName, "H2");
assert.ok(outline[0]?.classList.contains("sr-only"));
assert.equal(outline[0]?.textContent, "Endpoints");
assert.equal(body.querySelectorAll("h2").length, 1);
assert.equal(cards[0]?.querySelector("h3 a")?.textContent, "List workspaces GET");
assert.equal(cards[0]?.querySelector("h3 a span.font-mono")?.textContent, "GET");
assert.equal(cards[0]?.querySelector("code")?.textContent, "/api/v2/workspaces");
assert.equal(cards[0]?.querySelector(".docs-deprecated-pill"), null);
assert.equal(
cards[1]?.querySelector("code")?.textContent,
"/api/v2/organizations/{organization}/members/{user}/workspaces",
);
assert.equal(
cards[1]?.querySelector("h3 a .docs-deprecated-pill")?.textContent,
"Deprecated endpoint",
);
assert.equal(body.querySelectorAll("ul, ol, li").length, 0, "no second list");
assert.equal(renderToFragment(result?.after).querySelectorAll("li, [data-card]").length, 0);
assert.equal(result?.toc, undefined);
});

test("a tag page links each card to the operation page it always had", async () => {
const body = renderToFragment((await tagBody())?.replace);
assert.equal(
body.querySelectorAll(CARDS)[0]?.querySelector("h3 a")?.getAttribute("href"),
"/beta-docs/reference/api/workspaces/list-workspaces/",
);
});

test("a page that is not a tag page keeps its Markdown", async () => {
assert.equal(await tagBody(["reference", "api", "nothing"]), undefined);
});
Loading
Loading