-
Notifications
You must be signed in to change notification settings - Fork 177
feat(cow-fi): add Resources section for programmatic CMS content #7846
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
Open
riboflavin
wants to merge
10
commits into
cowprotocol:develop
Choose a base branch
from
riboflavin:feat/cow-fi-resources
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4a303f6
feat(cow-fi): add Resource CMS service functions
riboflavin af3d295
feat(cow-fi): add Resources pages and components
riboflavin 0de3be9
feat(ui): add Resources link to global footer
riboflavin 25afcb5
feat(cow-fi): extend cache, revalidation, and sitemap for Resources
riboflavin 23c9825
chore(cow-fi): link local @cowprotocol/cms for Resource endpoints
riboflavin 3ff5772
fix(cow-fi): avoid invalid Font.size usage on Resources pages
riboflavin 81754ee
fix(cow-fi): stop BigInt crash on Resources pages
riboflavin 2813596
fix(cow-fi): let campaign mismatch redirects escape try/catch
riboflavin 4984fa5
fix(cow-fi): harden BigInt gas constant against Webpack transpile
riboflavin 4f15eb3
chore(cow-fi): keep @cowprotocol/cms on published 0.11.0 until CMS ships
riboflavin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
100 changes: 100 additions & 0 deletions
100
apps/cow-fi/app/(main)/resources/[campaign]/[slug]/page.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import type { ReactNode } from 'react' | ||
|
|
||
| import { notFound, permanentRedirect } from 'next/navigation' | ||
|
|
||
| import { getAllResourceSlugs, getResourceBySlug, SharedRichTextComponent } from '../../../../../services/cms' | ||
|
|
||
| import type { Metadata } from 'next' | ||
|
|
||
| import { ResourcePageComponent } from '@/components/ResourcePageComponent' | ||
| import { getPageMetadata } from '@/util/getPageMetadata' | ||
| import { stripHtmlTags } from '@/util/stripHTMLTags' | ||
|
|
||
| export const revalidate = 43200 | ||
|
|
||
| const METADATA_DESCRIPTION_MAX_LENGTH = 150 | ||
| const METADATA_DESCRIPTION_TRUNCATE_LENGTH = METADATA_DESCRIPTION_MAX_LENGTH - 3 | ||
|
|
||
| function isRichTextComponent(block: unknown): block is SharedRichTextComponent { | ||
| return ( | ||
| typeof block === 'object' && | ||
| block !== null && | ||
| 'body' in block && | ||
| typeof (block as { body?: unknown }).body === 'string' | ||
| ) | ||
| } | ||
|
|
||
| type Props = { | ||
| params: Promise<{ campaign: string; slug: string }> | ||
| } | ||
|
|
||
| export async function generateMetadata({ params }: Props): Promise<Metadata> { | ||
| const { slug } = await params | ||
|
|
||
| if (!slug) return {} | ||
|
|
||
| try { | ||
| const resource = await getResourceBySlug(slug) | ||
| if (!resource?.attributes) { | ||
| return getPageMetadata({ | ||
| title: 'Resource Not Found', | ||
| description: 'The requested resource could not be found.', | ||
| }) | ||
| } | ||
|
|
||
| const attributes = resource.attributes | ||
| const { title, blocks, description, cover } = attributes | ||
| const coverImageUrl = cover?.data?.attributes?.url | ||
| const content = | ||
| blocks?.map((block: SharedRichTextComponent) => (isRichTextComponent(block) ? block.body : '')).join(' ') || '' | ||
| const plainContent = stripHtmlTags(content) | ||
|
|
||
| return getPageMetadata({ | ||
| absoluteTitle: `${title} - CoW DAO`, | ||
| description: description | ||
| ? stripHtmlTags(description) | ||
| : plainContent.length > METADATA_DESCRIPTION_MAX_LENGTH | ||
| ? stripHtmlTags(plainContent.substring(0, METADATA_DESCRIPTION_TRUNCATE_LENGTH)) + '...' | ||
| : stripHtmlTags(plainContent), | ||
| image: coverImageUrl, | ||
| }) | ||
| } catch (error) { | ||
| console.error(`Error generating metadata for resource ${slug}:`, error) | ||
| return getPageMetadata({ | ||
| title: 'Resource', | ||
| description: 'Loading resource...', | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| export async function generateStaticParams(): Promise<{ campaign: string; slug: string }[]> { | ||
| try { | ||
| return await getAllResourceSlugs() | ||
| } catch (error) { | ||
| console.error('Error generating resource static params:', error) | ||
| return [] | ||
| } | ||
| } | ||
|
|
||
| export default async function ResourcePage({ params }: Props): Promise<ReactNode> { | ||
| const { campaign, slug } = await params | ||
|
|
||
| let resource | ||
| try { | ||
| resource = await getResourceBySlug(slug) | ||
| } catch (error) { | ||
| console.error(`Error fetching resource ${slug}:`, error) | ||
| return notFound() | ||
| } | ||
|
|
||
| if (!resource?.attributes) { | ||
| return notFound() | ||
| } | ||
|
|
||
| // Keep outside try/catch — permanentRedirect throws a control-flow error Next must handle | ||
| if (resource.attributes.campaign !== campaign) { | ||
| permanentRedirect(`/resources/${resource.attributes.campaign}/${slug}`) | ||
| } | ||
|
|
||
| return <ResourcePageComponent resource={resource} /> | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import type { ReactNode } from 'react' | ||
|
|
||
| import { notFound } from 'next/navigation' | ||
|
|
||
| import { getCampaignSummaries, getResources } from '../../../../services/cms' | ||
|
|
||
| import type { Metadata } from 'next' | ||
|
|
||
| import { ResourcesCampaignComponent } from '@/components/ResourcesCampaignComponent' | ||
| import { getCampaignLabel } from '@/const/resources' | ||
| import { getPageMetadata } from '@/util/getPageMetadata' | ||
|
|
||
| export const revalidate = 43200 | ||
|
|
||
| type Props = { | ||
| params: Promise<{ campaign: string }> | ||
| } | ||
|
|
||
| export async function generateStaticParams(): Promise<{ campaign: string }[]> { | ||
| const campaigns = await getCampaignSummaries() | ||
| return campaigns.map(({ campaign }) => ({ campaign })) | ||
| } | ||
|
|
||
| export async function generateMetadata({ params }: Props): Promise<Metadata> { | ||
| const campaign = (await params).campaign | ||
| const label = getCampaignLabel(campaign) | ||
|
|
||
| return getPageMetadata({ | ||
| title: label, | ||
| description: `Programmatic ${label.toLowerCase()} resources from CoW DAO.`, | ||
| }) | ||
| } | ||
|
|
||
| export default async function ResourcesCampaignPage({ params }: Props): Promise<ReactNode> { | ||
| const campaign = (await params).campaign | ||
| const resourcesResponse = await getResources({ | ||
| filters: { | ||
| campaign: { | ||
| $eq: campaign, | ||
| }, | ||
| }, | ||
| }) | ||
|
|
||
| if (resourcesResponse.data.length === 0) { | ||
| return notFound() | ||
| } | ||
|
|
||
| return <ResourcesCampaignComponent campaign={campaign} resources={resourcesResponse.data} /> | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import type { ReactNode } from 'react' | ||
|
|
||
| import { getCampaignSummaries } from '../../../services/cms' | ||
|
|
||
| import type { Metadata } from 'next' | ||
|
|
||
| import { ResourcesHubComponent } from '@/components/ResourcesHubComponent' | ||
| import { getPageMetadata } from '@/util/getPageMetadata' | ||
|
|
||
| export const revalidate = 43200 | ||
|
|
||
| export async function generateMetadata(): Promise<Metadata> { | ||
| return getPageMetadata({ | ||
| title: 'Resources', | ||
| description: 'Programmatic reference content published by CoW DAO.', | ||
| }) | ||
| } | ||
|
|
||
| export default async function ResourcesPage(): Promise<ReactNode> { | ||
| const campaigns = await getCampaignSummaries() | ||
|
|
||
| return <ResourcesHubComponent campaigns={campaigns} /> | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| 'use client' | ||
|
|
||
| import type { ImgHTMLAttributes, ReactNode } from 'react' | ||
|
|
||
| import { Media } from '@cowprotocol/ui' | ||
|
|
||
| import { usePathname } from 'next/navigation' | ||
| import ReactMarkdown from 'react-markdown' | ||
| import styled from 'styled-components/macro' | ||
|
|
||
| import { Resource, SharedRichTextComponent } from '../services/cms' | ||
|
|
||
| import { LazyImage } from '@/components/LazyImage' | ||
| import { Link } from '@/components/Link' | ||
| import { ShareBlock } from '@/components/ShareBlock' | ||
| import { getCampaignLabel } from '@/const/resources' | ||
| import { ArticleContent, ArticleMainTitle, ArticleSubtitleWrapper, BodyContent, Breadcrumbs } from '@/styles/styled' | ||
| import { formatDate } from '@/util/formatDate' | ||
| import { remarkAllowedHtmlImages, sanitizeCmsMarkdown } from '@/util/markdownHtmlImages' | ||
|
|
||
| const SITE_ORIGIN = process.env.NEXT_PUBLIC_SITE_URL || '' | ||
|
|
||
| const Wrapper = styled.div` | ||
| display: flex; | ||
| flex-flow: column wrap; | ||
| justify-content: center; | ||
| width: 100%; | ||
| margin: 24px auto 0; | ||
| gap: 34px; | ||
| max-width: 1760px; | ||
|
|
||
| ${Media.upToMedium()} { | ||
| margin: 0 auto; | ||
| gap: 24px; | ||
| } | ||
| ` | ||
|
|
||
| interface ResourcePageComponentProps { | ||
| resource: Resource | ||
| } | ||
|
|
||
| export function ResourcePageComponent({ resource }: ResourcePageComponentProps): ReactNode { | ||
| const attributes = resource.attributes | ||
| const title = attributes?.title | ||
| const campaign = attributes?.campaign | ||
| const blocks = attributes?.blocks | ||
| const publishedAt = attributes?.publishedAt | ||
| const publishDate = attributes?.publishDate || null | ||
| const publishDateVisible = attributes?.publishDateVisible ?? true | ||
| const description = attributes?.description || '' | ||
| const content = | ||
| blocks?.map((block: SharedRichTextComponent) => (isRichTextComponent(block) ? block.body : '')).join(' ') || '' | ||
| const pathname = usePathname() | ||
| const fallbackUrl = buildFallbackUrl(pathname) | ||
| const shareTitle = title || 'CoW DAO Resource' | ||
|
|
||
| if (!campaign || !attributes?.slug) { | ||
| return null | ||
| } | ||
|
|
||
| const campaignLabel = getCampaignLabel(campaign) | ||
| const dateIso = publishDate || publishedAt || '' | ||
| const date = dateIso ? new Date(dateIso) : null | ||
| const showDate = Boolean(publishDateVisible && date && !Number.isNaN(date.getTime())) | ||
| const formattedDate = showDate && date ? formatDate(date) : null | ||
|
|
||
| return ( | ||
| <Wrapper> | ||
| <ArticleContent> | ||
| <Breadcrumbs> | ||
| <Link href="/">Home</Link> | ||
| <Link href="/resources">Resources</Link> | ||
| <Link href={`/resources/${campaign}`}>{campaignLabel}</Link> | ||
| <span>{title}</span> | ||
| </Breadcrumbs> | ||
|
|
||
| <ArticleMainTitle>{title}</ArticleMainTitle> | ||
|
|
||
| <ArticleSubtitleWrapper> | ||
| {description && <div>{description}</div>} | ||
| {formattedDate && ( | ||
| <> | ||
| {description && <div>·</div>} | ||
| <div> | ||
| <span>Published {formattedDate}</span> | ||
| </div> | ||
| </> | ||
| )} | ||
| </ArticleSubtitleWrapper> | ||
|
|
||
| <BodyContent> | ||
| {blocks?.map((block) => | ||
| isRichTextComponent(block) ? <ResourceRichText key={block.id} sharedRichText={block} /> : null, | ||
| )} | ||
| <ShareBlock url={fallbackUrl} title={shareTitle} onShare={() => undefined} /> | ||
| </BodyContent> | ||
| </ArticleContent> | ||
| </Wrapper> | ||
| ) | ||
| } | ||
|
|
||
| function buildFallbackUrl(pathname: string): string { | ||
| if (!SITE_ORIGIN) return '' | ||
| try { | ||
| return new URL(pathname, SITE_ORIGIN).toString() | ||
| } catch { | ||
| return '' | ||
| } | ||
| } | ||
|
|
||
| function isRichTextComponent(block: unknown): block is SharedRichTextComponent { | ||
| return ( | ||
| typeof block === 'object' && | ||
| block !== null && | ||
| 'body' in block && | ||
| typeof (block as { body?: unknown }).body === 'string' | ||
| ) | ||
| } | ||
|
|
||
| function MarkdownImage({ src, alt, ...props }: ImgHTMLAttributes<HTMLImageElement>): ReactNode { | ||
| const dataSrc = (props as Record<string, unknown>)['data-src'] | ||
| const resolvedSrc = typeof dataSrc === 'string' ? dataSrc : src | ||
| if (!resolvedSrc) return null | ||
| return <LazyImage src={resolvedSrc} alt={alt || ''} {...props} width={725} height={400} /> | ||
| } | ||
|
|
||
| function ResourceRichText({ sharedRichText }: { sharedRichText: SharedRichTextComponent }): ReactNode { | ||
| const content = sanitizeCmsMarkdown(sharedRichText.body || '') | ||
|
|
||
| return ( | ||
| <ReactMarkdown skipHtml remarkPlugins={[remarkAllowedHtmlImages]} components={{ img: MarkdownImage }}> | ||
| {content} | ||
| </ReactMarkdown> | ||
| ) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Missing null check for
resource.attributes.campaignbefore redirect comparison.If
campaignisundefinedornull, the conditionresource.attributes.campaign !== campaignevaluates totrue(sincecampaignfrom the URL is always a string), causing a redirect to/resources/undefined/${slug}. The downstreamResourcePageComponentexplicitly guards against falsycampaign(if (!campaign || !attributes?.slug) return null), confirming this case is reachable.🐛 Proposed fix: guard against missing campaign before redirect
if (!resource?.attributes) { return notFound() } + if (!resource.attributes.campaign) { + return notFound() + } + // Keep outside try/catch — permanentRedirect throws a control-flow error Next must handle if (resource.attributes.campaign !== campaign) { permanentRedirect(`/resources/${resource.attributes.campaign}/${slug}`) }📝 Committable suggestion
🤖 Prompt for AI Agents