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

feature(react-json-tree): add collapse/expand all #1410

Open
wants to merge 24 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/modern-masks-fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'react-json-tree': minor
---

Add expand/collapse all feature
15 changes: 15 additions & 0 deletions packages/react-json-tree/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,21 @@ Their full signatures are:
- `labelRenderer: function(keyPath, nodeType, expanded, expandable)`
- `valueRenderer: function(valueAsString, value, ...keyPath)`

#### Customize "Expand All/Collapse All" Buttons

Passing the `expandCollapseAll` props will activate in the top right corner of the JSONTree component the `expand all/collapse all` buttons. You can pass a JSON to customize the expand all/collapse all icons. The default icons are from [FontAwesome](https://fontawesome.com/).

```jsx
<JSONTree
expandCollapseAll={{
defaultValue: 'expand',
expandIcon: /* your custom expand icon */,
collapseIcon: /* your custom collapse icon */,
defaultIcon: /* your custom restore to default icon */,
}}
/>
```

#### More Options

- `shouldExpandNodeInitially: function(keyPath, data, level)` - determines if node should be expanded when it first renders (root is expanded by default)
Expand Down
2 changes: 1 addition & 1 deletion packages/react-json-tree/examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"react": "^18.2.0",
"react-base16-styling": "^0.9.1",
"react-dom": "^18.2.0",
"react-json-tree": "^0.18.0"
"react-json-tree": "link:.."
},
"devDependencies": {
"@babel/core": "^7.21.4",
Expand Down
7 changes: 6 additions & 1 deletion packages/react-json-tree/examples/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,12 @@ const App = () => (
Sort object keys with <code>sortObjectKeys</code> prop.
</p>
<div>
<JSONTree data={data} theme={theme} sortObjectKeys />
<JSONTree
data={data}
theme={theme}
sortObjectKeys
expandCollapseAll={{}}
/>
</div>
<p>Collapsed root node</p>
<div>
Expand Down
3 changes: 3 additions & 0 deletions packages/react-json-tree/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@
},
"dependencies": {
"@babel/runtime": "^7.21.0",
"@fortawesome/fontawesome-svg-core": "^6.4.0",
"@fortawesome/free-solid-svg-icons": "^6.4.0",
"@fortawesome/react-fontawesome": "^0.2.0",
"@types/lodash": "^4.14.194",
"react-base16-styling": "^0.9.1"
},
Expand Down
69 changes: 57 additions & 12 deletions packages/react-json-tree/src/JSONNestedNode.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React, { useCallback, useState } from 'react';
import React, { useCallback, useRef, useState } from 'react';
import ItemRange from './ItemRange';
import JSONArrow from './JSONArrow';
import getCollectionEntries from './getCollectionEntries';
import JSONNode from './JSONNode';
import ItemRange from './ItemRange';
import { useExpandCollapseAllContext } from './expandCollapseContext';
import getCollectionEntries from './getCollectionEntries';
import type { CircularCache, CommonInternalProps } from './types';

/**
Expand Down Expand Up @@ -112,23 +113,61 @@ export default function JSONNestedNode(props: Props) {
shouldExpandNodeInitially,
styling,
} = props;
const { expandAllState, setExpandAllState, setEnableDefaultButton } =
useExpandCollapseAllContext();

const [expanded, setExpanded] = useState<boolean>(
const [defaultExpanded] = useState<boolean>(
// calculate individual node expansion if necessary
isCircular ? false : shouldExpandNodeInitially(keyPath, data, level)
isCircular
? false
: (function getDefault() {
switch (expandAllState) {
case 'expand':
return true;
case 'collapse':
return false;
default:
return shouldExpandNodeInitially(keyPath, data, level);
}
})()
);

const [, setTriggerReRender] = useState<boolean>(defaultExpanded);

/**
* Used the useRef to handle expanded because calling a setState in a recursive implementation
* could lead to a "Maximum update depth exceeded" error */
const expandedRef = useRef<boolean>(defaultExpanded);

switch (expandAllState) {
case 'expand':
expandedRef.current = isCircular ? false : true;
break;
case 'collapse':
expandedRef.current = false;
break;
case 'default':
expandedRef.current = shouldExpandNodeInitially(keyPath, data, level);
break;
default: //Do nothing;
}

const handleClick = useCallback(() => {
if (expandable) setExpanded(!expanded);
}, [expandable, expanded]);
if (expandable) {
expandedRef.current = !expandedRef.current;
setTriggerReRender((e) => !e);
setEnableDefaultButton(true);
setExpandAllState(undefined);
}
}, [expandable, setEnableDefaultButton, setExpandAllState]);

const renderedChildren =
expanded || (hideRoot && level === 0)
expandedRef.current || (hideRoot && level === 0)
? renderChildNodes({ ...props, circularCache, level: level + 1 })
: null;

const itemType = (
<span {...styling('nestedNodeItemType', expanded)}>
<span {...styling('nestedNodeItemType', expandedRef.current)}>
{nodeTypeIndicator}
</span>
);
Expand All @@ -137,9 +176,15 @@ export default function JSONNestedNode(props: Props) {
data,
itemType,
createItemString(data, collectionLimit),
keyPath
keyPath,
expandedRef.current
);
const stylingArgs = [keyPath, nodeType, expanded, expandable] as const;
const stylingArgs = [
keyPath,
nodeType,
expandedRef.current,
expandable,
] as const;

return hideRoot ? (
<li {...styling('rootNode', ...stylingArgs)}>
Expand All @@ -153,7 +198,7 @@ export default function JSONNestedNode(props: Props) {
<JSONArrow
styling={styling}
nodeType={nodeType}
expanded={expanded}
expanded={expandedRef.current}
onClick={handleClick}
/>
)}
Expand Down
14 changes: 14 additions & 0 deletions packages/react-json-tree/src/createStylingFromTheme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ const getDefaultThemeStyling = (theme: Base16Theme): StylingConfig => {

return {
tree: {
position: 'relative',
border: 0,
padding: 0,
marginTop: '0.5em',
Expand All @@ -58,6 +59,19 @@ const getDefaultThemeStyling = (theme: Base16Theme): StylingConfig => {
backgroundColor: colors.BACKGROUND_COLOR,
},

expandCollapseAll: {
color: colors.TEXT_COLOR,
backgroundColor: colors.BACKGROUND_COLOR,
position: 'absolute',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
gap: '1rem',
top: '1rem',
right: '1rem',
cursor: 'pointer',
},

value: ({ style }, nodeType, keyPath) => ({
style: {
...style,
Expand Down
175 changes: 175 additions & 0 deletions packages/react-json-tree/src/expandCollapseButtons.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import {
faArrowDown,
faArrowRight,
faUndo,
faCopy,
faCheck,
} from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import React, { ReactNode, useEffect, useState } from 'react';
import { ExpandCollapseAll } from '.';
import { useExpandCollapseAllContext } from './expandCollapseContext';
import { StylingFunction } from 'react-base16-styling';

interface Props {
expandCollapseAll: ExpandCollapseAll;
styling: StylingFunction;
value: unknown;
}

interface ExpandButtonProps {
expandableDefaultValue?: 'expand' | 'collapse';
expandIcon?: ReactNode;
}

interface CollapseButtonProps {
expandableDefaultValue?: 'expand' | 'collapse';
collapseIcon?: ReactNode;
}

interface CopyToClipboardButtonProps {
copyToClipboardIcon?: ReactNode;
copiedToClipboardIcon?: ReactNode;
value: unknown;
}

interface DefaultButtonProps {
defaultIcon?: ReactNode;
}

function ExpandCollapseButtons({ expandCollapseAll, styling, value }: Props) {
const { enableDefaultButton } = useExpandCollapseAllContext();

const expandableDefaultValue = expandCollapseAll?.defaultValue || 'expand';

return (
<div {...styling('expandCollapseAll')}>
{enableDefaultButton && (
<DefaultButton defaultIcon={expandCollapseAll?.defaultIcon} />
)}

<CopyToClipboardButton
copyToClipboardIcon={expandCollapseAll?.copyToClipboardIcon}
copiedToClipboardIcon={expandCollapseAll?.copiedToClipboardIcon}
value={value}
/>

<ExpandButton
expandableDefaultValue={expandableDefaultValue}
expandIcon={expandCollapseAll?.expandIcon}
/>

<CollapseButton
expandableDefaultValue={expandCollapseAll?.defaultValue}
collapseIcon={expandCollapseAll?.collapseIcon}
/>
</div>
);
}

function ExpandButton({
expandableDefaultValue,
expandIcon,
}: ExpandButtonProps) {
const { expandAllState, setExpandAllState, setEnableDefaultButton } =
useExpandCollapseAllContext();

const onExpand = () => {
setExpandAllState('expand');
setEnableDefaultButton(true);
};

const isDefault = !expandAllState || expandAllState === 'default';

if (
expandAllState === 'collapse' ||
(isDefault && expandableDefaultValue === 'expand')
) {
return (
<div role="presentation" onClick={onExpand}>
{expandIcon || <FontAwesomeIcon icon={faArrowRight} />}
</div>
);
}

return <></>;
}

function CollapseButton({
expandableDefaultValue,
collapseIcon,
}: CollapseButtonProps) {
const { expandAllState, setExpandAllState, setEnableDefaultButton } =
useExpandCollapseAllContext();

const onCollapse = () => {
setExpandAllState('collapse');
setEnableDefaultButton(true);
};

const isDefault = !expandAllState || expandAllState === 'default';

if (
expandAllState === 'expand' ||
(isDefault && expandableDefaultValue === 'collapse')
) {
return (
<div role="presentation" onClick={onCollapse}>
{collapseIcon || <FontAwesomeIcon icon={faArrowDown} />}
</div>
);
}

return <></>;
}

function CopyToClipboardButton({
copyToClipboardIcon,
copiedToClipboardIcon,
value,
}: CopyToClipboardButtonProps) {
const [isCopied, setIsCopied] = useState(false);

const handleOnCopyToClipboard = async () => {
await navigator.clipboard.writeText(JSON.stringify(value, null, 2));
setIsCopied(true);
};

useEffect(() => {
if (isCopied) {
setTimeout(() => setIsCopied(false), 6000);
}
}, [isCopied]);

if (isCopied) {
return (
<div role="presentation" onClick={handleOnCopyToClipboard}>
{copiedToClipboardIcon || <FontAwesomeIcon icon={faCheck} />}
</div>
);
}

return (
<div role="presentation" onClick={handleOnCopyToClipboard}>
{copyToClipboardIcon || <FontAwesomeIcon icon={faCopy} />}
</div>
);
}

function DefaultButton({ defaultIcon }: DefaultButtonProps) {
const { setExpandAllState, setEnableDefaultButton } =
useExpandCollapseAllContext();

const onDefaultCollapse = () => {
setExpandAllState('default');
setEnableDefaultButton(false);
};

return (
<div role="presentation" onClick={onDefaultCollapse}>
{defaultIcon || <FontAwesomeIcon icon={faUndo} />}
</div>
);
}

export default ExpandCollapseButtons;