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

Filtering example #61

Open
wants to merge 2 commits into
base: master
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
202 changes: 202 additions & 0 deletions __stories__/FilteringVariableSizeTree.story.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
/* eslint-disable max-depth */
import {number, withKnobs} from '@storybook/addon-knobs';
import {storiesOf} from '@storybook/react';
import React, {FC, useState, useCallback, useEffect, useRef} from 'react';
import AutoSizer from 'react-virtualized-auto-sizer';
import {
TreeWalker,
TreeWalkerValue,
VariableSizeNodeData,
VariableSizeNodePublicState,
VariableSizeTree,
} from '../src';
import {NodeComponentProps} from '../src/Tree';

document.body.style.margin = '0';
document.body.style.display = 'flex';
document.body.style.minHeight = '100vh';

const root = document.getElementById('root')!;
root.style.margin = '10px 0 0 10px';
root.style.flex = '1';

type TreeNode = Readonly<{
children: TreeNode[];
id: number;
name: string;
}>;

type NodeMeta = Readonly<{
nestingLevel: number;
node: TreeNode;
}>;

type ExtendedData = VariableSizeNodeData &
Readonly<{
isLeaf: boolean;
name: string;
nestingLevel: number;
}>;

let nodeId = 0;

const createNode = (depth: number = 0) => {
const node: TreeNode = {
children: [],
id: nodeId,
name: `test-${nodeId}`,
};

nodeId += 1;

if (depth === 5) {
return node;
}

for (let i = 0; i < 10; i++) {
node.children.push(createNode(depth + 1));
}

return node;
};

const rootNode = createNode();
const defaultGapStyle = {marginLeft: 10};
const defaultButtonStyle = {fontFamily: 'Courier New'};

const Node: FC<NodeComponentProps<
ExtendedData,
VariableSizeNodePublicState<ExtendedData>
>> = ({data: {isLeaf, name, nestingLevel}, isOpen, style, setOpen}) => {
return (
<div
style={{
...style,
alignItems: 'center',
background: isLeaf ? '#fdd' : '#ddd',
display: 'flex',
marginLeft: nestingLevel * 30 + (isLeaf ? 48 : 0),
}}
>
{!isLeaf && (
<div>
<button
type="button"
onClick={() => setOpen(!isOpen)}
style={defaultButtonStyle}
>
{isOpen ? '-' : '+'}
</button>
</div>
)}
<div style={defaultGapStyle}>{name}</div>
</div>
);
};

type TreePresenterProps = Readonly<{
itemSize: number;
}>;

const getNodeData = (
node: TreeNode,
nestingLevel: number,
): TreeWalkerValue<ExtendedData, NodeMeta> => ({
data: {
defaultHeight: node.children.length === 0 ? 30 : 60,
id: node.id.toString(),
isLeaf: node.children.length === 0,
isOpenByDefault: true,
name: node.name,
nestingLevel,
},
nestingLevel,
node,
});

let i = 0;
function filterTree(tree: TreeNode, text: string) {
if (tree.children.length) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this PR.

What if there are multiple root nodes?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my understanding is that when there are multiple root nodes, you would probably still have a top level root with tree.children.length, it is just that the tree walker doesn't yield the root level node https://github.com/Lodin/react-vtree/blob/master/__stories__/MultipleRoots.story.tsx#L84-L86

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Easy solution:

Call filterTree for each root.

And instead of return your template when result is null:
{ name: 'no results', children: [], id: 'na', nestingLevel: 0, };

you can return empty object or null and filter it later from filtered result. It looks more better when you just hide empty nodes instead of comment each as 'no results'

Anyway thank you for this. I used it as base for my own filter solution.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any way to filter but keep the opened nodes? If we set isOpenByDefault to false (so we start with the tree not expanded), and we expand some nodes, and then filter, the nodes will not remain expanded. Any way to avoid this?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nervermind, we can use the async prop for the tree and it keeps the nodes open, don't mind me :)

const subtree = {
...tree,
children: tree.children
.map((child) => filterTree(child, text))
.filter((child) => !!child),
};

return subtree.children.length ? subtree : null;
}

return tree.name.startsWith(text) ? tree : null;
}

const TreePresenter: FC<TreePresenterProps> = () => {
const tree = useRef<VariableSizeTree<ExtendedData>>(null);
const [filter, setFilter] = useState('');
const filteredRootNode = filterTree(rootNode, filter) || {
name: 'no results',
children: [],
id: 'na',
nestingLevel: 0,
};
i = 0;

const treeWalker = useCallback(
function* treeWalker(): ReturnType<TreeWalker<ExtendedData, NodeMeta>> {
yield getNodeData(filteredRootNode, 0);

// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
while (true) {
const parentMeta = yield;

// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < parentMeta.node.children.length; i++) {
yield getNodeData(
parentMeta.node.children[i],
parentMeta.nestingLevel + 1,
);
}
}
},
[filteredRootNode],
);

useEffect(() => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
tree.current?.recomputeTree({
refreshNodes: true,
useDefaultHeight: true,
});
// Important, recompute tree on filter text changing
}, [filter]);

return (
<>
<label htmlFor="filter">Filter</label>
<input
id="filter"
type="text"
onChange={(event) => {
setFilter(event.target.value);
}}
value={filter}
/>
<AutoSizer disableWidth>
{({height}) => (
<VariableSizeTree
ref={tree}
treeWalker={treeWalker}
height={height}
width="100%"
>
{Node}
</VariableSizeTree>
)}
</AutoSizer>
</>
);
};

storiesOf('Tree', module)
.addDecorator(withKnobs)
.add('FilteringVariableSizeTree', () => <TreePresenter />);
1 change: 1 addition & 0 deletions __stories__/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import './FixedSizeTree.story';
import './VariableSizeTree.story';
import './FilteringVariableSizeTree.story';
import './MultipleRoots.story';
import './AsyncData.story';
import './AsyncDataIdle.story';
Expand Down