Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use NextImage and NextLink components via slots #10

Merged
merged 1 commit into from
Aug 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { graphqlClient } from "../lib/graphqlClient";
import { draftMode } from "next/headers";
import "./globals.css";
import { graphql } from "#/gql";
import { Navigation } from "#/components/navigation";
import "@contentful/live-preview/style.css";
import { ContentfulPreviewProvider } from "#/components/contentful-preview-provider";
import { cn } from "#/lib/utils";
Expand Down
43 changes: 43 additions & 0 deletions components/asset-ctf/asset-ctf.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { ImageCtf } from "#/components/image-ctf";
import { FragmentType, getFragmentData, graphql } from "#/gql";

export const AssetFieldsFragment = graphql(/* GraphQL */ `
fragment AssetFields on Asset {
__typename
sys {
id
}
contentType
title
url
width
height
description
}
`);

export type AssetCtfProps = {
data: FragmentType<typeof AssetFieldsFragment>;
};

export const AssetCtf = (props: AssetCtfProps) => {
const data = getFragmentData(AssetFieldsFragment, props.data);

const { url, contentType } = data;

if (!url) {
return null;
}

if (!contentType || !url) {
return null;
}

if (contentType.startsWith("image")) {
return <ImageCtf {...props} />;
}

// TODO: Handle other file types.

return null;
};
1 change: 1 addition & 0 deletions components/asset-ctf/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./asset-ctf";
27 changes: 21 additions & 6 deletions components/hero-banner-ctf/hero-banner-ctf-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,36 @@
import { HeroBanner } from "../ui/hero-banner";
import { ComponentHeroBannerFieldsFragment } from "#/gql/graphql";
import { RichTextCtf } from "#/components/rich-text-ctf";
import { getPageLinkProps } from "../page";
import { getPageLinkChildProps } from "../page";
import { useComponentPreview } from "../hooks/use-component-preview";
import { getImageChildProps } from "../image-ctf";

export const HeroBannerCtfClient: React.FC<{
data: ComponentHeroBannerFieldsFragment;
}> = (props) => {
const { data: originalData } = props;
const { data, addAttributes } = useComponentPreview(originalData);
const { data, addAttributes } =
useComponentPreview<ComponentHeroBannerFieldsFragment>(originalData);

return (
<HeroBanner
headline={data.headline}
bodyText={<RichTextCtf json={data.bodyText?.json} />}
ctaText={data.ctaText}
ctaLink={data.targetPage && getPageLinkProps(data.targetPage)?.href}
imageUrl={data.image?.url}
bodyText={data.bodyText && <RichTextCtf {...data.bodyText} />}
cta={
data.targetPage &&
getPageLinkChildProps({
data: data.targetPage,
children: data.ctaText,
})
}
image={
data.image &&
getImageChildProps({
data: data.image,
sizes: "100vw",
priority: true,
})
}
addAttributes={addAttributes}
/>
);
Expand Down
11 changes: 8 additions & 3 deletions components/hero-banner-ctf/hero-banner-ctf.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,20 @@ export const ComponentHeroBannerFieldsFragment = graphql(/* GraphQL */ `
headline
bodyText {
json
links {
assets {
block {
...AssetFields
}
}
}
}
ctaText
targetPage {
...PageLinkFields
}
image {
url
width
height
...AssetFields
}
imageStyle
heroSize
Expand Down
9 changes: 5 additions & 4 deletions components/hooks/use-component-preview.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
"use client";

import { Entity } from "@contentful/live-preview/dist/types";
import { Argument, Entity } from "@contentful/live-preview/dist/types";
import {
useContentfulInspectorMode,
useContentfulLiveUpdates,
} from "@contentful/live-preview/react";

export const useComponentPreview = (data: Entity) => {
const previewData = useContentfulLiveUpdates(data);
export const useComponentPreview = <T extends Argument>(
data: (typeof useContentfulLiveUpdates)["arguments"][0]
) => {
const previewData = useContentfulLiveUpdates<T>(data);
const inspectorProps = useContentfulInspectorMode({
entryId: data.sys.id,
});
Expand Down
50 changes: 50 additions & 0 deletions components/image-ctf/image-ctf.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { getFragmentData } from "#/gql";
import { default as NextImage, ImageProps } from "next/image";
import React from "react";
import { AssetCtfProps, AssetFieldsFragment } from "../asset-ctf";

// Omit src and alt from ImageProps because we're validating them at runtime.
// Apparently typescript doesn't like that ImageProps has src and alt as required but we're spreading props after we map them from Contentful fields,
// it basically thinks we'll always override those props via the spread.
export type ImageCtfProps = AssetCtfProps & Omit<ImageProps, "src" | "alt">;

export const getImageProps = ({
data: fragmentData,
...props
}: ImageCtfProps) => {
const data = getFragmentData(AssetFieldsFragment, fragmentData);
if (!data.url) {
return null;
}
return {
src: data?.url,
alt: data?.description || "",
width: data.width || undefined,
height: data.height || undefined,
...props,
};
};

export const getImageChildProps = (props: ImageCtfProps) => {
const imageProps = getImageProps(props);

if (!imageProps) {
return null;
}

return {
...imageProps,
children: <NextImage {...imageProps} />,
asChild: true,
};
};

export const ImageCtf = (props: ImageCtfProps) => {
const imageProps = getImageProps(props);

if (!imageProps) {
return null;
}

return <NextImage {...imageProps} />;
};
1 change: 1 addition & 0 deletions components/image-ctf/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./image-ctf";
34 changes: 27 additions & 7 deletions components/page/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { FragmentType, getFragmentData, graphql } from "#/gql";
import { default as NextLink } from "next/link";

export const PageLinkFieldsFragment = graphql(/* GraphQL */ `
fragment PageLinkFields on Page {
Expand All @@ -19,15 +20,34 @@ export const PageLinkFieldsFragment = graphql(/* GraphQL */ `
}
`);

export const getPageLinkProps = (
data: FragmentType<typeof PageLinkFieldsFragment>
) => {
const fragment = getFragmentData(PageLinkFieldsFragment, data);
export interface PageLinkProps {
data: FragmentType<typeof PageLinkFieldsFragment>;
children?: React.ReactNode;
[key: string]: any;
}

export const getPageLinkProps = ({
data: fragmentData,
children,
...props
}: PageLinkProps) => {
const data = getFragmentData(PageLinkFieldsFragment, fragmentData);

return {
href: `/${data.slug}`,
as: `/${data.slug}`,
children: children ?? data.pageName,
...props,
};
};

export const getPageLinkChildProps = (props: PageLinkProps) => {
const linkProps = getPageLinkProps(props);

return {
href: `/${fragment.slug}`,
as: `/${fragment.slug}`,
children: fragment.pageName,
...linkProps,
children: <NextLink {...linkProps} />,
asChild: true,
};
};

Expand Down
87 changes: 85 additions & 2 deletions components/rich-text-ctf/rich-text-ctf.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,86 @@
export const RichTextCtf = (props: any) => {
return <>{"TODO: Implement CtfRichtext"}</>;
import { useMemo } from "react";
import {
Block as RichtextBlock,
BLOCKS,
INLINES,
} from "@contentful/rich-text-types";
import {
documentToReactComponents,
Options,
} from "@contentful/rich-text-react-renderer";
import { OmitRecursive, tryget } from "#/lib/utils";
import { AssetFieldsFragment } from "#/gql/graphql";
import { AssetCtf } from "../asset-ctf";

export interface RichTextProps {
json: any;
links?: {
entries?: {
block?: any;
inline?: any;
} | null;
assets?: {
block?: any;
} | null;
} | null;
}

interface Block extends RichtextBlock {
__typename: string;
sys: { id: string };
}

type Asset = OmitRecursive<AssetFieldsFragment, "__typename">;

export const RichTextCtf = (props: RichTextProps) => {
const { json, links } = props;

const entryBlocks = useMemo(
() => tryget(() => links!.entries!.block!.filter((b: any) => !!b), [])!,
[links]
);

const assetBlocks = useMemo(
() => tryget(() => links!.assets!.block!.filter((b: any) => !!b), [])!,
[links]
);

const options = useMemo(() => {
const opts: Options = {};
opts.renderNode = {
[INLINES.EMBEDDED_ENTRY]: (node) => {
const id = tryget(() => node.data.target.sys.id);
return <>{`${node.nodeType} ${id}`}</>;
},
[BLOCKS.EMBEDDED_ENTRY]: (node) => {
const id = tryget(() => node.data.target.sys.id);
if (id) {
const entry = entryBlocks.find((block: any) => block!.sys.id === id);

if (entry) {
return (
<>
<div>Entry:</div>
<pre>{JSON.stringify(entry, null, 2)}</pre>
</>
);
}
}
return <>{`${node.nodeType} ${id}`}</>;
},
[BLOCKS.EMBEDDED_ASSET]: (node) => {
const id = tryget(() => node.data.target.sys.id);
if (id) {
const asset = assetBlocks.find((block: any) => block!.sys.id === id);
return asset && <AssetCtf data={asset} />;
}

return <>{`${node.nodeType} ${id}`}</>;
},
};

return opts;
}, [entryBlocks, assetBlocks]);

return <>{documentToReactComponents(json, options)}</>;
};
19 changes: 19 additions & 0 deletions components/ui/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
## UI Components

This folder is meant to contain UI components that can be used to compose any other components in NextJS or other React frameworks. Although this folder is within NextJS App itself (for simplicity), you should think of it as external component library that either lives outside NextJS in a monorepo, or even lives in another repo for some cases.

### Conventions


#### Pure UI Components
There are a few boundaries and principles we set with this UI folder that we should maintain:
- UI folder has no knowledge of Contentful. In other words UI components could work in Contentful or outside. There shouldn't be any data-fetching activities or knowledge of contentful-specific things except when needed to hint to Contentful with external escape hatches (see [addAttributes](./hero-banner/hero-banner.tsx) function as an example)
- UI folder should not have any knowledge of NextJS either. It's easy to put NextLink and NextImage in your UI components, but that makes them not possible to reuse outside of NextJS. For this reason alone we have a demonstated path to register NextJS-specific components via ComponentsProvider/useComponents technique. See [here](./hooks/useComponents.ts)
- Pure UI components in same folder makes it easy to understand when you violated that principle. If you see a NextJS or Contentful implementation detail in this folder, you did this wrong.
- This folder is ready for copy/paste into other projects or from other projects/libraries. Especially using shadcn/ui CLI, you can download components into this folder with commands like `npx shadcn-ui@latest add [component]`. See [components.json](../../components.json) for configuration for shadcn/ui.

#### Storybook

Storybook should be used to demonstrate UI components visuals, variations and interactions and it's much easier to do in isolation without the need to mock real API responses and data-fetching.


12 changes: 6 additions & 6 deletions components/ui/hero-banner/hero-banner.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import type { Meta, StoryObj } from "@storybook/react";
import { Button } from "../button";

import { HeroBanner } from "./hero-banner";

// More on how to set up stories at: https://storybook.js.org/docs/react/writing-stories/introduction#default-export
Expand All @@ -16,8 +14,8 @@ const meta = {
// More on argTypes: https://storybook.js.org/docs/react/api/argtypes
argTypes: {
headline: { control: "text" },
imageUrl: { control: "text" },
bodyText: { control: "text" },
image: { control: "object" },
},
} satisfies Meta<typeof HeroBanner>;

Expand All @@ -26,7 +24,10 @@ type Story = StoryObj<typeof meta>;

const defaultArgs = {
headline: "With great power comes great responsibility",
imageUrl: "https://picsum.photos/seed/picsum/1920/1080",
image: {
src: "https://picsum.photos/seed/picsum/1920/1080",
alt: "Placeholder image",
},
};
// More on writing stories with args: https://storybook.js.org/docs/react/writing-stories/args
export const Default: Story = {
Expand All @@ -51,7 +52,6 @@ export const WithReactComponent: Story = {
export const WithCta: Story = {
args: {
...defaultArgs,
ctaText: "Learn more",
ctaLink: "https://google.com",
cta: { children: "Learn more", href: "https://google.com" },
},
};
Loading