2024-12-06 15:36:37 +08:00
|
|
|
import type { MouseEvent, MouseEventHandler } from 'react';
|
|
|
|
import React, { useMemo, forwardRef } from 'react';
|
|
|
|
import { Link as DumiLink, useLocation, useAppData, useNavigate } from 'dumi';
|
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-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;
|
2024-07-15 09:22:02 +08:00
|
|
|
component?: React.ComponentType<any>;
|
2024-12-06 13:40:58 +08:00
|
|
|
children?: React.ReactNode;
|
2023-09-17 23:32:14 +08:00
|
|
|
}
|
2023-04-13 18:13:13 +08:00
|
|
|
|
2024-12-06 15:36:37 +08:00
|
|
|
const Link = forwardRef<HTMLAnchorElement, React.PropsWithChildren<LinkProps>>(
|
|
|
|
({ component, children, to, ...rest }, ref) => {
|
|
|
|
const { pathname } = useLocation();
|
|
|
|
const { preloadRoute } = useAppData();
|
|
|
|
const navigate = useNavigate();
|
|
|
|
const href = useMemo<string>(() => {
|
|
|
|
if (typeof to === 'object') {
|
|
|
|
return `${to.pathname || pathname}${to.search || ''}${to.hash || ''}`;
|
|
|
|
}
|
|
|
|
return to;
|
|
|
|
}, [to]);
|
|
|
|
const onClick = (e: MouseEvent<HTMLAnchorElement>) => {
|
|
|
|
rest.onClick?.(e);
|
|
|
|
if (!href?.startsWith('http')) {
|
|
|
|
// Should support open in new tab
|
|
|
|
if (!e.metaKey && !e.ctrlKey && !e.shiftKey) {
|
|
|
|
e.preventDefault();
|
|
|
|
navigate(href);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
if (component) {
|
|
|
|
return React.createElement(
|
|
|
|
component,
|
|
|
|
{
|
|
|
|
...rest,
|
|
|
|
ref,
|
|
|
|
href,
|
|
|
|
onClick,
|
|
|
|
onMouseEnter: () => preloadRoute?.(href),
|
|
|
|
},
|
|
|
|
children,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return (
|
|
|
|
<DumiLink ref={ref} {...rest} to={href} prefetch>
|
|
|
|
{children}
|
|
|
|
</DumiLink>
|
|
|
|
);
|
|
|
|
},
|
|
|
|
);
|
2023-04-13 18:13:13 +08:00
|
|
|
|
|
|
|
export default Link;
|