fix: Expand/Collapse all buttons disappears for flat structures (#1424)

Co-authored-by: AvroraPolnareff <araintheskywith@gmail.com>
Co-authored-by: Roman Hotsiy <gotsijroman@gmail.com>
Co-authored-by: anastasiia-developer <anastasiia@redocly.com>
This commit is contained in:
AvroraPolnareff 2022-04-26 13:36:14 +03:00 committed by GitHub
parent 8240404a55
commit 2ca8e081ba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 21 deletions

View File

@ -26,27 +26,37 @@ class Json extends React.PureComponent<JsonProps> {
return <CopyButtonWrapper data={this.props.data}>{this.renderInner}</CopyButtonWrapper>; return <CopyButtonWrapper data={this.props.data}>{this.renderInner}</CopyButtonWrapper>;
} }
renderInner = ({ renderCopyButton }) => ( renderInner = ({ renderCopyButton }) => {
<JsonViewerWrap> const showFoldingButtons = this.props.data && Object.values(this.props.data).some(
<SampleControls> (value) => typeof value === 'object' && value !== null,
{renderCopyButton()} );
<button onClick={this.expandAll}> Expand all </button>
<button onClick={this.collapseAll}> Collapse all </button> return (
</SampleControls> <JsonViewerWrap>
<OptionsContext.Consumer> <SampleControls>
{options => ( {renderCopyButton()}
<PrismDiv {showFoldingButtons &&
className={this.props.className} <>
// tslint:disable-next-line <button onClick={this.expandAll}> Expand all </button>
ref={node => (this.node = node!)} <button onClick={this.collapseAll}> Collapse all </button>
dangerouslySetInnerHTML={{ </>
__html: jsonToHTML(this.props.data, options.jsonSampleExpandLevel), }
}} </SampleControls>
/> <OptionsContext.Consumer>
)} {options => (
</OptionsContext.Consumer> <PrismDiv
</JsonViewerWrap> className={this.props.className}
); // tslint:disable-next-line
ref={node => (this.node = node!)}
dangerouslySetInnerHTML={{
__html: jsonToHTML(this.props.data, options.jsonSampleExpandLevel),
}}
/>
)}
</OptionsContext.Consumer>
</JsonViewerWrap>
);
};
expandAll = () => { expandAll = () => {
const elements = this.node.getElementsByClassName('collapsible'); const elements = this.node.getElementsByClassName('collapsible');

View File

@ -42,5 +42,13 @@ describe('Components', () => {
expect(ClipboardService.copySelected as jest.Mock).toHaveBeenCalled(); expect(ClipboardService.copySelected as jest.Mock).toHaveBeenCalled();
}); });
test('Expand/Collapse buttons disappears for flat structures', () => {
const flatData = { a: 1, b: '2', c: null };
const flatDataComponent = mount(withTheme(<JsonViewer data={flatData} />));
expect(flatDataComponent.html()).not.toContain('Expand all');
expect(flatDataComponent.html()).not.toContain('Collapse all');
});
}); });
}); });