Skip to content

Commit

Permalink
Add HiddenIfInvalidLink helper (#237)
Browse files Browse the repository at this point in the history
Hides a link and its content if the link target isn't valid.

---------

Co-authored-by: Kerstin Reichinger <kerstin.reichinger@vivid-planet.com>
  • Loading branch information
kerstin97 and kerstinreichinger-vivid authored May 23, 2024
1 parent d3c196b commit debe706
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
30 changes: 30 additions & 0 deletions site/src/common/helpers/HiddenIfInvalidLink.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { usePreview } from "@comet/cms-site";
import { ExternalLinkBlockData, InternalLinkBlockData, LinkBlockData } from "@src/blocks.generated";
import * as React from "react";

interface HiddenIfInvalidLinkProps {
link: LinkBlockData;
children: React.ReactElement;
}

export function HiddenIfInvalidLink({ link, children }: HiddenIfInvalidLinkProps) {
const { previewType } = usePreview();

if (previewType === "BlockPreview") {
return children;
}

if (!isValidLink(link)) {
return null;
}

return children;
}

const isValidLink = (link: LinkBlockData) => {
return Boolean(
link.block &&
((link.block.type === "internal" && (link.block.props as InternalLinkBlockData).targetPage) ||
(link.block.type === "external" && (link.block.props as ExternalLinkBlockData).targetUrl)),
);
};
7 changes: 6 additions & 1 deletion site/src/layout/header/PageLink.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Link, useRouter } from "@comet/cms-site";
import { LinkBlock } from "@src/common/blocks/LinkBlock";
import { HiddenIfInvalidLink } from "@src/common/helpers/HiddenIfInvalidLink";
import { gql } from "graphql-request";
import * as React from "react";

Expand Down Expand Up @@ -32,7 +33,11 @@ function PageLink({ page, children }: Props): JSX.Element | null {
return null;
}

return <LinkBlock data={page.document.content}>{typeof children === "function" ? children(active) : children}</LinkBlock>;
return (
<HiddenIfInvalidLink link={page.document.content}>
<LinkBlock data={page.document.content}>{typeof children === "function" ? children(active) : children}</LinkBlock>
</HiddenIfInvalidLink>
);
} else if (page.documentType === "Page") {
return (
<Link href={page.path} passHref>
Expand Down

0 comments on commit debe706

Please sign in to comment.