Fix OpenAPI spec rendering (#3037)

This commit is contained in:
Greg Bergé
2025-03-25 16:13:18 +01:00
committed by GitHub
parent 27de1cd01d
commit cd99ed57fb
17 changed files with 213 additions and 115 deletions
+6
View File
@@ -0,0 +1,6 @@
---
"@gitbook/react-openapi": patch
"gitbook": patch
---
Fix spec properties rendering and missing keys
+3
View File
@@ -241,6 +241,7 @@
"@scalar/oas-utils": "^0.2.120",
"clsx": "^2.1.1",
"flatted": "^3.2.9",
"json-decycle": "^4.0.0",
"json-xml-parse": "^1.3.0",
"react-aria": "^3.37.0",
"react-aria-components": "^1.6.0",
@@ -2069,6 +2070,8 @@
"json-buffer": ["json-buffer@3.0.0", "", {}, "sha512-CuUqjv0FUZIdXkHPI8MezCnFCdaTAacej1TZYulLoAg1h/PhwkdXFN4V/gzY4g+fMBCOV2xF+rp7t2XD2ns/NQ=="],
"json-decycle": ["json-decycle@4.0.0", "", {}, "sha512-3GFL/vWazCbMu1kw+NdIfAHh6Ugq5pxkKcSUnK1f/Fw1nDtt1i+BiBfRJs0iPEKscYAz4k4+osvgjY95hmuJXQ=="],
"json-parse-even-better-errors": ["json-parse-even-better-errors@2.3.1", "", {}, "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w=="],
"json-schema": ["json-schema@0.4.0", "", {}, "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="],
@@ -54,7 +54,7 @@ export function UnwrappedBlocks<TBlock extends DocumentBlock>(props: UnwrappedBl
const { nodes, blockStyle, isOffscreen: defaultIsOffscreen = false, ...contextProps } = props;
let isOffscreen = defaultIsOffscreen;
return nodes.map((node) => {
return nodes.map((node, index) => {
isOffscreen =
isOffscreen ||
isBlockOffscreen({
@@ -65,7 +65,7 @@ export function UnwrappedBlocks<TBlock extends DocumentBlock>(props: UnwrappedBl
return (
<Block
key={node.key}
key={node.key || `${node.type}-${index}`}
block={node}
style={[
'mx-auto w-full decoration-primary/6',
@@ -24,14 +24,16 @@ export function Inlines<T extends DocumentInline | DocumentText>(
) {
const { nodes, document, ancestorInlines, ...contextProps } = props;
return nodes.map((node) => {
return nodes.map((node, index) => {
const key = node.key || `key-${index}`;
if (node.object === 'text') {
return <Text key={node.key} text={node} />;
return <Text key={key} text={node} />;
}
return (
<Inline
key={node.key}
key={key}
inline={node}
document={document}
ancestorInlines={ancestorInlines}
+1
View File
@@ -16,6 +16,7 @@
"@scalar/oas-utils": "^0.2.120",
"clsx": "^2.1.1",
"flatted": "^3.2.9",
"json-decycle": "^4.0.0",
"json-xml-parse": "^1.3.0",
"react-aria-components": "^1.6.0",
"react-aria": "^3.37.0",
@@ -32,8 +32,6 @@ export function InteractiveSection(props: {
defaultTab?: string;
/** Content of the header */
header?: React.ReactNode;
/** Body of the section */
children?: React.ReactNode;
/** Children to display within the container */
overlay?: React.ReactNode;
}) {
@@ -45,7 +43,6 @@ export function InteractiveSection(props: {
tabs = [],
defaultTab = tabs[0]?.key,
header,
children,
overlay,
toggleIcon = '▶',
} = props;
@@ -83,7 +80,7 @@ export function InteractiveSection(props: {
className={className}
>
<SectionHeaderContent className={className}>
{(children || selectedTab?.body) && toggeable ? (
{selectedTab?.body && toggeable ? (
<button
{...mergeProps(buttonProps, focusProps)}
ref={triggerRef}
@@ -131,9 +128,8 @@ export function InteractiveSection(props: {
</div>
</SectionHeader>
) : null}
{(!toggeable || state.isExpanded) && (children || selectedTab?.body) ? (
{(!toggeable || state.isExpanded) && selectedTab?.body ? (
<SectionBody ref={panelRef} {...panelProps} className={className}>
{children}
{selectedTab?.body}
</SectionBody>
) : null}
@@ -148,7 +148,13 @@ function generateCodeSamples(props: {
return {
key: `default-${generator.id}`,
label: generator.label,
body: <OpenAPIMediaTypeExamplesBody data={data} renderers={renderers} />,
body: (
<OpenAPIMediaTypeExamplesBody
method={data.method}
path={data.path}
renderers={renderers}
/>
),
footer: (
<OpenAPICodeSampleFooter renderers={renderers} data={data} context={context} />
),
@@ -189,9 +195,9 @@ function OpenAPICodeSampleFooter(props: {
const { method, path } = data;
const { specUrl } = context;
const hideTryItPanel = data['x-hideTryItPanel'] || data.operation['x-hideTryItPanel'];
const hasMediaTypes = renderers.length > 0;
const hasMultipleMediaTypes = renderers.length > 1;
if (hideTryItPanel && !hasMediaTypes) {
if (hideTryItPanel && !hasMultipleMediaTypes) {
return null;
}
@@ -201,8 +207,12 @@ function OpenAPICodeSampleFooter(props: {
return (
<div className="openapi-codesample-footer">
{hasMediaTypes ? (
<OpenAPIMediaTypeExamplesSelector data={data} renderers={renderers} />
{hasMultipleMediaTypes ? (
<OpenAPIMediaTypeExamplesSelector
method={data.method}
path={data.path}
renderers={renderers}
/>
) : (
<span />
)}
@@ -3,10 +3,9 @@ import clsx from 'clsx';
import { useCallback } from 'react';
import { useStore } from 'zustand';
import type { MediaTypeRenderer } from './OpenAPICodeSample';
import type { OpenAPIOperationData } from './types';
import { getOrCreateTabStoreByKey } from './useSyncedTabsGlobalState';
function useMediaTypeState(data: OpenAPIOperationData, defaultKey: string) {
function useMediaTypeState(data: { method: string; path: string }, defaultKey: string) {
const { method, path } = data;
const store = useStore(getOrCreateTabStoreByKey(`media-type-${method}-${path}`, defaultKey));
if (typeof store.tabKey !== 'string') {
@@ -18,7 +17,7 @@ function useMediaTypeState(data: OpenAPIOperationData, defaultKey: string) {
};
}
function useMediaTypeSampleIndexState(data: OpenAPIOperationData, mediaType: string) {
function useMediaTypeSampleIndexState(data: { method: string; path: string }, mediaType: string) {
const { method, path } = data;
const store = useStore(
getOrCreateTabStoreByKey(`media-type-sample-${mediaType}-${method}-${path}`, 0)
@@ -33,14 +32,15 @@ function useMediaTypeSampleIndexState(data: OpenAPIOperationData, mediaType: str
}
export function OpenAPIMediaTypeExamplesSelector(props: {
data: OpenAPIOperationData;
method: string;
path: string;
renderers: MediaTypeRenderer[];
}) {
const { data, renderers } = props;
const { method, path, renderers } = props;
if (!renderers[0]) {
throw new Error('No renderers provided');
}
const state = useMediaTypeState(data, renderers[0].mediaType);
const state = useMediaTypeState({ method, path }, renderers[0].mediaType);
const selected = renderers.find((r) => r.mediaType === state.mediaType) || renderers[0];
return (
@@ -56,17 +56,18 @@ export function OpenAPIMediaTypeExamplesSelector(props: {
</option>
))}
</select>
<ExamplesSelector data={data} renderer={selected} />
<ExamplesSelector method={method} path={path} renderer={selected} />
</div>
);
}
function ExamplesSelector(props: {
data: OpenAPIOperationData;
method: string;
path: string;
renderer: MediaTypeRenderer;
}) {
const { data, renderer } = props;
const state = useMediaTypeSampleIndexState(data, renderer.mediaType);
const { method, path, renderer } = props;
const state = useMediaTypeSampleIndexState({ method, path }, renderer.mediaType);
if (renderer.examples.length < 2) {
return null;
}
@@ -87,25 +88,26 @@ function ExamplesSelector(props: {
}
export function OpenAPIMediaTypeExamplesBody(props: {
data: OpenAPIOperationData;
method: string;
path: string;
renderers: MediaTypeRenderer[];
}) {
const { renderers, data } = props;
const { renderers, method, path } = props;
if (!renderers[0]) {
throw new Error('No renderers provided');
}
const mediaTypeState = useMediaTypeState(data, renderers[0].mediaType);
const mediaTypeState = useMediaTypeState({ method, path }, renderers[0].mediaType);
const selected =
renderers.find((r) => r.mediaType === mediaTypeState.mediaType) ?? renderers[0];
if (selected.examples.length === 0) {
return selected.element;
}
return <ExamplesBody data={data} renderer={selected} />;
return <ExamplesBody method={method} path={path} renderer={selected} />;
}
function ExamplesBody(props: { data: OpenAPIOperationData; renderer: MediaTypeRenderer }) {
const { data, renderer } = props;
const exampleState = useMediaTypeSampleIndexState(data, renderer.mediaType);
function ExamplesBody(props: { method: string; path: string; renderer: MediaTypeRenderer }) {
const { method, path, renderer } = props;
const exampleState = useMediaTypeSampleIndexState({ method, path }, renderer.mediaType);
const example = renderer.examples[exampleState.index] ?? renderer.examples[0];
if (!example) {
throw new Error(`No example found for index ${exampleState.index}`);
+2 -2
View File
@@ -47,7 +47,7 @@ function formatPath(path: string) {
parts.push(path.slice(lastIndex, offset));
}
parts.push(
<span key={offset} className="openapi-path-variable">
<span key={`offset-${offset}`} className="openapi-path-variable">
{match}
</span>
);
@@ -61,7 +61,7 @@ function formatPath(path: string) {
const formattedPath = parts.map((part, index) => {
if (typeof part === 'string') {
return <span key={index}>{part}</span>;
return <span key={`part-${index}`}>{part}</span>;
}
return part;
});
@@ -1,6 +1,6 @@
import type { OpenAPIV3 } from '@gitbook/openapi-parser';
import { InteractiveSection } from './InteractiveSection';
import { OpenAPIRootSchema } from './OpenAPISchema';
import { OpenAPIRootSchema } from './OpenAPISchemaServer';
import type { OpenAPIClientContext } from './types';
import { checkIsReference } from './utils';
@@ -1,6 +1,6 @@
import type { OpenAPIV3 } from '@gitbook/openapi-parser';
import { OpenAPIDisclosure } from './OpenAPIDisclosure';
import { OpenAPISchemaProperties } from './OpenAPISchema';
import { OpenAPISchemaProperties } from './OpenAPISchemaServer';
import type { OpenAPIClientContext } from './types';
import { parameterToProperty, resolveDescription } from './utils';
@@ -29,9 +29,9 @@ export function OpenAPIResponse(props: {
{headers.length > 0 ? (
<OpenAPIDisclosure context={context} label="Headers">
<OpenAPISchemaProperties
properties={headers.map(([name, header]) => {
return parameterToProperty({ name, ...header });
})}
properties={headers.map(([name, header]) =>
parameterToProperty({ name, ...header })
)}
context={context}
/>
</OpenAPIDisclosure>
@@ -27,10 +27,7 @@ export function OpenAPIResponses(props: {
return {
id: statusCode,
label: (
<div
className="openapi-response-tab-content"
key={`response-${statusCode}`}
>
<div className="openapi-response-tab-content">
<span className="openapi-response-statuscode">
{statusCode}
</span>
@@ -47,7 +44,6 @@ export function OpenAPIResponses(props: {
label: contentType,
body: (
<OpenAPIResponse
key={`$response-${statusCode}-${contentType}`}
response={response}
mediaType={mediaType}
context={context}
+101 -45
View File
@@ -1,7 +1,12 @@
'use client';
// This component does not use any client feature but we don't want to
// render it server-side because it has recursion.
import type { OpenAPIV3 } from '@gitbook/openapi-parser';
import { useId } from 'react';
import clsx from 'clsx';
import { retrocycle } from 'json-decycle';
import { Markdown } from './Markdown';
import { OpenAPIDisclosure } from './OpenAPIDisclosure';
import { OpenAPISchemaName } from './OpenAPISchemaName';
@@ -10,7 +15,7 @@ import { checkIsReference, resolveDescription, resolveFirstExample } from './uti
type CircularRefsIds = Map<OpenAPIV3.SchemaObject, string>;
interface OpenAPISchemaPropertyEntry {
export interface OpenAPISchemaPropertyEntry {
propertyName?: string | undefined;
required?: boolean | undefined;
schema: OpenAPIV3.SchemaObject;
@@ -22,15 +27,10 @@ interface OpenAPISchemaPropertyEntry {
function OpenAPISchemaProperty(props: {
property: OpenAPISchemaPropertyEntry;
context: OpenAPIClientContext;
circularRefs?: CircularRefsIds;
circularRefs: CircularRefsIds;
className?: string;
}) {
const {
property,
circularRefs: parentCircularRefs = new Map<OpenAPIV3.SchemaObject, string>(),
context,
className,
} = props;
const { circularRefs: parentCircularRefs, context, className, property } = props;
const { schema } = property;
@@ -40,37 +40,43 @@ function OpenAPISchemaProperty(props: {
<div id={id} className={clsx('openapi-schema', className)}>
<OpenAPISchemaPresentation property={property} />
{(() => {
const parentCircularRef = parentCircularRefs.get(schema);
const circularRefId = parentCircularRefs.get(schema);
// Avoid recursing infinitely, and instead render a link to the parent schema
if (parentCircularRef) {
return <OpenAPISchemaCircularRef id={parentCircularRef} schema={schema} />;
if (circularRefId) {
return <OpenAPISchemaCircularRef id={circularRefId} schema={schema} />;
}
const circularRefs = parentCircularRefs.set(schema, id);
const circularRefs = new Map(parentCircularRefs);
circularRefs.set(schema, id);
const properties = getSchemaProperties(schema);
const alternatives = getSchemaAlternatives(schema, new Set(circularRefs.keys()));
return (
<>
{alternatives?.map((schema, index) => (
<OpenAPISchemaAlternative
key={index}
schema={schema}
if (properties) {
return (
<OpenAPIDisclosure context={context} label={getDisclosureLabel(schema)}>
<OpenAPISchemaProperties
properties={properties}
circularRefs={circularRefs}
context={context}
/>
))}
{properties?.length ? (
<OpenAPIDisclosure context={context} label={getDisclosureLabel(schema)}>
<OpenAPISchemaProperties
properties={properties}
circularRefs={circularRefs}
context={context}
/>
</OpenAPIDisclosure>
) : null}
</>
);
</OpenAPIDisclosure>
);
}
const ancestors = new Set(circularRefs.keys());
const alternatives = getSchemaAlternatives(schema, ancestors);
if (alternatives) {
return alternatives.map((schema, index) => (
<OpenAPISchemaAlternative
key={index}
schema={schema}
circularRefs={circularRefs}
context={context}
/>
));
}
return null;
})()}
</div>
);
@@ -79,41 +85,77 @@ function OpenAPISchemaProperty(props: {
/**
* Render a set of properties of an OpenAPI schema.
*/
export function OpenAPISchemaProperties(props: {
function OpenAPISchemaProperties(props: {
id?: string;
properties: OpenAPISchemaPropertyEntry[];
circularRefs?: CircularRefsIds;
context: OpenAPIClientContext;
}) {
const { id, properties, circularRefs, context } = props;
const {
id,
properties,
circularRefs = new Map<OpenAPIV3.SchemaObject, string>(),
context,
} = props;
return (
<div id={id} className="openapi-schema-properties">
{properties.map((property, index) => (
<OpenAPISchemaProperty
key={index}
circularRefs={circularRefs}
property={property}
context={context}
/>
))}
{properties.map((property, index) => {
return (
<OpenAPISchemaProperty
key={index}
circularRefs={circularRefs}
property={property}
context={context}
/>
);
})}
</div>
);
}
export function OpenAPISchemaPropertiesFromServer(props: {
id?: string;
properties: string;
context: OpenAPIClientContext;
}) {
return (
<OpenAPISchemaProperties
id={props.id}
properties={JSON.parse(props.properties, retrocycle())}
context={props.context}
/>
);
}
/**
* Render a root schema (such as the request body or response body).
*/
export function OpenAPIRootSchema(props: {
function OpenAPIRootSchema(props: {
schema: OpenAPIV3.SchemaObject;
context: OpenAPIClientContext;
circularRefs?: CircularRefsIds;
}) {
const { schema, context } = props;
const {
schema,
context,
circularRefs: parentCircularRefs = new Map<OpenAPIV3.SchemaObject, string>(),
} = props;
const id = useId();
const properties = getSchemaProperties(schema);
if (properties?.length) {
return <OpenAPISchemaProperties properties={properties} context={context} />;
const circularRefs = new Map(parentCircularRefs);
circularRefs.set(schema, id);
return (
<OpenAPISchemaProperties
properties={properties}
circularRefs={circularRefs}
context={context}
/>
);
}
return (
@@ -121,6 +163,19 @@ export function OpenAPIRootSchema(props: {
className="openapi-schema-root"
property={{ schema }}
context={context}
circularRefs={parentCircularRefs}
/>
);
}
export function OpenAPIRootSchemaFromServer(props: {
schema: string;
context: OpenAPIClientContext;
}) {
return (
<OpenAPIRootSchema
schema={JSON.parse(props.schema, retrocycle())}
context={props.context}
/>
);
}
@@ -136,6 +191,7 @@ function OpenAPISchemaAlternative(props: {
context: OpenAPIClientContext;
}) {
const { schema, circularRefs, context } = props;
const description = resolveDescription(schema);
const properties = getSchemaProperties(schema);
@@ -0,0 +1,34 @@
import type { OpenAPIV3 } from '@gitbook/openapi-parser';
import { decycle } from 'json-decycle';
import {
OpenAPIRootSchemaFromServer,
OpenAPISchemaPropertiesFromServer,
type OpenAPISchemaPropertyEntry,
} from './OpenAPISchema';
import type { OpenAPIClientContext } from './types';
export function OpenAPISchemaProperties(props: {
id?: string;
properties: OpenAPISchemaPropertyEntry[];
context: OpenAPIClientContext;
}) {
return (
<OpenAPISchemaPropertiesFromServer
id={props.id}
properties={JSON.stringify(props.properties, decycle())}
context={props.context}
/>
);
}
export function OpenAPIRootSchema(props: {
schema: OpenAPIV3.SchemaObject;
context: OpenAPIClientContext;
}) {
return (
<OpenAPIRootSchemaFromServer
schema={JSON.stringify(props.schema, decycle())}
context={props.context}
/>
);
}
+13 -11
View File
@@ -2,18 +2,12 @@ import type { OpenAPI } from '@gitbook/openapi-parser';
import { OpenAPIRequestBody } from './OpenAPIRequestBody';
import { OpenAPIResponses } from './OpenAPIResponses';
import { OpenAPISchemaProperties } from './OpenAPISchema';
import { OpenAPISchemaProperties } from './OpenAPISchemaServer';
import { OpenAPISecurities } from './OpenAPISecurities';
import { StaticSection } from './StaticSection';
import type { OpenAPIClientContext, OpenAPIOperationData } from './types';
import { parameterToProperty } from './utils';
/**
* Client component to render the spec for the request and response.
*
* We use a client component as rendering recursive JSON schema in the server is expensive
* (the entire schema is rendered at once, while the client component only renders the visible part)
*/
export function OpenAPISpec(props: { data: OpenAPIOperationData; context: OpenAPIClientContext }) {
const { data, context } = props;
@@ -25,13 +19,13 @@ export function OpenAPISpec(props: { data: OpenAPIOperationData; context: OpenAP
return (
<>
{securities.length > 0 ? (
<OpenAPISecurities securities={securities} context={context} />
<OpenAPISecurities key="securities" securities={securities} context={context} />
) : null}
{parameterGroups.map((group) => {
return (
<StaticSection
key={group.key}
key={`parameter-${group.key}`}
className="openapi-parameters"
header={group.label}
>
@@ -44,10 +38,18 @@ export function OpenAPISpec(props: { data: OpenAPIOperationData; context: OpenAP
})}
{operation.requestBody ? (
<OpenAPIRequestBody requestBody={operation.requestBody} context={context} />
<OpenAPIRequestBody
key="body"
requestBody={operation.requestBody}
context={context}
/>
) : null}
{operation.responses ? (
<OpenAPIResponses responses={operation.responses} context={context} />
<OpenAPIResponses
key="responses"
responses={operation.responses}
context={context}
/>
) : null}
</>
);
+3 -13
View File
@@ -137,21 +137,11 @@ export function OpenAPITabsPanels() {
const key = selectedTab.key.toString();
return (
<TabPanel key={key} id={key} className="openapi-tabs-panel">
{selectedTab.body}
<TabPanel id={key} className="openapi-tabs-panel">
<div className="openapi-tabs-body">{selectedTab.body}</div>
{selectedTab.footer ? (
<OpenAPITabsPanelFooter>{selectedTab.footer}</OpenAPITabsPanelFooter>
<div className="openapi-tabs-footer">{selectedTab.footer}</div>
) : null}
</TabPanel>
);
}
/**
* The OpenAPI Tabs panel footer component.
* This component should be used as a child of the OpenAPITabs component.
*/
function OpenAPITabsPanelFooter(props: { children: React.ReactNode }) {
const { children } = props;
return <div className="openapi-tabs-footer">{children}</div>;
}
@@ -1,6 +1,6 @@
import clsx from 'clsx';
import { OpenAPIDisclosureGroup } from '../OpenAPIDisclosureGroup';
import { OpenAPIRootSchema } from '../OpenAPISchema';
import { OpenAPIRootSchema } from '../OpenAPISchemaServer';
import { Section, SectionBody } from '../StaticSection';
import type { OpenAPIClientContext, OpenAPIContextProps, OpenAPISchemasData } from '../types';