93 lines
2.5 KiB
TypeScript
93 lines
2.5 KiB
TypeScript
import { Link } from "react-router";
|
|
import clsx from "clsx";
|
|
import { Fragment, ReactNode, Ref, useEffect, useRef } from "react";
|
|
import { Button } from "../button";
|
|
|
|
interface Props {
|
|
type?: "button" | "submit";
|
|
to: string | undefined;
|
|
children: ReactNode;
|
|
className?: string;
|
|
target?: undefined | "_blank" | string;
|
|
role?: string;
|
|
ariaLabel?: string;
|
|
rel?: string;
|
|
onClick?: (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => void;
|
|
reloadDocument?: boolean;
|
|
autoFocus?: boolean;
|
|
prefetch?: "intent" | "render" | "none";
|
|
disabled?: boolean;
|
|
isLoading?: boolean;
|
|
onMouseEnter?: (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement | HTMLDivElement>) => void;
|
|
onMouseLeave?: (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement | HTMLDivElement>) => void;
|
|
}
|
|
export default function LinkOrAhref({
|
|
type = "button",
|
|
to,
|
|
target,
|
|
children,
|
|
className,
|
|
role,
|
|
ariaLabel,
|
|
rel,
|
|
onClick,
|
|
reloadDocument,
|
|
autoFocus,
|
|
prefetch,
|
|
disabled,
|
|
isLoading,
|
|
onMouseEnter,
|
|
onMouseLeave,
|
|
}: Props) {
|
|
const focusRef = useRef<HTMLButtonElement | HTMLAnchorElement | null>(null);
|
|
|
|
useEffect(() => {
|
|
if (!autoFocus) {
|
|
return;
|
|
}
|
|
const timeout = window.setTimeout(() => focusRef.current?.focus(), 0);
|
|
return () => window.clearTimeout(timeout);
|
|
}, [autoFocus]);
|
|
|
|
return (
|
|
<Fragment>
|
|
{(!to && !onClick) || (to && disabled) ? (
|
|
<div className={className} role={role} aria-label={ariaLabel} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
|
|
{children}
|
|
</div>
|
|
) : to == undefined ? (
|
|
<Button
|
|
ref={focusRef as Ref<HTMLButtonElement>}
|
|
type={type}
|
|
onClick={onClick}
|
|
className={clsx(className, isLoading && "base-spinner cursor-not-allowed")}
|
|
role={role}
|
|
aria-label={ariaLabel}
|
|
disabled={disabled}
|
|
onMouseEnter={onMouseEnter}
|
|
onMouseLeave={onMouseLeave}
|
|
>
|
|
{children}
|
|
</Button>
|
|
) : (
|
|
<Link
|
|
reloadDocument={reloadDocument}
|
|
onClick={onClick}
|
|
to={to}
|
|
target={target}
|
|
className={className}
|
|
role={role}
|
|
aria-label={ariaLabel}
|
|
ref={focusRef as Ref<HTMLAnchorElement>}
|
|
prefetch={prefetch}
|
|
rel={rel}
|
|
onMouseEnter={onMouseEnter}
|
|
onMouseLeave={onMouseLeave}
|
|
>
|
|
{children}
|
|
</Link>
|
|
)}
|
|
</Fragment>
|
|
);
|
|
}
|