saleor-apps-redis_apl/packages/ui/src/text-link.tsx

76 lines
1.7 KiB
TypeScript
Raw Normal View History

import { actions, useAppBridge } from "@saleor/app-sdk/app-bridge";
import { Text, TextProps } from "@saleor/macaw-ui/next";
import { useRouter } from "next/router";
export interface TextLinkProps extends TextProps {
href: string;
newTab?: boolean;
}
const BaseTextLink = (props: TextLinkProps) => {
return (
2023-05-17 16:53:49 +00:00
<Text target="_blank" as={"a"} textDecoration={"none"} rel="noopener noreferrer" {...props}>
<Text
2023-05-17 16:53:49 +00:00
transition={"ease"}
variant={"bodyStrong"}
color={{
default: "text3Decorative",
hover: "text1Decorative",
}}
>
{props.children}
</Text>
</Text>
);
};
export const TextLink = ({ href, newTab = false, children, ...props }: TextLinkProps) => {
const { appBridge } = useAppBridge();
const { push } = useRouter();
const onNewTabClick = (event: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
event.preventDefault();
if (!appBridge) {
console.warn(
"App bridge is not initialized, TextLink cannot be used with external links without it."
);
}
appBridge?.dispatch(
actions.Redirect({
to: href,
newContext: true,
})
);
if (props.onClick) {
props.onClick(event);
}
};
const onInternalClick = (event: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
event.preventDefault();
push(href);
if (props.onClick) {
props.onClick(event);
}
};
if (newTab) {
return (
<BaseTextLink href={href} onClick={onNewTabClick} {...props}>
{children}
</BaseTextLink>
);
} else {
return (
<BaseTextLink href={href} onClick={onInternalClick} {...props}>
{children}
</BaseTextLink>
);
}
};