Skip to content

Commit

Permalink
fix: wrong search scroll position of 1-level heading in current page (#…
Browse files Browse the repository at this point in the history
…1978)

* fix: fixed the hash was cleared and did not scroll to the corresponding position

* feat: 调整搜索逻辑,如果目标链接是本页 & !hash,则滚动到顶部
  • Loading branch information
binyellow authored Dec 11, 2023
1 parent 1c2a6fb commit 8f9e80b
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions src/client/theme-default/slots/SearchResult/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { ReactComponent as IconInbox } from '@ant-design/icons-svg/inline-svg/outlined/inbox.svg';
import { FormattedMessage, history, Link, type useSiteSearch } from 'dumi';
import animateScrollTo from 'animated-scroll-to';
import {
FormattedMessage,
history,
Link,
useLocation,
type useSiteSearch,
} from 'dumi';
import React, {
Fragment,
useCallback,
Expand Down Expand Up @@ -119,6 +126,20 @@ const SearchResult: FC<{
}> = (props) => {
const [data, histsCount] = useFlatSearchData(props.data);
const [activeIndex, setActiveIndex] = useState(-1);
const { pathname } = useLocation();

const onItemSelect = (item: ISearchResult[0]['hints'][0]) => {
props.onItemSelect?.(item);

const url = new URL(item?.link, location.origin);
if (url?.pathname === pathname && !url.hash) {
setTimeout(() => {
animateScrollTo(0, {
maxDuration: 300,
});
}, 1);
}
};

useEffect(() => {
const handler = (ev: KeyboardEvent) => {
Expand All @@ -133,7 +154,7 @@ const SearchResult: FC<{
)!.value as ISearchResult[0]['hints'][0];

history.push(item.link);
props.onItemSelect?.(item);
onItemSelect?.(item);
(document.activeElement as HTMLInputElement).blur();
}

Expand Down Expand Up @@ -167,7 +188,7 @@ const SearchResult: FC<{
<Link
to={item.value.link}
data-active={activeIndex === item.activeIndex || undefined}
onClick={() => props.onItemSelect?.(item.value)}
onClick={() => onItemSelect?.(item.value)}
>
{React.createElement(ICONS_MAPPING[item.value.type])}
<h4>
Expand Down

0 comments on commit 8f9e80b

Please sign in to comment.