diff --git a/src/components/FileExplorer/hooks/useHandleClickFileLink.ts b/src/components/FileExplorer/hooks/useHandleClickFileLink.ts new file mode 100644 index 0000000..546bbdf --- /dev/null +++ b/src/components/FileExplorer/hooks/useHandleClickFileLink.ts @@ -0,0 +1,37 @@ +import { useCallback, useRef } from 'react' +import { useEvent } from 'react-use' +import { useAfterRedirect } from 'utils/hooks/useFastRedirect' + +export function useHandleClickFileLink(ref: React.MutableRefObject) { + const toGoRef = useRef(null) + const onClickCaptureSaveHrefWithHash = useCallback( + (e: Event) => { + const target = e.target + if (target instanceof HTMLElement && ref.current?.contains(target)) { + let e: HTMLElement | null = target + while (e && e !== ref.current) { + if (e instanceof HTMLAnchorElement) { + const hash = e.href.split('#')[1] + if (hash) { + toGoRef.current = e.href + } + } + e = e.parentElement + } + } + }, + [ref], + ) + useEvent('click', onClickCaptureSaveHrefWithHash, document, true) + + const redirectToSavedHrefWithHash = useCallback(() => { + const toGo = toGoRef.current + if (toGo) { + toGoRef.current = null + if (toGo.startsWith(location.href)) { + window.location.replace(toGo) + } + } + }, []) + useAfterRedirect(redirectToSavedHrefWithHash) +} diff --git a/src/components/FileExplorer/hooks/useOnNodeClick.tsx b/src/components/FileExplorer/hooks/useOnNodeClick.tsx index 625a669..9fe11be 100644 --- a/src/components/FileExplorer/hooks/useOnNodeClick.tsx +++ b/src/components/FileExplorer/hooks/useOnNodeClick.tsx @@ -41,7 +41,8 @@ export function useHandleNodeClick( focusNode(node) if (node.url) { - const isHashLink = node.url.includes('#') + const isHashLink = + node.url.includes('#') && node.url.split('#')[0] === location.pathname if (!isHashLink) { event.preventDefault() loadWithFastRedirect(node.url, event.currentTarget) diff --git a/src/components/FileExplorer/index.tsx b/src/components/FileExplorer/index.tsx index 3e4d533..9ff740c 100644 --- a/src/components/FileExplorer/index.tsx +++ b/src/components/FileExplorer/index.tsx @@ -26,6 +26,7 @@ import { useOnLocationChange } from 'utils/hooks/useOnLocationChange' import { VisibleNodes, VisibleNodesGenerator } from 'utils/VisibleNodesGenerator' import { SideBarStateContext } from '../../containers/SideBarState' import { useGetCurrentPath } from './hooks/useGetCurrentPath' +import { useHandleClickFileLink } from './hooks/useHandleClickFileLink' import { useHandleKeyDown } from './hooks/useHandleKeyDown' import { NodeRenderer, @@ -199,6 +200,8 @@ function LoadedFileExplorer({ useCallback(() => ref.current?.focus(), []), ) + useHandleClickFileLink(ref) + return (
{visibleNodesGenerator?.defer && (