From d5241e2f1c0b6248df2eaa253ba3e4f720080a77 Mon Sep 17 00:00:00 2001 From: EnixCoda Date: Sun, 11 Aug 2019 21:40:30 +0800 Subject: [PATCH] feat: scroll to top when search key changes --- src/components/FileExplorer.tsx | 16 +++++++++++----- src/driver/core/FileExplorer.ts | 10 ---------- src/utils/hooks.ts | 8 ++++++++ 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/src/components/FileExplorer.tsx b/src/components/FileExplorer.tsx index ff11118..1bbb612 100644 --- a/src/components/FileExplorer.tsx +++ b/src/components/FileExplorer.tsx @@ -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 { } 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 @@ -76,12 +77,17 @@ class FileExplorer extends React.Component { }>(({ nodes, width, height, focusedNode }) => { const listRef = React.useRef(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 ( void execAfterRender: () => void @@ -312,9 +311,6 @@ const goTo: MethodCreator = 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 { 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) }) diff --git a/src/utils/hooks.ts b/src/utils/hooks.ts index a22abe6..578ae1f 100644 --- a/src/utils/hooks.ts +++ b/src/utils/hooks.ts @@ -39,3 +39,11 @@ export function useMediaStyleSheet( ) } } + +export function usePrevious(newValue: T) { + const previousRef = React.useRef(newValue) + React.useEffect(() => { + previousRef.current = newValue + }) + return previousRef.current +}