Skip to content
Merged
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
37 changes: 33 additions & 4 deletions src/components/JsonSchemaViewer.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { isRegularNode, SchemaTree as JsonSchemaTree, SchemaTreeRefDereferenceFn } from '@stoplight/json-schema-tree';
import {
isRegularNode,
RootNode,
SchemaNode,
SchemaTree as JsonSchemaTree,
SchemaTreeRefDereferenceFn,
} from '@stoplight/json-schema-tree';
import { Box, Provider as MosaicProvider } from '@stoplight/mosaic';
import { ErrorBoundaryForwardedProps, FallbackProps, withErrorBoundary } from '@stoplight/react-error-boundary';
import cn from 'classnames';
Expand All @@ -14,6 +20,7 @@ export type JsonSchemaProps = Partial<JSVOptions> & {
emptyText?: string;
className?: string;
resolveRef?: SchemaTreeRefDereferenceFn;
onTreePopulated?: (props: { rootNode: RootNode; nodeCount: number }) => void;
};

const JsonSchemaViewerComponent: React.FC<JsonSchemaProps & ErrorBoundaryForwardedProps> = ({
Expand All @@ -26,13 +33,16 @@ const JsonSchemaViewerComponent: React.FC<JsonSchemaProps & ErrorBoundaryForward
onGoToRef,
renderRowAddon,
hideExamples,
onTreePopulated,
}) => {
const jsonSchemaTreeRoot = React.useMemo(() => {
const { jsonSchemaTreeRoot, nodeCount } = React.useMemo(() => {
const jsonSchemaTree = new JsonSchemaTree(schema, {
mergeAllOf: true,
refResolver: resolveRef,
});
jsonSchemaTree.walker.hookInto('filter', node => {

let nodeCount = 0;
const shouldNodeBeIncluded = (node: SchemaNode) => {
if (!isRegularNode(node)) return true;

const { validations } = node;
Expand All @@ -42,9 +52,21 @@ const JsonSchemaViewerComponent: React.FC<JsonSchemaProps & ErrorBoundaryForward
}

return !((viewMode === 'read' && !!validations.writeOnly) || (viewMode === 'write' && !!validations.readOnly));
};

jsonSchemaTree.walker.hookInto('filter', node => {
if (shouldNodeBeIncluded(node)) {
nodeCount++;
return true;
}
return false;
});
jsonSchemaTree.populate();
return jsonSchemaTree.root;

return {
jsonSchemaTreeRoot: jsonSchemaTree.root,
nodeCount,
};
}, [schema, resolveRef, viewMode]);

const isEmpty = React.useMemo(() => jsonSchemaTreeRoot.children.every(node => !isRegularNode(node) || node.unknown), [
Expand All @@ -59,6 +81,13 @@ const JsonSchemaViewerComponent: React.FC<JsonSchemaProps & ErrorBoundaryForward
hideExamples,
]);

React.useEffect(() => {
onTreePopulated?.({
rootNode: jsonSchemaTreeRoot,
nodeCount: nodeCount,
});
}, [jsonSchemaTreeRoot, onTreePopulated, nodeCount]);

if (isEmpty) {
return <Box className={cn(className, 'JsonSchemaViewer', 'sl-text-sm')}>{emptyText}</Box>;
}
Expand Down