2023-10-08 13:44:02 +08:00
|
|
|
import type { MouseEvent, MouseEventHandler } from 'react';
|
2024-02-04 17:08:39 +08:00
|
|
|
import React, { forwardRef, useLayoutEffect, useTransition } from 'react';
|
2023-08-02 14:04:29 +08:00
|
|
|
import { useLocation, useNavigate } from 'dumi';
|
|
|
|
import nprogress from 'nprogress';
|
2023-04-13 18:13:13 +08:00
|
|
|
|
2023-09-17 23:32:14 +08:00
|
|
|
export interface LinkProps {
|
2024-02-04 17:08:39 +08:00
|
|
|
to: string | { pathname?: string; search?: string; hash?: string };
|
2023-04-13 18:13:13 +08:00
|
|
|
children?: React.ReactNode;
|
2023-08-07 11:43:28 +08:00
|
|
|
style?: React.CSSProperties;
|
2023-04-18 15:29:34 +08:00
|
|
|
className?: string;
|
2023-10-08 13:44:02 +08:00
|
|
|
onClick?: MouseEventHandler;
|
2023-09-17 23:32:14 +08:00
|
|
|
}
|
2023-04-13 18:13:13 +08:00
|
|
|
|
|
|
|
const Link = forwardRef<HTMLAnchorElement, LinkProps>((props, ref) => {
|
2023-04-18 15:29:34 +08:00
|
|
|
const { to, children, ...rest } = props;
|
2023-08-02 14:04:29 +08:00
|
|
|
const [isPending, startTransition] = useTransition();
|
2023-04-13 18:13:13 +08:00
|
|
|
const navigate = useNavigate();
|
2023-08-02 14:04:29 +08:00
|
|
|
const { pathname } = useLocation();
|
|
|
|
|
2024-02-04 17:08:39 +08:00
|
|
|
const href = React.useMemo<string>(() => {
|
2023-08-02 14:04:29 +08:00
|
|
|
if (typeof to === 'object') {
|
|
|
|
return `${to.pathname || pathname}${to.search || ''}${to.hash || ''}`;
|
|
|
|
}
|
|
|
|
return to;
|
|
|
|
}, [to]);
|
2023-04-13 18:13:13 +08:00
|
|
|
|
|
|
|
const handleClick = (e: MouseEvent<HTMLAnchorElement>) => {
|
2023-10-08 13:44:02 +08:00
|
|
|
props.onClick?.(e);
|
2023-09-17 23:32:14 +08:00
|
|
|
if (!href?.startsWith('http')) {
|
2023-07-06 13:45:40 +08:00
|
|
|
// Should support open in new tab
|
|
|
|
if (!e.metaKey && !e.ctrlKey && !e.shiftKey) {
|
|
|
|
e.preventDefault();
|
|
|
|
startTransition(() => {
|
2023-09-17 23:32:14 +08:00
|
|
|
if (href) {
|
|
|
|
navigate(href);
|
|
|
|
}
|
2023-07-06 13:45:40 +08:00
|
|
|
});
|
|
|
|
}
|
2023-04-13 18:13:13 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-08-02 14:04:29 +08:00
|
|
|
useLayoutEffect(() => {
|
|
|
|
if (isPending) {
|
|
|
|
nprogress.start();
|
|
|
|
} else {
|
|
|
|
nprogress.done();
|
|
|
|
}
|
|
|
|
}, [isPending]);
|
|
|
|
|
2023-04-13 18:13:13 +08:00
|
|
|
return (
|
2023-10-08 13:44:02 +08:00
|
|
|
<a ref={ref} onClick={handleClick} {...rest} href={href}>
|
2023-04-13 18:13:13 +08:00
|
|
|
{children}
|
|
|
|
</a>
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
|
|
|
export default Link;
|