feat: scroll to top when search key changes

This commit is contained in:
EnixCoda 2019-08-11 21:40:30 +08:00
parent 5f6feeff00
commit d5241e2f1c
No known key found for this signature in database
GPG key ID: 0C1A07377913A1DD
3 changed files with 19 additions and 15 deletions

View file

@ -11,6 +11,7 @@ import { TreeData, MetaData } from 'utils/GitHubHelper'
import { VisibleNodes, TreeNode } from 'utils/VisibleNodesGenerator'
import Icon from './Icon'
import SizeObserver from './SizeObserver'
import { usePrevious } from 'utils/hooks'
export type Props = {
treeData?: TreeData
@ -53,8 +54,8 @@ class FileExplorer extends React.Component<Props & ConnectorState> {
}
renderFiles(visibleNodes: VisibleNodes) {
const { nodes } = visibleNodes
const { searchKey, focusedNode } = this.props
const { nodes, focusedNode } = visibleNodes
const { searchKey } = this.props
const inSearch = searchKey !== ''
if (inSearch && nodes.length === 0) {
return <label className={'no-results'}>No results found.</label>
@ -76,12 +77,17 @@ class FileExplorer extends React.Component<Props & ConnectorState> {
}>(({ nodes, width, height, focusedNode }) => {
const listRef = React.useRef<List>(null)
React.useEffect(() => {
const { visibleNodes } = this.props
const nodes = visibleNodes && visibleNodes.nodes
if (nodes && focusedNode && listRef.current) {
if (focusedNode && listRef.current) {
listRef.current.scrollToItem(nodes.indexOf(focusedNode), 'smart')
}
}, [listRef.current, focusedNode])
const lastNodeLength = usePrevious(nodes.length)
React.useEffect(() => {
if (listRef.current && !focusedNode && lastNodeLength !== nodes.length) {
listRef.current.scrollTo(0)
}
}, [listRef.current, focusedNode, nodes.length])
return (
<List
ref={listRef}

View file

@ -16,7 +16,6 @@ export type ConnectorState = {
visibleNodes: VisibleNodes | null
searchKey: string
searched: boolean
focusedNode: TreeNode | null
init: () => void
execAfterRender: () => void
@ -312,9 +311,6 @@ const goTo: MethodCreator<Props, ConnectorState, [string[]]> = dispatch => async
const nodeExpandedTo = visibleNodesGenerator.expandTo(currentPath.join('/'))
if (nodeExpandedTo) {
visibleNodesGenerator.focusNode(nodeExpandedTo)
dispatch.set({
focusedNode: nodeExpandedTo,
})
}
dispatch.call(updateVisibleNodes)
})
@ -345,12 +341,6 @@ const focusNode: MethodCreator<Props, ConnectorState, [TreeNode | null, boolean]
dispatch.get(({ visibleNodes }) => {
if (!visibleNodes) return
visibleNodesGenerator.focusNode(node)
if (node && !skipScroll) {
// when focus a node not in viewport(by keyboard), scroll to it
dispatch.set({
focusedNode: node,
})
}
dispatch.call(updateVisibleNodes)
})

View file

@ -39,3 +39,11 @@ export function useMediaStyleSheet(
)
}
}
export function usePrevious<T>(newValue: T) {
const previousRef = React.useRef(newValue)
React.useEffect(() => {
previousRef.current = newValue
})
return previousRef.current
}