Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: openapi spec driven api ref #790

Draft
wants to merge 15 commits into
base: main
Choose a base branch
from
133 changes: 133 additions & 0 deletions components/ApiReference/ApiReference.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import Link from "next/link";
import { ApiReferenceProvider } from "../../components/ApiReference/ApiReferenceContext";
import { ApiReferenceSection } from "../../components/ApiReference";
import MinimalHeader from "../../components/Header/MinimalHeader";
import Sidebar from "../../components/Sidebar";
import { Page } from "../../layouts/Page";
import { useEffect, useLayoutEffect } from "react";
import { useRouter } from "next/router";
import { StainlessConfig } from "../../lib/openApiSpec";
import { OpenAPIV3 } from "@scalar/openapi-types";
import { getSidebarContent } from "./helpers";
import { SidebarSection } from "../../data/types";

type Props = {
name: string;
openApiSpec: OpenAPIV3.Document;
stainlessSpec: StainlessConfig;
preContent?: React.ReactNode;
preSidebarContent?: SidebarSection[];
resourceOrder: string[];
};

function ApiReference({
name,
openApiSpec,
stainlessSpec,
preContent,
preSidebarContent,
resourceOrder = [],
}: Props) {
const router = useRouter();
const basePath = router.pathname.split("/")[1];

useEffect(() => {
const path = router.asPath;

const resourcePath = path.replace(`/${basePath}`, "");
const element = document.querySelector(
`[data-resource-path="${resourcePath}"]`,
);

if (element) {
setTimeout(() => {
element.scrollIntoView();
}, 200);
}
}, [router.asPath, basePath]);

useLayoutEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const resourcePath =
entry.target.getAttribute("data-resource-path");
if (resourcePath) {
window.history.replaceState(
null,
"",
`/${basePath}${resourcePath}`,
);
}
}
});
},
{
threshold: 0.1,
rootMargin: "-64px 0px -80% 0px",
},
);

// Observe all elements with data-resource-path
document.querySelectorAll("[data-resource-path]").forEach((element) => {
observer.observe(element);
});

// Cleanup observer on unmount
return () => observer.disconnect();
}, [basePath]);

return (
<ApiReferenceProvider
openApiSpec={openApiSpec}
stainlessConfig={stainlessSpec}
>
<div className="wrapper">
<Page
header={<MinimalHeader pageType="API" />}
sidebar={
<Sidebar
content={getSidebarContent(
openApiSpec,
stainlessSpec,
resourceOrder,
basePath,
preSidebarContent,
)}
>
<Link
href="/"
passHref
className="text-sm block font-medium text-gray-500 hover:text-gray-900 dark:text-gray-300 dark:hover:text-gray-100"
>
&#8592; Back to docs
</Link>
</Sidebar>
}
metaProps={{
title: `Knock ${name} Reference | Knock`,
description: `Complete reference documentation for the Knock ${name}.`,
}}
>
<div className="w-full max-w-5xl lg:flex mx-auto relative">
<div className="w-full flex-auto">
<div className="docs-content api-docs-content">
{preContent}
{resourceOrder.map((resourceName) => (
<ApiReferenceSection
key={resourceName}
resourceName={resourceName}
resource={stainlessSpec.resources[resourceName]}
/>
))}
</div>
</div>
</div>
</Page>
</div>
</ApiReferenceProvider>
);
}

export default ApiReference;
47 changes: 47 additions & 0 deletions components/ApiReference/ApiReferenceContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { createContext, useContext, ReactNode } from "react";
import { OpenAPIV3 } from "@scalar/openapi-types";
import { StainlessConfig } from "../../lib/openApiSpec";

interface ApiReferenceContextType {
openApiSpec: OpenAPIV3.Document;
stainlessConfig: StainlessConfig;
baseUrl: string;
}

const ApiReferenceContext = createContext<ApiReferenceContextType | undefined>(
undefined,
);

interface ApiReferenceProviderProps {
children: ReactNode;
openApiSpec: OpenAPIV3.Document;
stainlessConfig: StainlessConfig;
}

export function ApiReferenceProvider({
children,
openApiSpec,
stainlessConfig,
}: ApiReferenceProviderProps) {
const baseUrl = stainlessConfig.environments.production;

return (
<ApiReferenceContext.Provider
value={{ openApiSpec, stainlessConfig, baseUrl }}
>
{children}
</ApiReferenceContext.Provider>
);
}

export function useApiReference() {
const context = useContext(ApiReferenceContext);
if (context === undefined) {
throw new Error(
"useApiReference must be used within an ApiReferenceProvider",
);
}
return context;
}

export default ApiReferenceContext;
135 changes: 135 additions & 0 deletions components/ApiReference/ApiReferenceMethod/ApiReferenceMethod.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import type { OpenAPIV3 } from "@scalar/openapi-types";
import { useState } from "react";
import Markdown from "react-markdown";

import { Endpoint } from "../../Endpoints";
import { ContentColumn, ExampleColumn, Section } from "../../ApiSections";
import { CodeBlock } from "../../CodeBlock";
import { useApiReference } from "../ApiReferenceContext";
import { SchemaProperties } from "../SchemaProperties";
import OperationParameters from "../OperationParameters/OperationParameters";
import { PropertyRow } from "../SchemaProperties/PropertyRow";
import MultiLangExample from "../MultiLangExample";
import { augmentSnippetsWithCurlRequest } from "../helpers";

type Props = {
methodName: string;
methodType: "get" | "post" | "put" | "delete";
endpoint: string;
};

function ApiReferenceMethod({ methodName, methodType, endpoint }: Props) {
const { openApiSpec, baseUrl } = useApiReference();
const [isResponseExpanded, setIsResponseExpanded] = useState(false);
const method = openApiSpec.paths?.[endpoint]?.[methodType];

if (!method) {
return null;
}

const parameters = method.parameters || [];
const responses = method.responses || {};
const response = responses[Object.keys(responses)[0]];

const pathParameters = parameters.filter(
(p) => p.in === "path",
) as OpenAPIV3.ParameterObject[];
const queryParameters = parameters.filter(
(p) => p.in === "query",
) as OpenAPIV3.ParameterObject[];

const responseSchema: OpenAPIV3.SchemaObject | undefined =
response?.content?.["application/json"]?.schema;
const requestBody: OpenAPIV3.SchemaObject | undefined =
method.requestBody?.content?.["application/json"]?.schema;

return (
<Section title={method.summary} slug={method.summary}>
<ContentColumn>
<Markdown>{method.description ?? ""}</Markdown>

<h3 className="!text-sm font-medium">Endpoint</h3>

<Endpoint
method={methodType.toUpperCase()}
path={`${baseUrl}${endpoint}`}
name={methodName}
/>

{pathParameters.length > 0 && (
<>
<h3 className="!text-base font-medium">Path parameters</h3>
<OperationParameters parameters={pathParameters} />
</>
)}

{queryParameters.length > 0 && (
<>
<h3 className="!text-base font-medium">Query parameters</h3>
<OperationParameters parameters={queryParameters} />
</>
)}

{requestBody && (
<>
<h3 className="!text-base font-medium">Request body</h3>
<SchemaProperties schema={requestBody} />
</>
)}

<h3 className="!text-base font-medium">Returns</h3>

{responseSchema && (
<PropertyRow.Wrapper>
<PropertyRow.Container>
<PropertyRow.Header>
<PropertyRow.Type>{responseSchema.title}</PropertyRow.Type>
</PropertyRow.Header>
<PropertyRow.Description>
<Markdown>{responseSchema.description ?? ""}</Markdown>
</PropertyRow.Description>

{responseSchema.properties && (
<>
<PropertyRow.ExpandableButton
isOpen={isResponseExpanded}
onClick={() => setIsResponseExpanded(!isResponseExpanded)}
>
{isResponseExpanded ? "Hide properties" : "Show properties"}
</PropertyRow.ExpandableButton>

{isResponseExpanded && (
<PropertyRow.ChildProperties>
<SchemaProperties schema={responseSchema} hideRequired />
</PropertyRow.ChildProperties>
)}
</>
)}
</PropertyRow.Container>
</PropertyRow.Wrapper>
)}
</ContentColumn>
<ExampleColumn>
<MultiLangExample
title={`${method.summary} (example)`}
examples={augmentSnippetsWithCurlRequest(
method["x-stainless-snippets"],
{
baseUrl,
methodType,
endpoint,
body: requestBody?.example,
},
)}
/>
{responseSchema?.example && (
<CodeBlock title="Response" language="json" languages={["json"]}>
{JSON.stringify(responseSchema?.example, null, 2)}
</CodeBlock>
)}
</ExampleColumn>
</Section>
);
}

export default ApiReferenceMethod;
1 change: 1 addition & 0 deletions components/ApiReference/ApiReferenceMethod/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "./ApiReferenceMethod";
Loading
Loading