-
Notifications
You must be signed in to change notification settings - Fork 43
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
cmdcolin
wants to merge
2
commits into
Lodin:master
Choose a base branch
from
cmdcolin:filtering_example
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) { | ||
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 />); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 isnull
:{ name: 'no results', children: [], id: 'na', nestingLevel: 0, };
you can return
empty object
ornull
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 :)