Add user data to open graph images - #1144

Merged
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images
Oct 17, 2024
Merged

Add user data to open graph images#1144
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images

Conversation

@NiallJoeMaher

Copy link
Copy Markdown
Contributor

✨ Codu Pull Request 💻

Pull Request details

  • Add article information to Open Graph image
  • Update styles
  • Add custom fonts to the design
  • Refactor design
  • Remove from users profile

Any Breaking changes

  • None

Associated Screenshots

New Open Graph with new branding

* Add Lato fonts for image
* Remove unused images
* Add background SVGs as components
* Update user profile and articles to account for updates
@NiallJoeMaher
NiallJoeMaher requested a review from a team as a code ownerOctober 17, 2024 21:36
@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

@NiallJoeMaher is attempting to deploy a commit to the Codú Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitaiBot commented Oct 17, 2024

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces several modifications across multiple files to enhance metadata structures and improve accessibility. Key changes include updates to the generateMetadata functions for user profiles and articles, adding more descriptive titles and structured open graph metadata. The GET function in the routing file now requires additional query parameters with enhanced error handling. New React components for rendering graphics have been added, and error handling in an image processing function has been improved.

Changes

File PathChange Summary
app/(app)/[username]/page.tsxUpdated generateMetadata and Page functions for improved metadata and accessibility; added h1 for better structure.
app/(app)/articles/[slug]/page.tsxEnhanced generateMetadata for articles with additional context; updated image metadata parameters.
app/og/route.tsxModified GET function to require four query parameters; added error handling and new helper function formatDate.
cdk/lambdas/uploadResize/index.jsImproved error handling in resizeImage function; no changes to public entity declarations.
components/background/background.tsxIntroduced new components Stars and Waves for SVG rendering with TypeScript support.

Possibly related PRs

🐇 In the meadow, bright and fair,
New metadata fills the air.
With stars that twinkle, waves that flow,
Our profiles shine, as they grow!
Error handling, sleek and neat,
In CodeRabbit's world, it’s quite the treat! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

NameStatusPreviewCommentsUpdated (UTC)
codu✅ Ready (Inspect)Visit Preview💬 Add feedbackOct 17, 2024 9:43pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
app/(app)/[username]/page.tsx (2)

33-43: Enhanced Open Graph metadata structure.

The changes to the openGraph metadata are well-implemented:

  1. The type is now correctly set to "profile".
  2. The images array now contains a detailed object, which is more informative for the Open Graph protocol.
  3. The dynamic alt text improves accessibility.

Consider adding a username property to the Open Graph metadata, as it's specific to user profiles:

 openGraph: {
title,
description,
type: "profile",
+ username: username,
images: [
// ...
],
siteName: "Codú",
},

47-50: Improved Twitter card metadata, but consider consistency.

The addition of the card property enhances the Twitter metadata. However, the images array format is inconsistent with the openGraph images.

For consistency, consider updating the twitter.images to match the openGraph.images format:

 twitter: {
card: "summary_large_image",
title,
description,
- images: ["/images/og/home-og.png"],+ images: [+ {+ url: "/images/og/home-og.png",+ width: 1200,+ height: 630,+ alt: `${name || username}'s profile on Codú`,+ },+ ],
},

This change would provide more detailed image information for Twitter cards as well.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 556ae96 and 613c640.

⛔ Files ignored due to path filters (8)
  • assets/Lato-Bold.ttf is excluded by !**/*.ttf, !**/*.ttf
  • assets/Lato-Regular.ttf is excluded by !**/*.ttf, !**/*.ttf
  • public/images/og/noise.png is excluded by !**/*.png, !**/*.png
  • public/images/og/noise.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/planet.png is excluded by !**/*.png, !**/*.png
  • public/images/og/planet.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/stars.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/waves.svg is excluded by !**/*.svg, !**/*.svg
📒 Files selected for processing (5)
  • app/(app)/[username]/page.tsx (2 hunks)
  • app/(app)/articles/[slug]/page.tsx (1 hunks)
  • app/og/route.tsx (2 hunks)
  • cdk/lambdas/uploadResize/index.js (1 hunks)
  • components/background/background.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • cdk/lambdas/uploadResize/index.js
🧰 Additional context used
🪛 Biome
app/og/route.tsx

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (5)
app/(app)/[username]/page.tsx (3)

26-27: Improved metadata construction for better SEO and sharing.

The changes to title and description enhance the metadata by providing more context and using fallbacks. This is beneficial for SEO and when sharing the profile on various platforms.


120-123: Improved accessibility with semantic heading.

The addition of the h1 element with the sr-only class significantly enhances the page's accessibility. This provides a clear, high-level description of the page content for screen reader users without affecting the visual layout.


Line range hint 1-123: Overall assessment: Excellent improvements to metadata and accessibility.

The changes in this file successfully address the PR objectives by enhancing the Open Graph metadata, improving accessibility, and refining the overall structure. The modifications to the generateMetadata function and the Page component's return statement are particularly noteworthy for their positive impact on SEO, social media sharing, and screen reader compatibility.

A few minor suggestions were made for further improvement:

  1. Adding a username property to the Open Graph metadata.
  2. Ensuring consistency between the openGraph and twitter image formats.

These changes significantly enhance the user profile representation and align well with best practices for web development.

components/background/background.tsx (2)

1-64: Overall assessment: Well-structured components with room for improvement

The Stars and Waves components are well-implemented, type-safe React components that provide reusable SVG graphics. They align with the PR objective of enhancing the visual identity and improving the representation of content.

Positive aspects:

  1. Use of TypeScript for type safety.
  2. Flexible prop handling with spread operator.
  3. Reusable and easily integrable components.

Areas for improvement:

  1. Enhance responsiveness by allowing dynamic sizing.
  2. Consider simplifying the complex path in the Waves component for better performance and maintainability.

These components contribute to the visual enhancement mentioned in the PR objectives. However, to fully meet the goal of incorporating article information into Open Graph images, ensure that these components are properly integrated with the article data rendering logic elsewhere in the codebase.

To confirm the integration of these components with article data, you could run:

✅ Verification successful

Integration Confirmed: Stars and Waves components are utilized in Open Graph functionality

The Stars and Waves components are successfully integrated within the app/og/route.tsx file, ensuring they contribute to the generation of Open Graph images as intended. This alignment supports the PR objective of enhancing visual identity and improving content representation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" --type tsx --type ts | rg -i "article|opengraph|og"

Length of output: 101


Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" -g '*.tsx' -g '*.ts'| rg -i "article|opengraph|og"

Length of output: 225


46-64: 🛠️ Refactor suggestion

Enhance responsiveness and consider simplifying the Waves component

The Waves component is well-structured but has some areas for improvement:

  1. Fixed dimensions may limit responsiveness.

  2. The single path element is quite complex, which might affect performance and maintainability.

  3. Improve responsiveness:
    Similar to the Stars component, consider accepting width and height as optional props and use viewBox for scaling. For example:

    exportconstWaves=({
    width =1200,
    height =638,
    ...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1200 638"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);
  4. Consider path complexity:
    The single path element is very complex. If possible, consider breaking it down into multiple simpler paths or using a different approach to create the wave effect. This could improve performance and make the component easier to maintain and modify in the future.

To assess the impact of the complex path on performance, you could run a performance profiling tool. Here's a script to check if there are any performance-related comments in the codebase:

Comment on lines +41 to +47
images: [
`/og?title=${encodeURIComponent(
post.title,
)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(
post.user.name,
)}&date=${post.updatedAt}`,
],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

readTimeMins is properly defined and usage is safe.

The readTimeMins property is consistently defined in the codebase, ensuring that its usage does not require additional null checks. This addresses and resolves the concern about potential undefined errors.

However, there is still an inconsistency between the openGraph.images and twitter.images properties that needs to be addressed to maintain metadata consistency across platforms.

🔗 Analysis chain

Improved Open Graph metadata with article details.

The addition of readTime, author, and date to the Open Graph image URL enhances the metadata, aligning with the PR objective. Good use of encodeURIComponent for proper URL encoding.

However, there are two points to consider:

  1. The twitter.images property hasn't been updated to match the new format used in openGraph.images. This could lead to inconsistency in metadata across platforms.

Consider updating the twitter.images property to match:

twitter: {description: post.excerpt,images: [`/og?title=${encodeURIComponent(post.title)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(post.user.name)}&date=${post.updatedAt}`],},
  1. The readTimeMins property is used without checking if it exists, which could potentially lead to errors if the property is undefined.

Consider adding a null check or providing a default value:

readTime=${post.readTimeMins??0}

Let's verify the existence and type of the readTimeMins property:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg --type typescript "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg --type typescript "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 402


Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 1935

Comment on lines +3 to +44
export const Stars = (
props: React.JSX.IntrinsicAttributes & React.SVGProps<SVGSVGElement>,
) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={1131}
height={601}
fill="none"
{...props}
>
<path
fill="#fff"
fillOpacity={0.2}
d="M104.227 331.67a4.949 4.949 0 1 1-9.896 0 4.949 4.949 0 1 1 9.896 0ZM866.23 36.452a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM151.009 220.963a2.25 2.25 0 1 1-4.5.002 2.25 2.25 0 0 1 4.5-.002ZM1110.04 374.873c0 1.242-1.01 2.25-2.25 2.25a2.246 2.246 0 0 1-2.25-2.25c0-1.243 1-2.25 2.25-2.25 1.24 0 2.25 1.007 2.25 2.25ZM358.828 85.055a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM1111.83 21.151a2.245 2.245 0 1 1-4.49 0 2.245 2.245 0 1 1 4.49 0ZM1096.54 149.859c0 1.243-1.01 2.25-2.25 2.25a2.251 2.251 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM729.484 111.157a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0ZM20.56 2.25a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M31.565 330.348a2.251 2.251 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM34.12 230.333a2.25 2.25 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM63.181 215.232a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.761 4.434ZM30.719 260.798a2.25 2.25 0 0 1 .76-4.436 2.251 2.251 0 0 1-.76 4.436ZM59.623 156.175a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.762 4.434ZM97.22 149.847a2.25 2.25 0 0 1 .762-4.436 2.25 2.25 0 0 1-.761 4.436ZM1077.05 141.685c.69-.572.78-1.588.2-2.27a1.6 1.6 0 0 0-2.26-.201 1.598 1.598 0 0 0-.2 2.271 1.6 1.6 0 0 0 2.26.2ZM1039.43 80.706c.69-.571.78-1.588.2-2.27a1.61 1.61 0 1 0-2.47 2.07c.58.682 1.59.772 2.27.2ZM1016.01 81.843a1.612 1.612 0 0 0-2.07-2.47 1.606 1.606 0 0 0-.2 2.27 1.61 1.61 0 0 0 2.27.2ZM1052.52 98.335a1.611 1.611 0 1 0-2.07-2.472 1.611 1.611 0 0 0 2.07 2.472ZM996.929 44.008a1.612 1.612 0 0 0-2.07-2.47 1.611 1.611 0 1 0 2.07 2.47ZM971.378 53.651a1.611 1.611 0 1 0-2.068-2.471 1.611 1.611 0 0 0 2.068 2.471Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M4.498 444.841a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M1128.37 438.118a2.256 2.256 0 0 1-1.84-2.598 2.255 2.255 0 0 1 2.6-1.838 2.25 2.25 0 1 1-.76 4.436Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M831.276 591.549a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.949 4.949 0 1 1 9.896 0ZM36.886 525.845a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.95 4.95 0 0 1 4.948-4.95 4.95 4.95 0 0 1 4.948 4.95ZM1030.1 580.749c0 1.242-1.01 2.25-2.25 2.25a2.252 2.252 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM599.166 562.748a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M462.42 584.349a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM363.458 598.75a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM343.666 572.648a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM394.046 596.95a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM286.088 586.149a2.249 2.249 0 1 1-4.498 0 2.25 2.25 0 1 1 4.498 0ZM273.493 550.147a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
</svg>
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider improving responsiveness of the Stars component

The Stars component is well-structured and uses TypeScript for type safety. However, the fixed dimensions (width: 1131, height: 601) might limit its responsiveness across different screen sizes.

Consider making the component more responsive by:

  1. Accepting width and height as optional props with default values.
  2. Using percentage values or viewBox for scaling.

Here's an example of how you could modify the component:

exportconstStars=({
width =1131,
height =601,
...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1131 601"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);

This change allows the component to be more flexible while maintaining its aspect ratio.

Comment threadapp/og/route.tsx
Comment on lines +24 to +31
const regularFontData = await fetch(
new URL("@/assets/Lato-Regular.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

const boldFontData = await fetch(
new URL("@/assets/Lato-Bold.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Suggestion: Fetch font data in parallel to improve performance

Currently, the font data for regular and bold fonts is fetched sequentially, which can lead to increased response times. Fetching both fonts in parallel will optimize performance by reducing the total fetch time.

Apply this diff to fetch font data in parallel:

- const regularFontData = await fetch(- new URL("@/assets/Lato-Regular.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());-- const boldFontData = await fetch(- new URL("@/assets/Lato-Bold.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());+ const [regularFontData, boldFontData] = await Promise.all([+ fetch(new URL("@/assets/Lato-Regular.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ fetch(new URL("@/assets/Lato-Bold.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ ]);
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constregularFontData=awaitfetch(
newURL("@/assets/Lato-Regular.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
constboldFontData=awaitfetch(
newURL("@/assets/Lato-Bold.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
const[regularFontData,boldFontData]=awaitPromise.all([
fetch(newURL("@/assets/Lato-Regular.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
fetch(newURL("@/assets/Lato-Bold.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
]);

Comment threadapp/og/route.tsx
Comment on lines +198 to +200
if (isNaN(date.getTime())) {
throw new Error("Invalid date");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Replace unsafe isNaN with Number.isNaN

Using the global isNaN function is unsafe because it performs type coercion, which may lead to unexpected results. The Number.isNaN method provides a more reliable check by ensuring the value is of the Number type and is actually NaN.

Apply this diff to fix the issue:

- if (isNaN(date.getTime())) {+ if (Number.isNaN(date.getTime())) {
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(isNaN(date.getTime())){
thrownewError("Invalid date");
}
if(Number.isNaN(date.getTime())){
thrownewError("Invalid date");
}
🧰 Tools
🪛 Biome

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@NiallJoeMaher
NiallJoeMaher merged commit 48708f0 into codu-code:developOct 17, 2024
@NiallJoeMaher
NiallJoeMaher deleted the feat/add-user-data-to-open-graph-images branch October 17, 2024 21:45
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@NiallJoeMaher
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Add user data to open graph images - #1144

Merged
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images
Oct 17, 2024
Merged

Add user data to open graph images#1144
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images

Conversation

@NiallJoeMaher

Copy link
Copy Markdown
Contributor

✨ Codu Pull Request 💻

Pull Request details

  • Add article information to Open Graph image
  • Update styles
  • Add custom fonts to the design
  • Refactor design
  • Remove from users profile

Any Breaking changes

  • None

Associated Screenshots

New Open Graph with new branding

* Add Lato fonts for image
* Remove unused images
* Add background SVGs as components
* Update user profile and articles to account for updates
@NiallJoeMaher
NiallJoeMaher requested a review from a team as a code ownerOctober 17, 2024 21:36
@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

@NiallJoeMaher is attempting to deploy a commit to the Codú Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitaiBot commented Oct 17, 2024

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces several modifications across multiple files to enhance metadata structures and improve accessibility. Key changes include updates to the generateMetadata functions for user profiles and articles, adding more descriptive titles and structured open graph metadata. The GET function in the routing file now requires additional query parameters with enhanced error handling. New React components for rendering graphics have been added, and error handling in an image processing function has been improved.

Changes

File PathChange Summary
app/(app)/[username]/page.tsxUpdated generateMetadata and Page functions for improved metadata and accessibility; added h1 for better structure.
app/(app)/articles/[slug]/page.tsxEnhanced generateMetadata for articles with additional context; updated image metadata parameters.
app/og/route.tsxModified GET function to require four query parameters; added error handling and new helper function formatDate.
cdk/lambdas/uploadResize/index.jsImproved error handling in resizeImage function; no changes to public entity declarations.
components/background/background.tsxIntroduced new components Stars and Waves for SVG rendering with TypeScript support.

Possibly related PRs

🐇 In the meadow, bright and fair,
New metadata fills the air.
With stars that twinkle, waves that flow,
Our profiles shine, as they grow!
Error handling, sleek and neat,
In CodeRabbit's world, it’s quite the treat! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

NameStatusPreviewCommentsUpdated (UTC)
codu✅ Ready (Inspect)Visit Preview💬 Add feedbackOct 17, 2024 9:43pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
app/(app)/[username]/page.tsx (2)

33-43: Enhanced Open Graph metadata structure.

The changes to the openGraph metadata are well-implemented:

  1. The type is now correctly set to "profile".
  2. The images array now contains a detailed object, which is more informative for the Open Graph protocol.
  3. The dynamic alt text improves accessibility.

Consider adding a username property to the Open Graph metadata, as it's specific to user profiles:

 openGraph: {
title,
description,
type: "profile",
+ username: username,
images: [
// ...
],
siteName: "Codú",
},

47-50: Improved Twitter card metadata, but consider consistency.

The addition of the card property enhances the Twitter metadata. However, the images array format is inconsistent with the openGraph images.

For consistency, consider updating the twitter.images to match the openGraph.images format:

 twitter: {
card: "summary_large_image",
title,
description,
- images: ["/images/og/home-og.png"],+ images: [+ {+ url: "/images/og/home-og.png",+ width: 1200,+ height: 630,+ alt: `${name || username}'s profile on Codú`,+ },+ ],
},

This change would provide more detailed image information for Twitter cards as well.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 556ae96 and 613c640.

⛔ Files ignored due to path filters (8)
  • assets/Lato-Bold.ttf is excluded by !**/*.ttf, !**/*.ttf
  • assets/Lato-Regular.ttf is excluded by !**/*.ttf, !**/*.ttf
  • public/images/og/noise.png is excluded by !**/*.png, !**/*.png
  • public/images/og/noise.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/planet.png is excluded by !**/*.png, !**/*.png
  • public/images/og/planet.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/stars.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/waves.svg is excluded by !**/*.svg, !**/*.svg
📒 Files selected for processing (5)
  • app/(app)/[username]/page.tsx (2 hunks)
  • app/(app)/articles/[slug]/page.tsx (1 hunks)
  • app/og/route.tsx (2 hunks)
  • cdk/lambdas/uploadResize/index.js (1 hunks)
  • components/background/background.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • cdk/lambdas/uploadResize/index.js
🧰 Additional context used
🪛 Biome
app/og/route.tsx

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (5)
app/(app)/[username]/page.tsx (3)

26-27: Improved metadata construction for better SEO and sharing.

The changes to title and description enhance the metadata by providing more context and using fallbacks. This is beneficial for SEO and when sharing the profile on various platforms.


120-123: Improved accessibility with semantic heading.

The addition of the h1 element with the sr-only class significantly enhances the page's accessibility. This provides a clear, high-level description of the page content for screen reader users without affecting the visual layout.


Line range hint 1-123: Overall assessment: Excellent improvements to metadata and accessibility.

The changes in this file successfully address the PR objectives by enhancing the Open Graph metadata, improving accessibility, and refining the overall structure. The modifications to the generateMetadata function and the Page component's return statement are particularly noteworthy for their positive impact on SEO, social media sharing, and screen reader compatibility.

A few minor suggestions were made for further improvement:

  1. Adding a username property to the Open Graph metadata.
  2. Ensuring consistency between the openGraph and twitter image formats.

These changes significantly enhance the user profile representation and align well with best practices for web development.

components/background/background.tsx (2)

1-64: Overall assessment: Well-structured components with room for improvement

The Stars and Waves components are well-implemented, type-safe React components that provide reusable SVG graphics. They align with the PR objective of enhancing the visual identity and improving the representation of content.

Positive aspects:

  1. Use of TypeScript for type safety.
  2. Flexible prop handling with spread operator.
  3. Reusable and easily integrable components.

Areas for improvement:

  1. Enhance responsiveness by allowing dynamic sizing.
  2. Consider simplifying the complex path in the Waves component for better performance and maintainability.

These components contribute to the visual enhancement mentioned in the PR objectives. However, to fully meet the goal of incorporating article information into Open Graph images, ensure that these components are properly integrated with the article data rendering logic elsewhere in the codebase.

To confirm the integration of these components with article data, you could run:

✅ Verification successful

Integration Confirmed: Stars and Waves components are utilized in Open Graph functionality

The Stars and Waves components are successfully integrated within the app/og/route.tsx file, ensuring they contribute to the generation of Open Graph images as intended. This alignment supports the PR objective of enhancing visual identity and improving content representation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" --type tsx --type ts | rg -i "article|opengraph|og"

Length of output: 101


Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" -g '*.tsx' -g '*.ts'| rg -i "article|opengraph|og"

Length of output: 225


46-64: 🛠️ Refactor suggestion

Enhance responsiveness and consider simplifying the Waves component

The Waves component is well-structured but has some areas for improvement:

  1. Fixed dimensions may limit responsiveness.

  2. The single path element is quite complex, which might affect performance and maintainability.

  3. Improve responsiveness:
    Similar to the Stars component, consider accepting width and height as optional props and use viewBox for scaling. For example:

    exportconstWaves=({
    width =1200,
    height =638,
    ...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1200 638"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);
  4. Consider path complexity:
    The single path element is very complex. If possible, consider breaking it down into multiple simpler paths or using a different approach to create the wave effect. This could improve performance and make the component easier to maintain and modify in the future.

To assess the impact of the complex path on performance, you could run a performance profiling tool. Here's a script to check if there are any performance-related comments in the codebase:

Comment on lines +41 to +47
images: [
`/og?title=${encodeURIComponent(
post.title,
)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(
post.user.name,
)}&date=${post.updatedAt}`,
],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

readTimeMins is properly defined and usage is safe.

The readTimeMins property is consistently defined in the codebase, ensuring that its usage does not require additional null checks. This addresses and resolves the concern about potential undefined errors.

However, there is still an inconsistency between the openGraph.images and twitter.images properties that needs to be addressed to maintain metadata consistency across platforms.

🔗 Analysis chain

Improved Open Graph metadata with article details.

The addition of readTime, author, and date to the Open Graph image URL enhances the metadata, aligning with the PR objective. Good use of encodeURIComponent for proper URL encoding.

However, there are two points to consider:

  1. The twitter.images property hasn't been updated to match the new format used in openGraph.images. This could lead to inconsistency in metadata across platforms.

Consider updating the twitter.images property to match:

twitter: {description: post.excerpt,images: [`/og?title=${encodeURIComponent(post.title)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(post.user.name)}&date=${post.updatedAt}`],},
  1. The readTimeMins property is used without checking if it exists, which could potentially lead to errors if the property is undefined.

Consider adding a null check or providing a default value:

readTime=${post.readTimeMins??0}

Let's verify the existence and type of the readTimeMins property:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg --type typescript "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg --type typescript "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 402


Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 1935

Comment on lines +3 to +44
export const Stars = (
props: React.JSX.IntrinsicAttributes & React.SVGProps<SVGSVGElement>,
) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={1131}
height={601}
fill="none"
{...props}
>
<path
fill="#fff"
fillOpacity={0.2}
d="M104.227 331.67a4.949 4.949 0 1 1-9.896 0 4.949 4.949 0 1 1 9.896 0ZM866.23 36.452a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM151.009 220.963a2.25 2.25 0 1 1-4.5.002 2.25 2.25 0 0 1 4.5-.002ZM1110.04 374.873c0 1.242-1.01 2.25-2.25 2.25a2.246 2.246 0 0 1-2.25-2.25c0-1.243 1-2.25 2.25-2.25 1.24 0 2.25 1.007 2.25 2.25ZM358.828 85.055a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM1111.83 21.151a2.245 2.245 0 1 1-4.49 0 2.245 2.245 0 1 1 4.49 0ZM1096.54 149.859c0 1.243-1.01 2.25-2.25 2.25a2.251 2.251 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM729.484 111.157a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0ZM20.56 2.25a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M31.565 330.348a2.251 2.251 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM34.12 230.333a2.25 2.25 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM63.181 215.232a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.761 4.434ZM30.719 260.798a2.25 2.25 0 0 1 .76-4.436 2.251 2.251 0 0 1-.76 4.436ZM59.623 156.175a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.762 4.434ZM97.22 149.847a2.25 2.25 0 0 1 .762-4.436 2.25 2.25 0 0 1-.761 4.436ZM1077.05 141.685c.69-.572.78-1.588.2-2.27a1.6 1.6 0 0 0-2.26-.201 1.598 1.598 0 0 0-.2 2.271 1.6 1.6 0 0 0 2.26.2ZM1039.43 80.706c.69-.571.78-1.588.2-2.27a1.61 1.61 0 1 0-2.47 2.07c.58.682 1.59.772 2.27.2ZM1016.01 81.843a1.612 1.612 0 0 0-2.07-2.47 1.606 1.606 0 0 0-.2 2.27 1.61 1.61 0 0 0 2.27.2ZM1052.52 98.335a1.611 1.611 0 1 0-2.07-2.472 1.611 1.611 0 0 0 2.07 2.472ZM996.929 44.008a1.612 1.612 0 0 0-2.07-2.47 1.611 1.611 0 1 0 2.07 2.47ZM971.378 53.651a1.611 1.611 0 1 0-2.068-2.471 1.611 1.611 0 0 0 2.068 2.471Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M4.498 444.841a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M1128.37 438.118a2.256 2.256 0 0 1-1.84-2.598 2.255 2.255 0 0 1 2.6-1.838 2.25 2.25 0 1 1-.76 4.436Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M831.276 591.549a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.949 4.949 0 1 1 9.896 0ZM36.886 525.845a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.95 4.95 0 0 1 4.948-4.95 4.95 4.95 0 0 1 4.948 4.95ZM1030.1 580.749c0 1.242-1.01 2.25-2.25 2.25a2.252 2.252 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM599.166 562.748a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M462.42 584.349a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM363.458 598.75a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM343.666 572.648a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM394.046 596.95a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM286.088 586.149a2.249 2.249 0 1 1-4.498 0 2.25 2.25 0 1 1 4.498 0ZM273.493 550.147a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
</svg>
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider improving responsiveness of the Stars component

The Stars component is well-structured and uses TypeScript for type safety. However, the fixed dimensions (width: 1131, height: 601) might limit its responsiveness across different screen sizes.

Consider making the component more responsive by:

  1. Accepting width and height as optional props with default values.
  2. Using percentage values or viewBox for scaling.

Here's an example of how you could modify the component:

exportconstStars=({
width =1131,
height =601,
...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1131 601"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);

This change allows the component to be more flexible while maintaining its aspect ratio.

Comment threadapp/og/route.tsx
Comment on lines +24 to +31
const regularFontData = await fetch(
new URL("@/assets/Lato-Regular.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

const boldFontData = await fetch(
new URL("@/assets/Lato-Bold.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Suggestion: Fetch font data in parallel to improve performance

Currently, the font data for regular and bold fonts is fetched sequentially, which can lead to increased response times. Fetching both fonts in parallel will optimize performance by reducing the total fetch time.

Apply this diff to fetch font data in parallel:

- const regularFontData = await fetch(- new URL("@/assets/Lato-Regular.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());-- const boldFontData = await fetch(- new URL("@/assets/Lato-Bold.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());+ const [regularFontData, boldFontData] = await Promise.all([+ fetch(new URL("@/assets/Lato-Regular.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ fetch(new URL("@/assets/Lato-Bold.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ ]);
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constregularFontData=awaitfetch(
newURL("@/assets/Lato-Regular.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
constboldFontData=awaitfetch(
newURL("@/assets/Lato-Bold.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
const[regularFontData,boldFontData]=awaitPromise.all([
fetch(newURL("@/assets/Lato-Regular.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
fetch(newURL("@/assets/Lato-Bold.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
]);

Comment threadapp/og/route.tsx
Comment on lines +198 to +200
if (isNaN(date.getTime())) {
throw new Error("Invalid date");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Replace unsafe isNaN with Number.isNaN

Using the global isNaN function is unsafe because it performs type coercion, which may lead to unexpected results. The Number.isNaN method provides a more reliable check by ensuring the value is of the Number type and is actually NaN.

Apply this diff to fix the issue:

- if (isNaN(date.getTime())) {+ if (Number.isNaN(date.getTime())) {
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(isNaN(date.getTime())){
thrownewError("Invalid date");
}
if(Number.isNaN(date.getTime())){
thrownewError("Invalid date");
}
🧰 Tools
🪛 Biome

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@NiallJoeMaher
NiallJoeMaher merged commit 48708f0 into codu-code:developOct 17, 2024
@NiallJoeMaher
NiallJoeMaher deleted the feat/add-user-data-to-open-graph-images branch October 17, 2024 21:45
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@NiallJoeMaher
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Add user data to open graph images - #1144

Merged
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images
Oct 17, 2024
Merged

Add user data to open graph images#1144
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images

Conversation

@NiallJoeMaher

Copy link
Copy Markdown
Contributor

✨ Codu Pull Request 💻

Pull Request details

  • Add article information to Open Graph image
  • Update styles
  • Add custom fonts to the design
  • Refactor design
  • Remove from users profile

Any Breaking changes

  • None

Associated Screenshots

New Open Graph with new branding

* Add Lato fonts for image
* Remove unused images
* Add background SVGs as components
* Update user profile and articles to account for updates
@NiallJoeMaher
NiallJoeMaher requested a review from a team as a code ownerOctober 17, 2024 21:36
@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

@NiallJoeMaher is attempting to deploy a commit to the Codú Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitaiBot commented Oct 17, 2024

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces several modifications across multiple files to enhance metadata structures and improve accessibility. Key changes include updates to the generateMetadata functions for user profiles and articles, adding more descriptive titles and structured open graph metadata. The GET function in the routing file now requires additional query parameters with enhanced error handling. New React components for rendering graphics have been added, and error handling in an image processing function has been improved.

Changes

File PathChange Summary
app/(app)/[username]/page.tsxUpdated generateMetadata and Page functions for improved metadata and accessibility; added h1 for better structure.
app/(app)/articles/[slug]/page.tsxEnhanced generateMetadata for articles with additional context; updated image metadata parameters.
app/og/route.tsxModified GET function to require four query parameters; added error handling and new helper function formatDate.
cdk/lambdas/uploadResize/index.jsImproved error handling in resizeImage function; no changes to public entity declarations.
components/background/background.tsxIntroduced new components Stars and Waves for SVG rendering with TypeScript support.

Possibly related PRs

🐇 In the meadow, bright and fair,
New metadata fills the air.
With stars that twinkle, waves that flow,
Our profiles shine, as they grow!
Error handling, sleek and neat,
In CodeRabbit's world, it’s quite the treat! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

NameStatusPreviewCommentsUpdated (UTC)
codu✅ Ready (Inspect)Visit Preview💬 Add feedbackOct 17, 2024 9:43pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
app/(app)/[username]/page.tsx (2)

33-43: Enhanced Open Graph metadata structure.

The changes to the openGraph metadata are well-implemented:

  1. The type is now correctly set to "profile".
  2. The images array now contains a detailed object, which is more informative for the Open Graph protocol.
  3. The dynamic alt text improves accessibility.

Consider adding a username property to the Open Graph metadata, as it's specific to user profiles:

 openGraph: {
title,
description,
type: "profile",
+ username: username,
images: [
// ...
],
siteName: "Codú",
},

47-50: Improved Twitter card metadata, but consider consistency.

The addition of the card property enhances the Twitter metadata. However, the images array format is inconsistent with the openGraph images.

For consistency, consider updating the twitter.images to match the openGraph.images format:

 twitter: {
card: "summary_large_image",
title,
description,
- images: ["/images/og/home-og.png"],+ images: [+ {+ url: "/images/og/home-og.png",+ width: 1200,+ height: 630,+ alt: `${name || username}'s profile on Codú`,+ },+ ],
},

This change would provide more detailed image information for Twitter cards as well.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 556ae96 and 613c640.

⛔ Files ignored due to path filters (8)
  • assets/Lato-Bold.ttf is excluded by !**/*.ttf, !**/*.ttf
  • assets/Lato-Regular.ttf is excluded by !**/*.ttf, !**/*.ttf
  • public/images/og/noise.png is excluded by !**/*.png, !**/*.png
  • public/images/og/noise.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/planet.png is excluded by !**/*.png, !**/*.png
  • public/images/og/planet.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/stars.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/waves.svg is excluded by !**/*.svg, !**/*.svg
📒 Files selected for processing (5)
  • app/(app)/[username]/page.tsx (2 hunks)
  • app/(app)/articles/[slug]/page.tsx (1 hunks)
  • app/og/route.tsx (2 hunks)
  • cdk/lambdas/uploadResize/index.js (1 hunks)
  • components/background/background.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • cdk/lambdas/uploadResize/index.js
🧰 Additional context used
🪛 Biome
app/og/route.tsx

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (5)
app/(app)/[username]/page.tsx (3)

26-27: Improved metadata construction for better SEO and sharing.

The changes to title and description enhance the metadata by providing more context and using fallbacks. This is beneficial for SEO and when sharing the profile on various platforms.


120-123: Improved accessibility with semantic heading.

The addition of the h1 element with the sr-only class significantly enhances the page's accessibility. This provides a clear, high-level description of the page content for screen reader users without affecting the visual layout.


Line range hint 1-123: Overall assessment: Excellent improvements to metadata and accessibility.

The changes in this file successfully address the PR objectives by enhancing the Open Graph metadata, improving accessibility, and refining the overall structure. The modifications to the generateMetadata function and the Page component's return statement are particularly noteworthy for their positive impact on SEO, social media sharing, and screen reader compatibility.

A few minor suggestions were made for further improvement:

  1. Adding a username property to the Open Graph metadata.
  2. Ensuring consistency between the openGraph and twitter image formats.

These changes significantly enhance the user profile representation and align well with best practices for web development.

components/background/background.tsx (2)

1-64: Overall assessment: Well-structured components with room for improvement

The Stars and Waves components are well-implemented, type-safe React components that provide reusable SVG graphics. They align with the PR objective of enhancing the visual identity and improving the representation of content.

Positive aspects:

  1. Use of TypeScript for type safety.
  2. Flexible prop handling with spread operator.
  3. Reusable and easily integrable components.

Areas for improvement:

  1. Enhance responsiveness by allowing dynamic sizing.
  2. Consider simplifying the complex path in the Waves component for better performance and maintainability.

These components contribute to the visual enhancement mentioned in the PR objectives. However, to fully meet the goal of incorporating article information into Open Graph images, ensure that these components are properly integrated with the article data rendering logic elsewhere in the codebase.

To confirm the integration of these components with article data, you could run:

✅ Verification successful

Integration Confirmed: Stars and Waves components are utilized in Open Graph functionality

The Stars and Waves components are successfully integrated within the app/og/route.tsx file, ensuring they contribute to the generation of Open Graph images as intended. This alignment supports the PR objective of enhancing visual identity and improving content representation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" --type tsx --type ts | rg -i "article|opengraph|og"

Length of output: 101


Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" -g '*.tsx' -g '*.ts'| rg -i "article|opengraph|og"

Length of output: 225


46-64: 🛠️ Refactor suggestion

Enhance responsiveness and consider simplifying the Waves component

The Waves component is well-structured but has some areas for improvement:

  1. Fixed dimensions may limit responsiveness.

  2. The single path element is quite complex, which might affect performance and maintainability.

  3. Improve responsiveness:
    Similar to the Stars component, consider accepting width and height as optional props and use viewBox for scaling. For example:

    exportconstWaves=({
    width =1200,
    height =638,
    ...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1200 638"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);
  4. Consider path complexity:
    The single path element is very complex. If possible, consider breaking it down into multiple simpler paths or using a different approach to create the wave effect. This could improve performance and make the component easier to maintain and modify in the future.

To assess the impact of the complex path on performance, you could run a performance profiling tool. Here's a script to check if there are any performance-related comments in the codebase:

Comment on lines +41 to +47
images: [
`/og?title=${encodeURIComponent(
post.title,
)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(
post.user.name,
)}&date=${post.updatedAt}`,
],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

readTimeMins is properly defined and usage is safe.

The readTimeMins property is consistently defined in the codebase, ensuring that its usage does not require additional null checks. This addresses and resolves the concern about potential undefined errors.

However, there is still an inconsistency between the openGraph.images and twitter.images properties that needs to be addressed to maintain metadata consistency across platforms.

🔗 Analysis chain

Improved Open Graph metadata with article details.

The addition of readTime, author, and date to the Open Graph image URL enhances the metadata, aligning with the PR objective. Good use of encodeURIComponent for proper URL encoding.

However, there are two points to consider:

  1. The twitter.images property hasn't been updated to match the new format used in openGraph.images. This could lead to inconsistency in metadata across platforms.

Consider updating the twitter.images property to match:

twitter: {description: post.excerpt,images: [`/og?title=${encodeURIComponent(post.title)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(post.user.name)}&date=${post.updatedAt}`],},
  1. The readTimeMins property is used without checking if it exists, which could potentially lead to errors if the property is undefined.

Consider adding a null check or providing a default value:

readTime=${post.readTimeMins??0}

Let's verify the existence and type of the readTimeMins property:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg --type typescript "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg --type typescript "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 402


Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 1935

Comment on lines +3 to +44
export const Stars = (
props: React.JSX.IntrinsicAttributes & React.SVGProps<SVGSVGElement>,
) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={1131}
height={601}
fill="none"
{...props}
>
<path
fill="#fff"
fillOpacity={0.2}
d="M104.227 331.67a4.949 4.949 0 1 1-9.896 0 4.949 4.949 0 1 1 9.896 0ZM866.23 36.452a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM151.009 220.963a2.25 2.25 0 1 1-4.5.002 2.25 2.25 0 0 1 4.5-.002ZM1110.04 374.873c0 1.242-1.01 2.25-2.25 2.25a2.246 2.246 0 0 1-2.25-2.25c0-1.243 1-2.25 2.25-2.25 1.24 0 2.25 1.007 2.25 2.25ZM358.828 85.055a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM1111.83 21.151a2.245 2.245 0 1 1-4.49 0 2.245 2.245 0 1 1 4.49 0ZM1096.54 149.859c0 1.243-1.01 2.25-2.25 2.25a2.251 2.251 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM729.484 111.157a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0ZM20.56 2.25a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M31.565 330.348a2.251 2.251 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM34.12 230.333a2.25 2.25 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM63.181 215.232a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.761 4.434ZM30.719 260.798a2.25 2.25 0 0 1 .76-4.436 2.251 2.251 0 0 1-.76 4.436ZM59.623 156.175a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.762 4.434ZM97.22 149.847a2.25 2.25 0 0 1 .762-4.436 2.25 2.25 0 0 1-.761 4.436ZM1077.05 141.685c.69-.572.78-1.588.2-2.27a1.6 1.6 0 0 0-2.26-.201 1.598 1.598 0 0 0-.2 2.271 1.6 1.6 0 0 0 2.26.2ZM1039.43 80.706c.69-.571.78-1.588.2-2.27a1.61 1.61 0 1 0-2.47 2.07c.58.682 1.59.772 2.27.2ZM1016.01 81.843a1.612 1.612 0 0 0-2.07-2.47 1.606 1.606 0 0 0-.2 2.27 1.61 1.61 0 0 0 2.27.2ZM1052.52 98.335a1.611 1.611 0 1 0-2.07-2.472 1.611 1.611 0 0 0 2.07 2.472ZM996.929 44.008a1.612 1.612 0 0 0-2.07-2.47 1.611 1.611 0 1 0 2.07 2.47ZM971.378 53.651a1.611 1.611 0 1 0-2.068-2.471 1.611 1.611 0 0 0 2.068 2.471Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M4.498 444.841a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M1128.37 438.118a2.256 2.256 0 0 1-1.84-2.598 2.255 2.255 0 0 1 2.6-1.838 2.25 2.25 0 1 1-.76 4.436Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M831.276 591.549a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.949 4.949 0 1 1 9.896 0ZM36.886 525.845a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.95 4.95 0 0 1 4.948-4.95 4.95 4.95 0 0 1 4.948 4.95ZM1030.1 580.749c0 1.242-1.01 2.25-2.25 2.25a2.252 2.252 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM599.166 562.748a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M462.42 584.349a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM363.458 598.75a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM343.666 572.648a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM394.046 596.95a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM286.088 586.149a2.249 2.249 0 1 1-4.498 0 2.25 2.25 0 1 1 4.498 0ZM273.493 550.147a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
</svg>
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider improving responsiveness of the Stars component

The Stars component is well-structured and uses TypeScript for type safety. However, the fixed dimensions (width: 1131, height: 601) might limit its responsiveness across different screen sizes.

Consider making the component more responsive by:

  1. Accepting width and height as optional props with default values.
  2. Using percentage values or viewBox for scaling.

Here's an example of how you could modify the component:

exportconstStars=({
width =1131,
height =601,
...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1131 601"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);

This change allows the component to be more flexible while maintaining its aspect ratio.

Comment threadapp/og/route.tsx
Comment on lines +24 to +31
const regularFontData = await fetch(
new URL("@/assets/Lato-Regular.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

const boldFontData = await fetch(
new URL("@/assets/Lato-Bold.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Suggestion: Fetch font data in parallel to improve performance

Currently, the font data for regular and bold fonts is fetched sequentially, which can lead to increased response times. Fetching both fonts in parallel will optimize performance by reducing the total fetch time.

Apply this diff to fetch font data in parallel:

- const regularFontData = await fetch(- new URL("@/assets/Lato-Regular.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());-- const boldFontData = await fetch(- new URL("@/assets/Lato-Bold.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());+ const [regularFontData, boldFontData] = await Promise.all([+ fetch(new URL("@/assets/Lato-Regular.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ fetch(new URL("@/assets/Lato-Bold.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ ]);
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constregularFontData=awaitfetch(
newURL("@/assets/Lato-Regular.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
constboldFontData=awaitfetch(
newURL("@/assets/Lato-Bold.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
const[regularFontData,boldFontData]=awaitPromise.all([
fetch(newURL("@/assets/Lato-Regular.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
fetch(newURL("@/assets/Lato-Bold.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
]);

Comment threadapp/og/route.tsx
Comment on lines +198 to +200
if (isNaN(date.getTime())) {
throw new Error("Invalid date");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Replace unsafe isNaN with Number.isNaN

Using the global isNaN function is unsafe because it performs type coercion, which may lead to unexpected results. The Number.isNaN method provides a more reliable check by ensuring the value is of the Number type and is actually NaN.

Apply this diff to fix the issue:

- if (isNaN(date.getTime())) {+ if (Number.isNaN(date.getTime())) {
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(isNaN(date.getTime())){
thrownewError("Invalid date");
}
if(Number.isNaN(date.getTime())){
thrownewError("Invalid date");
}
🧰 Tools
🪛 Biome

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@NiallJoeMaher
NiallJoeMaher merged commit 48708f0 into codu-code:developOct 17, 2024
@NiallJoeMaher
NiallJoeMaher deleted the feat/add-user-data-to-open-graph-images branch October 17, 2024 21:45
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@NiallJoeMaher
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Add user data to open graph images - #1144

Merged
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images
Oct 17, 2024
Merged

Add user data to open graph images#1144
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images

Conversation

@NiallJoeMaher

Copy link
Copy Markdown
Contributor

✨ Codu Pull Request 💻

Pull Request details

  • Add article information to Open Graph image
  • Update styles
  • Add custom fonts to the design
  • Refactor design
  • Remove from users profile

Any Breaking changes

  • None

Associated Screenshots

New Open Graph with new branding

* Add Lato fonts for image
* Remove unused images
* Add background SVGs as components
* Update user profile and articles to account for updates
@NiallJoeMaher
NiallJoeMaher requested a review from a team as a code ownerOctober 17, 2024 21:36
@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

@NiallJoeMaher is attempting to deploy a commit to the Codú Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitaiBot commented Oct 17, 2024

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces several modifications across multiple files to enhance metadata structures and improve accessibility. Key changes include updates to the generateMetadata functions for user profiles and articles, adding more descriptive titles and structured open graph metadata. The GET function in the routing file now requires additional query parameters with enhanced error handling. New React components for rendering graphics have been added, and error handling in an image processing function has been improved.

Changes

File PathChange Summary
app/(app)/[username]/page.tsxUpdated generateMetadata and Page functions for improved metadata and accessibility; added h1 for better structure.
app/(app)/articles/[slug]/page.tsxEnhanced generateMetadata for articles with additional context; updated image metadata parameters.
app/og/route.tsxModified GET function to require four query parameters; added error handling and new helper function formatDate.
cdk/lambdas/uploadResize/index.jsImproved error handling in resizeImage function; no changes to public entity declarations.
components/background/background.tsxIntroduced new components Stars and Waves for SVG rendering with TypeScript support.

Possibly related PRs

🐇 In the meadow, bright and fair,
New metadata fills the air.
With stars that twinkle, waves that flow,
Our profiles shine, as they grow!
Error handling, sleek and neat,
In CodeRabbit's world, it’s quite the treat! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

NameStatusPreviewCommentsUpdated (UTC)
codu✅ Ready (Inspect)Visit Preview💬 Add feedbackOct 17, 2024 9:43pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
app/(app)/[username]/page.tsx (2)

33-43: Enhanced Open Graph metadata structure.

The changes to the openGraph metadata are well-implemented:

  1. The type is now correctly set to "profile".
  2. The images array now contains a detailed object, which is more informative for the Open Graph protocol.
  3. The dynamic alt text improves accessibility.

Consider adding a username property to the Open Graph metadata, as it's specific to user profiles:

 openGraph: {
title,
description,
type: "profile",
+ username: username,
images: [
// ...
],
siteName: "Codú",
},

47-50: Improved Twitter card metadata, but consider consistency.

The addition of the card property enhances the Twitter metadata. However, the images array format is inconsistent with the openGraph images.

For consistency, consider updating the twitter.images to match the openGraph.images format:

 twitter: {
card: "summary_large_image",
title,
description,
- images: ["/images/og/home-og.png"],+ images: [+ {+ url: "/images/og/home-og.png",+ width: 1200,+ height: 630,+ alt: `${name || username}'s profile on Codú`,+ },+ ],
},

This change would provide more detailed image information for Twitter cards as well.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 556ae96 and 613c640.

⛔ Files ignored due to path filters (8)
  • assets/Lato-Bold.ttf is excluded by !**/*.ttf, !**/*.ttf
  • assets/Lato-Regular.ttf is excluded by !**/*.ttf, !**/*.ttf
  • public/images/og/noise.png is excluded by !**/*.png, !**/*.png
  • public/images/og/noise.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/planet.png is excluded by !**/*.png, !**/*.png
  • public/images/og/planet.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/stars.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/waves.svg is excluded by !**/*.svg, !**/*.svg
📒 Files selected for processing (5)
  • app/(app)/[username]/page.tsx (2 hunks)
  • app/(app)/articles/[slug]/page.tsx (1 hunks)
  • app/og/route.tsx (2 hunks)
  • cdk/lambdas/uploadResize/index.js (1 hunks)
  • components/background/background.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • cdk/lambdas/uploadResize/index.js
🧰 Additional context used
🪛 Biome
app/og/route.tsx

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (5)
app/(app)/[username]/page.tsx (3)

26-27: Improved metadata construction for better SEO and sharing.

The changes to title and description enhance the metadata by providing more context and using fallbacks. This is beneficial for SEO and when sharing the profile on various platforms.


120-123: Improved accessibility with semantic heading.

The addition of the h1 element with the sr-only class significantly enhances the page's accessibility. This provides a clear, high-level description of the page content for screen reader users without affecting the visual layout.


Line range hint 1-123: Overall assessment: Excellent improvements to metadata and accessibility.

The changes in this file successfully address the PR objectives by enhancing the Open Graph metadata, improving accessibility, and refining the overall structure. The modifications to the generateMetadata function and the Page component's return statement are particularly noteworthy for their positive impact on SEO, social media sharing, and screen reader compatibility.

A few minor suggestions were made for further improvement:

  1. Adding a username property to the Open Graph metadata.
  2. Ensuring consistency between the openGraph and twitter image formats.

These changes significantly enhance the user profile representation and align well with best practices for web development.

components/background/background.tsx (2)

1-64: Overall assessment: Well-structured components with room for improvement

The Stars and Waves components are well-implemented, type-safe React components that provide reusable SVG graphics. They align with the PR objective of enhancing the visual identity and improving the representation of content.

Positive aspects:

  1. Use of TypeScript for type safety.
  2. Flexible prop handling with spread operator.
  3. Reusable and easily integrable components.

Areas for improvement:

  1. Enhance responsiveness by allowing dynamic sizing.
  2. Consider simplifying the complex path in the Waves component for better performance and maintainability.

These components contribute to the visual enhancement mentioned in the PR objectives. However, to fully meet the goal of incorporating article information into Open Graph images, ensure that these components are properly integrated with the article data rendering logic elsewhere in the codebase.

To confirm the integration of these components with article data, you could run:

✅ Verification successful

Integration Confirmed: Stars and Waves components are utilized in Open Graph functionality

The Stars and Waves components are successfully integrated within the app/og/route.tsx file, ensuring they contribute to the generation of Open Graph images as intended. This alignment supports the PR objective of enhancing visual identity and improving content representation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" --type tsx --type ts | rg -i "article|opengraph|og"

Length of output: 101


Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" -g '*.tsx' -g '*.ts'| rg -i "article|opengraph|og"

Length of output: 225


46-64: 🛠️ Refactor suggestion

Enhance responsiveness and consider simplifying the Waves component

The Waves component is well-structured but has some areas for improvement:

  1. Fixed dimensions may limit responsiveness.

  2. The single path element is quite complex, which might affect performance and maintainability.

  3. Improve responsiveness:
    Similar to the Stars component, consider accepting width and height as optional props and use viewBox for scaling. For example:

    exportconstWaves=({
    width =1200,
    height =638,
    ...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1200 638"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);
  4. Consider path complexity:
    The single path element is very complex. If possible, consider breaking it down into multiple simpler paths or using a different approach to create the wave effect. This could improve performance and make the component easier to maintain and modify in the future.

To assess the impact of the complex path on performance, you could run a performance profiling tool. Here's a script to check if there are any performance-related comments in the codebase:

Comment on lines +41 to +47
images: [
`/og?title=${encodeURIComponent(
post.title,
)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(
post.user.name,
)}&date=${post.updatedAt}`,
],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

readTimeMins is properly defined and usage is safe.

The readTimeMins property is consistently defined in the codebase, ensuring that its usage does not require additional null checks. This addresses and resolves the concern about potential undefined errors.

However, there is still an inconsistency between the openGraph.images and twitter.images properties that needs to be addressed to maintain metadata consistency across platforms.

🔗 Analysis chain

Improved Open Graph metadata with article details.

The addition of readTime, author, and date to the Open Graph image URL enhances the metadata, aligning with the PR objective. Good use of encodeURIComponent for proper URL encoding.

However, there are two points to consider:

  1. The twitter.images property hasn't been updated to match the new format used in openGraph.images. This could lead to inconsistency in metadata across platforms.

Consider updating the twitter.images property to match:

twitter: {description: post.excerpt,images: [`/og?title=${encodeURIComponent(post.title)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(post.user.name)}&date=${post.updatedAt}`],},
  1. The readTimeMins property is used without checking if it exists, which could potentially lead to errors if the property is undefined.

Consider adding a null check or providing a default value:

readTime=${post.readTimeMins??0}

Let's verify the existence and type of the readTimeMins property:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg --type typescript "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg --type typescript "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 402


Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 1935

Comment on lines +3 to +44
export const Stars = (
props: React.JSX.IntrinsicAttributes & React.SVGProps<SVGSVGElement>,
) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={1131}
height={601}
fill="none"
{...props}
>
<path
fill="#fff"
fillOpacity={0.2}
d="M104.227 331.67a4.949 4.949 0 1 1-9.896 0 4.949 4.949 0 1 1 9.896 0ZM866.23 36.452a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM151.009 220.963a2.25 2.25 0 1 1-4.5.002 2.25 2.25 0 0 1 4.5-.002ZM1110.04 374.873c0 1.242-1.01 2.25-2.25 2.25a2.246 2.246 0 0 1-2.25-2.25c0-1.243 1-2.25 2.25-2.25 1.24 0 2.25 1.007 2.25 2.25ZM358.828 85.055a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM1111.83 21.151a2.245 2.245 0 1 1-4.49 0 2.245 2.245 0 1 1 4.49 0ZM1096.54 149.859c0 1.243-1.01 2.25-2.25 2.25a2.251 2.251 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM729.484 111.157a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0ZM20.56 2.25a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M31.565 330.348a2.251 2.251 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM34.12 230.333a2.25 2.25 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM63.181 215.232a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.761 4.434ZM30.719 260.798a2.25 2.25 0 0 1 .76-4.436 2.251 2.251 0 0 1-.76 4.436ZM59.623 156.175a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.762 4.434ZM97.22 149.847a2.25 2.25 0 0 1 .762-4.436 2.25 2.25 0 0 1-.761 4.436ZM1077.05 141.685c.69-.572.78-1.588.2-2.27a1.6 1.6 0 0 0-2.26-.201 1.598 1.598 0 0 0-.2 2.271 1.6 1.6 0 0 0 2.26.2ZM1039.43 80.706c.69-.571.78-1.588.2-2.27a1.61 1.61 0 1 0-2.47 2.07c.58.682 1.59.772 2.27.2ZM1016.01 81.843a1.612 1.612 0 0 0-2.07-2.47 1.606 1.606 0 0 0-.2 2.27 1.61 1.61 0 0 0 2.27.2ZM1052.52 98.335a1.611 1.611 0 1 0-2.07-2.472 1.611 1.611 0 0 0 2.07 2.472ZM996.929 44.008a1.612 1.612 0 0 0-2.07-2.47 1.611 1.611 0 1 0 2.07 2.47ZM971.378 53.651a1.611 1.611 0 1 0-2.068-2.471 1.611 1.611 0 0 0 2.068 2.471Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M4.498 444.841a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M1128.37 438.118a2.256 2.256 0 0 1-1.84-2.598 2.255 2.255 0 0 1 2.6-1.838 2.25 2.25 0 1 1-.76 4.436Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M831.276 591.549a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.949 4.949 0 1 1 9.896 0ZM36.886 525.845a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.95 4.95 0 0 1 4.948-4.95 4.95 4.95 0 0 1 4.948 4.95ZM1030.1 580.749c0 1.242-1.01 2.25-2.25 2.25a2.252 2.252 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM599.166 562.748a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M462.42 584.349a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM363.458 598.75a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM343.666 572.648a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM394.046 596.95a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM286.088 586.149a2.249 2.249 0 1 1-4.498 0 2.25 2.25 0 1 1 4.498 0ZM273.493 550.147a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
</svg>
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider improving responsiveness of the Stars component

The Stars component is well-structured and uses TypeScript for type safety. However, the fixed dimensions (width: 1131, height: 601) might limit its responsiveness across different screen sizes.

Consider making the component more responsive by:

  1. Accepting width and height as optional props with default values.
  2. Using percentage values or viewBox for scaling.

Here's an example of how you could modify the component:

exportconstStars=({
width =1131,
height =601,
...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1131 601"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);

This change allows the component to be more flexible while maintaining its aspect ratio.

Comment threadapp/og/route.tsx
Comment on lines +24 to +31
const regularFontData = await fetch(
new URL("@/assets/Lato-Regular.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

const boldFontData = await fetch(
new URL("@/assets/Lato-Bold.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Suggestion: Fetch font data in parallel to improve performance

Currently, the font data for regular and bold fonts is fetched sequentially, which can lead to increased response times. Fetching both fonts in parallel will optimize performance by reducing the total fetch time.

Apply this diff to fetch font data in parallel:

- const regularFontData = await fetch(- new URL("@/assets/Lato-Regular.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());-- const boldFontData = await fetch(- new URL("@/assets/Lato-Bold.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());+ const [regularFontData, boldFontData] = await Promise.all([+ fetch(new URL("@/assets/Lato-Regular.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ fetch(new URL("@/assets/Lato-Bold.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ ]);
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constregularFontData=awaitfetch(
newURL("@/assets/Lato-Regular.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
constboldFontData=awaitfetch(
newURL("@/assets/Lato-Bold.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
const[regularFontData,boldFontData]=awaitPromise.all([
fetch(newURL("@/assets/Lato-Regular.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
fetch(newURL("@/assets/Lato-Bold.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
]);

Comment threadapp/og/route.tsx
Comment on lines +198 to +200
if (isNaN(date.getTime())) {
throw new Error("Invalid date");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Replace unsafe isNaN with Number.isNaN

Using the global isNaN function is unsafe because it performs type coercion, which may lead to unexpected results. The Number.isNaN method provides a more reliable check by ensuring the value is of the Number type and is actually NaN.

Apply this diff to fix the issue:

- if (isNaN(date.getTime())) {+ if (Number.isNaN(date.getTime())) {
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(isNaN(date.getTime())){
thrownewError("Invalid date");
}
if(Number.isNaN(date.getTime())){
thrownewError("Invalid date");
}
🧰 Tools
🪛 Biome

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@NiallJoeMaher
NiallJoeMaher merged commit 48708f0 into codu-code:developOct 17, 2024
@NiallJoeMaher
NiallJoeMaher deleted the feat/add-user-data-to-open-graph-images branch October 17, 2024 21:45
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@NiallJoeMaher
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Add user data to open graph images - #1144

Merged
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images
Oct 17, 2024
Merged

Add user data to open graph images#1144
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images

Conversation

@NiallJoeMaher

Copy link
Copy Markdown
Contributor

✨ Codu Pull Request 💻

Pull Request details

  • Add article information to Open Graph image
  • Update styles
  • Add custom fonts to the design
  • Refactor design
  • Remove from users profile

Any Breaking changes

  • None

Associated Screenshots

New Open Graph with new branding

* Add Lato fonts for image
* Remove unused images
* Add background SVGs as components
* Update user profile and articles to account for updates
@NiallJoeMaher
NiallJoeMaher requested a review from a team as a code ownerOctober 17, 2024 21:36
@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

@NiallJoeMaher is attempting to deploy a commit to the Codú Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitaiBot commented Oct 17, 2024

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces several modifications across multiple files to enhance metadata structures and improve accessibility. Key changes include updates to the generateMetadata functions for user profiles and articles, adding more descriptive titles and structured open graph metadata. The GET function in the routing file now requires additional query parameters with enhanced error handling. New React components for rendering graphics have been added, and error handling in an image processing function has been improved.

Changes

File PathChange Summary
app/(app)/[username]/page.tsxUpdated generateMetadata and Page functions for improved metadata and accessibility; added h1 for better structure.
app/(app)/articles/[slug]/page.tsxEnhanced generateMetadata for articles with additional context; updated image metadata parameters.
app/og/route.tsxModified GET function to require four query parameters; added error handling and new helper function formatDate.
cdk/lambdas/uploadResize/index.jsImproved error handling in resizeImage function; no changes to public entity declarations.
components/background/background.tsxIntroduced new components Stars and Waves for SVG rendering with TypeScript support.

Possibly related PRs

🐇 In the meadow, bright and fair,
New metadata fills the air.
With stars that twinkle, waves that flow,
Our profiles shine, as they grow!
Error handling, sleek and neat,
In CodeRabbit's world, it’s quite the treat! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

NameStatusPreviewCommentsUpdated (UTC)
codu✅ Ready (Inspect)Visit Preview💬 Add feedbackOct 17, 2024 9:43pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
app/(app)/[username]/page.tsx (2)

33-43: Enhanced Open Graph metadata structure.

The changes to the openGraph metadata are well-implemented:

  1. The type is now correctly set to "profile".
  2. The images array now contains a detailed object, which is more informative for the Open Graph protocol.
  3. The dynamic alt text improves accessibility.

Consider adding a username property to the Open Graph metadata, as it's specific to user profiles:

 openGraph: {
title,
description,
type: "profile",
+ username: username,
images: [
// ...
],
siteName: "Codú",
},

47-50: Improved Twitter card metadata, but consider consistency.

The addition of the card property enhances the Twitter metadata. However, the images array format is inconsistent with the openGraph images.

For consistency, consider updating the twitter.images to match the openGraph.images format:

 twitter: {
card: "summary_large_image",
title,
description,
- images: ["/images/og/home-og.png"],+ images: [+ {+ url: "/images/og/home-og.png",+ width: 1200,+ height: 630,+ alt: `${name || username}'s profile on Codú`,+ },+ ],
},

This change would provide more detailed image information for Twitter cards as well.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 556ae96 and 613c640.

⛔ Files ignored due to path filters (8)
  • assets/Lato-Bold.ttf is excluded by !**/*.ttf, !**/*.ttf
  • assets/Lato-Regular.ttf is excluded by !**/*.ttf, !**/*.ttf
  • public/images/og/noise.png is excluded by !**/*.png, !**/*.png
  • public/images/og/noise.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/planet.png is excluded by !**/*.png, !**/*.png
  • public/images/og/planet.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/stars.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/waves.svg is excluded by !**/*.svg, !**/*.svg
📒 Files selected for processing (5)
  • app/(app)/[username]/page.tsx (2 hunks)
  • app/(app)/articles/[slug]/page.tsx (1 hunks)
  • app/og/route.tsx (2 hunks)
  • cdk/lambdas/uploadResize/index.js (1 hunks)
  • components/background/background.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • cdk/lambdas/uploadResize/index.js
🧰 Additional context used
🪛 Biome
app/og/route.tsx

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (5)
app/(app)/[username]/page.tsx (3)

26-27: Improved metadata construction for better SEO and sharing.

The changes to title and description enhance the metadata by providing more context and using fallbacks. This is beneficial for SEO and when sharing the profile on various platforms.


120-123: Improved accessibility with semantic heading.

The addition of the h1 element with the sr-only class significantly enhances the page's accessibility. This provides a clear, high-level description of the page content for screen reader users without affecting the visual layout.


Line range hint 1-123: Overall assessment: Excellent improvements to metadata and accessibility.

The changes in this file successfully address the PR objectives by enhancing the Open Graph metadata, improving accessibility, and refining the overall structure. The modifications to the generateMetadata function and the Page component's return statement are particularly noteworthy for their positive impact on SEO, social media sharing, and screen reader compatibility.

A few minor suggestions were made for further improvement:

  1. Adding a username property to the Open Graph metadata.
  2. Ensuring consistency between the openGraph and twitter image formats.

These changes significantly enhance the user profile representation and align well with best practices for web development.

components/background/background.tsx (2)

1-64: Overall assessment: Well-structured components with room for improvement

The Stars and Waves components are well-implemented, type-safe React components that provide reusable SVG graphics. They align with the PR objective of enhancing the visual identity and improving the representation of content.

Positive aspects:

  1. Use of TypeScript for type safety.
  2. Flexible prop handling with spread operator.
  3. Reusable and easily integrable components.

Areas for improvement:

  1. Enhance responsiveness by allowing dynamic sizing.
  2. Consider simplifying the complex path in the Waves component for better performance and maintainability.

These components contribute to the visual enhancement mentioned in the PR objectives. However, to fully meet the goal of incorporating article information into Open Graph images, ensure that these components are properly integrated with the article data rendering logic elsewhere in the codebase.

To confirm the integration of these components with article data, you could run:

✅ Verification successful

Integration Confirmed: Stars and Waves components are utilized in Open Graph functionality

The Stars and Waves components are successfully integrated within the app/og/route.tsx file, ensuring they contribute to the generation of Open Graph images as intended. This alignment supports the PR objective of enhancing visual identity and improving content representation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" --type tsx --type ts | rg -i "article|opengraph|og"

Length of output: 101


Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" -g '*.tsx' -g '*.ts'| rg -i "article|opengraph|og"

Length of output: 225


46-64: 🛠️ Refactor suggestion

Enhance responsiveness and consider simplifying the Waves component

The Waves component is well-structured but has some areas for improvement:

  1. Fixed dimensions may limit responsiveness.

  2. The single path element is quite complex, which might affect performance and maintainability.

  3. Improve responsiveness:
    Similar to the Stars component, consider accepting width and height as optional props and use viewBox for scaling. For example:

    exportconstWaves=({
    width =1200,
    height =638,
    ...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1200 638"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);
  4. Consider path complexity:
    The single path element is very complex. If possible, consider breaking it down into multiple simpler paths or using a different approach to create the wave effect. This could improve performance and make the component easier to maintain and modify in the future.

To assess the impact of the complex path on performance, you could run a performance profiling tool. Here's a script to check if there are any performance-related comments in the codebase:

Comment on lines +41 to +47
images: [
`/og?title=${encodeURIComponent(
post.title,
)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(
post.user.name,
)}&date=${post.updatedAt}`,
],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

readTimeMins is properly defined and usage is safe.

The readTimeMins property is consistently defined in the codebase, ensuring that its usage does not require additional null checks. This addresses and resolves the concern about potential undefined errors.

However, there is still an inconsistency between the openGraph.images and twitter.images properties that needs to be addressed to maintain metadata consistency across platforms.

🔗 Analysis chain

Improved Open Graph metadata with article details.

The addition of readTime, author, and date to the Open Graph image URL enhances the metadata, aligning with the PR objective. Good use of encodeURIComponent for proper URL encoding.

However, there are two points to consider:

  1. The twitter.images property hasn't been updated to match the new format used in openGraph.images. This could lead to inconsistency in metadata across platforms.

Consider updating the twitter.images property to match:

twitter: {description: post.excerpt,images: [`/og?title=${encodeURIComponent(post.title)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(post.user.name)}&date=${post.updatedAt}`],},
  1. The readTimeMins property is used without checking if it exists, which could potentially lead to errors if the property is undefined.

Consider adding a null check or providing a default value:

readTime=${post.readTimeMins??0}

Let's verify the existence and type of the readTimeMins property:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg --type typescript "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg --type typescript "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 402


Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 1935

Comment on lines +3 to +44
export const Stars = (
props: React.JSX.IntrinsicAttributes & React.SVGProps<SVGSVGElement>,
) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={1131}
height={601}
fill="none"
{...props}
>
<path
fill="#fff"
fillOpacity={0.2}
d="M104.227 331.67a4.949 4.949 0 1 1-9.896 0 4.949 4.949 0 1 1 9.896 0ZM866.23 36.452a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM151.009 220.963a2.25 2.25 0 1 1-4.5.002 2.25 2.25 0 0 1 4.5-.002ZM1110.04 374.873c0 1.242-1.01 2.25-2.25 2.25a2.246 2.246 0 0 1-2.25-2.25c0-1.243 1-2.25 2.25-2.25 1.24 0 2.25 1.007 2.25 2.25ZM358.828 85.055a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM1111.83 21.151a2.245 2.245 0 1 1-4.49 0 2.245 2.245 0 1 1 4.49 0ZM1096.54 149.859c0 1.243-1.01 2.25-2.25 2.25a2.251 2.251 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM729.484 111.157a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0ZM20.56 2.25a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M31.565 330.348a2.251 2.251 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM34.12 230.333a2.25 2.25 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM63.181 215.232a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.761 4.434ZM30.719 260.798a2.25 2.25 0 0 1 .76-4.436 2.251 2.251 0 0 1-.76 4.436ZM59.623 156.175a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.762 4.434ZM97.22 149.847a2.25 2.25 0 0 1 .762-4.436 2.25 2.25 0 0 1-.761 4.436ZM1077.05 141.685c.69-.572.78-1.588.2-2.27a1.6 1.6 0 0 0-2.26-.201 1.598 1.598 0 0 0-.2 2.271 1.6 1.6 0 0 0 2.26.2ZM1039.43 80.706c.69-.571.78-1.588.2-2.27a1.61 1.61 0 1 0-2.47 2.07c.58.682 1.59.772 2.27.2ZM1016.01 81.843a1.612 1.612 0 0 0-2.07-2.47 1.606 1.606 0 0 0-.2 2.27 1.61 1.61 0 0 0 2.27.2ZM1052.52 98.335a1.611 1.611 0 1 0-2.07-2.472 1.611 1.611 0 0 0 2.07 2.472ZM996.929 44.008a1.612 1.612 0 0 0-2.07-2.47 1.611 1.611 0 1 0 2.07 2.47ZM971.378 53.651a1.611 1.611 0 1 0-2.068-2.471 1.611 1.611 0 0 0 2.068 2.471Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M4.498 444.841a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M1128.37 438.118a2.256 2.256 0 0 1-1.84-2.598 2.255 2.255 0 0 1 2.6-1.838 2.25 2.25 0 1 1-.76 4.436Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M831.276 591.549a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.949 4.949 0 1 1 9.896 0ZM36.886 525.845a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.95 4.95 0 0 1 4.948-4.95 4.95 4.95 0 0 1 4.948 4.95ZM1030.1 580.749c0 1.242-1.01 2.25-2.25 2.25a2.252 2.252 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM599.166 562.748a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M462.42 584.349a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM363.458 598.75a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM343.666 572.648a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM394.046 596.95a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM286.088 586.149a2.249 2.249 0 1 1-4.498 0 2.25 2.25 0 1 1 4.498 0ZM273.493 550.147a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
</svg>
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider improving responsiveness of the Stars component

The Stars component is well-structured and uses TypeScript for type safety. However, the fixed dimensions (width: 1131, height: 601) might limit its responsiveness across different screen sizes.

Consider making the component more responsive by:

  1. Accepting width and height as optional props with default values.
  2. Using percentage values or viewBox for scaling.

Here's an example of how you could modify the component:

exportconstStars=({
width =1131,
height =601,
...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1131 601"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);

This change allows the component to be more flexible while maintaining its aspect ratio.

Comment threadapp/og/route.tsx
Comment on lines +24 to +31
const regularFontData = await fetch(
new URL("@/assets/Lato-Regular.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

const boldFontData = await fetch(
new URL("@/assets/Lato-Bold.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Suggestion: Fetch font data in parallel to improve performance

Currently, the font data for regular and bold fonts is fetched sequentially, which can lead to increased response times. Fetching both fonts in parallel will optimize performance by reducing the total fetch time.

Apply this diff to fetch font data in parallel:

- const regularFontData = await fetch(- new URL("@/assets/Lato-Regular.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());-- const boldFontData = await fetch(- new URL("@/assets/Lato-Bold.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());+ const [regularFontData, boldFontData] = await Promise.all([+ fetch(new URL("@/assets/Lato-Regular.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ fetch(new URL("@/assets/Lato-Bold.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ ]);
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constregularFontData=awaitfetch(
newURL("@/assets/Lato-Regular.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
constboldFontData=awaitfetch(
newURL("@/assets/Lato-Bold.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
const[regularFontData,boldFontData]=awaitPromise.all([
fetch(newURL("@/assets/Lato-Regular.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
fetch(newURL("@/assets/Lato-Bold.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
]);

Comment threadapp/og/route.tsx
Comment on lines +198 to +200
if (isNaN(date.getTime())) {
throw new Error("Invalid date");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Replace unsafe isNaN with Number.isNaN

Using the global isNaN function is unsafe because it performs type coercion, which may lead to unexpected results. The Number.isNaN method provides a more reliable check by ensuring the value is of the Number type and is actually NaN.

Apply this diff to fix the issue:

- if (isNaN(date.getTime())) {+ if (Number.isNaN(date.getTime())) {
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(isNaN(date.getTime())){
thrownewError("Invalid date");
}
if(Number.isNaN(date.getTime())){
thrownewError("Invalid date");
}
🧰 Tools
🪛 Biome

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@NiallJoeMaher
NiallJoeMaher merged commit 48708f0 into codu-code:developOct 17, 2024
@NiallJoeMaher
NiallJoeMaher deleted the feat/add-user-data-to-open-graph-images branch October 17, 2024 21:45
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@NiallJoeMaher
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Add user data to open graph images - #1144

Merged
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images
Oct 17, 2024
Merged

Add user data to open graph images#1144
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images

Conversation

@NiallJoeMaher

Copy link
Copy Markdown
Contributor

✨ Codu Pull Request 💻

Pull Request details

  • Add article information to Open Graph image
  • Update styles
  • Add custom fonts to the design
  • Refactor design
  • Remove from users profile

Any Breaking changes

  • None

Associated Screenshots

New Open Graph with new branding

* Add Lato fonts for image
* Remove unused images
* Add background SVGs as components
* Update user profile and articles to account for updates
@NiallJoeMaher
NiallJoeMaher requested a review from a team as a code ownerOctober 17, 2024 21:36
@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

@NiallJoeMaher is attempting to deploy a commit to the Codú Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitaiBot commented Oct 17, 2024

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces several modifications across multiple files to enhance metadata structures and improve accessibility. Key changes include updates to the generateMetadata functions for user profiles and articles, adding more descriptive titles and structured open graph metadata. The GET function in the routing file now requires additional query parameters with enhanced error handling. New React components for rendering graphics have been added, and error handling in an image processing function has been improved.

Changes

File PathChange Summary
app/(app)/[username]/page.tsxUpdated generateMetadata and Page functions for improved metadata and accessibility; added h1 for better structure.
app/(app)/articles/[slug]/page.tsxEnhanced generateMetadata for articles with additional context; updated image metadata parameters.
app/og/route.tsxModified GET function to require four query parameters; added error handling and new helper function formatDate.
cdk/lambdas/uploadResize/index.jsImproved error handling in resizeImage function; no changes to public entity declarations.
components/background/background.tsxIntroduced new components Stars and Waves for SVG rendering with TypeScript support.

Possibly related PRs

🐇 In the meadow, bright and fair,
New metadata fills the air.
With stars that twinkle, waves that flow,
Our profiles shine, as they grow!
Error handling, sleek and neat,
In CodeRabbit's world, it’s quite the treat! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

NameStatusPreviewCommentsUpdated (UTC)
codu✅ Ready (Inspect)Visit Preview💬 Add feedbackOct 17, 2024 9:43pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
app/(app)/[username]/page.tsx (2)

33-43: Enhanced Open Graph metadata structure.

The changes to the openGraph metadata are well-implemented:

  1. The type is now correctly set to "profile".
  2. The images array now contains a detailed object, which is more informative for the Open Graph protocol.
  3. The dynamic alt text improves accessibility.

Consider adding a username property to the Open Graph metadata, as it's specific to user profiles:

 openGraph: {
title,
description,
type: "profile",
+ username: username,
images: [
// ...
],
siteName: "Codú",
},

47-50: Improved Twitter card metadata, but consider consistency.

The addition of the card property enhances the Twitter metadata. However, the images array format is inconsistent with the openGraph images.

For consistency, consider updating the twitter.images to match the openGraph.images format:

 twitter: {
card: "summary_large_image",
title,
description,
- images: ["/images/og/home-og.png"],+ images: [+ {+ url: "/images/og/home-og.png",+ width: 1200,+ height: 630,+ alt: `${name || username}'s profile on Codú`,+ },+ ],
},

This change would provide more detailed image information for Twitter cards as well.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 556ae96 and 613c640.

⛔ Files ignored due to path filters (8)
  • assets/Lato-Bold.ttf is excluded by !**/*.ttf, !**/*.ttf
  • assets/Lato-Regular.ttf is excluded by !**/*.ttf, !**/*.ttf
  • public/images/og/noise.png is excluded by !**/*.png, !**/*.png
  • public/images/og/noise.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/planet.png is excluded by !**/*.png, !**/*.png
  • public/images/og/planet.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/stars.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/waves.svg is excluded by !**/*.svg, !**/*.svg
📒 Files selected for processing (5)
  • app/(app)/[username]/page.tsx (2 hunks)
  • app/(app)/articles/[slug]/page.tsx (1 hunks)
  • app/og/route.tsx (2 hunks)
  • cdk/lambdas/uploadResize/index.js (1 hunks)
  • components/background/background.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • cdk/lambdas/uploadResize/index.js
🧰 Additional context used
🪛 Biome
app/og/route.tsx

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (5)
app/(app)/[username]/page.tsx (3)

26-27: Improved metadata construction for better SEO and sharing.

The changes to title and description enhance the metadata by providing more context and using fallbacks. This is beneficial for SEO and when sharing the profile on various platforms.


120-123: Improved accessibility with semantic heading.

The addition of the h1 element with the sr-only class significantly enhances the page's accessibility. This provides a clear, high-level description of the page content for screen reader users without affecting the visual layout.


Line range hint 1-123: Overall assessment: Excellent improvements to metadata and accessibility.

The changes in this file successfully address the PR objectives by enhancing the Open Graph metadata, improving accessibility, and refining the overall structure. The modifications to the generateMetadata function and the Page component's return statement are particularly noteworthy for their positive impact on SEO, social media sharing, and screen reader compatibility.

A few minor suggestions were made for further improvement:

  1. Adding a username property to the Open Graph metadata.
  2. Ensuring consistency between the openGraph and twitter image formats.

These changes significantly enhance the user profile representation and align well with best practices for web development.

components/background/background.tsx (2)

1-64: Overall assessment: Well-structured components with room for improvement

The Stars and Waves components are well-implemented, type-safe React components that provide reusable SVG graphics. They align with the PR objective of enhancing the visual identity and improving the representation of content.

Positive aspects:

  1. Use of TypeScript for type safety.
  2. Flexible prop handling with spread operator.
  3. Reusable and easily integrable components.

Areas for improvement:

  1. Enhance responsiveness by allowing dynamic sizing.
  2. Consider simplifying the complex path in the Waves component for better performance and maintainability.

These components contribute to the visual enhancement mentioned in the PR objectives. However, to fully meet the goal of incorporating article information into Open Graph images, ensure that these components are properly integrated with the article data rendering logic elsewhere in the codebase.

To confirm the integration of these components with article data, you could run:

✅ Verification successful

Integration Confirmed: Stars and Waves components are utilized in Open Graph functionality

The Stars and Waves components are successfully integrated within the app/og/route.tsx file, ensuring they contribute to the generation of Open Graph images as intended. This alignment supports the PR objective of enhancing visual identity and improving content representation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" --type tsx --type ts | rg -i "article|opengraph|og"

Length of output: 101


Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" -g '*.tsx' -g '*.ts'| rg -i "article|opengraph|og"

Length of output: 225


46-64: 🛠️ Refactor suggestion

Enhance responsiveness and consider simplifying the Waves component

The Waves component is well-structured but has some areas for improvement:

  1. Fixed dimensions may limit responsiveness.

  2. The single path element is quite complex, which might affect performance and maintainability.

  3. Improve responsiveness:
    Similar to the Stars component, consider accepting width and height as optional props and use viewBox for scaling. For example:

    exportconstWaves=({
    width =1200,
    height =638,
    ...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1200 638"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);
  4. Consider path complexity:
    The single path element is very complex. If possible, consider breaking it down into multiple simpler paths or using a different approach to create the wave effect. This could improve performance and make the component easier to maintain and modify in the future.

To assess the impact of the complex path on performance, you could run a performance profiling tool. Here's a script to check if there are any performance-related comments in the codebase:

Comment on lines +41 to +47
images: [
`/og?title=${encodeURIComponent(
post.title,
)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(
post.user.name,
)}&date=${post.updatedAt}`,
],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

readTimeMins is properly defined and usage is safe.

The readTimeMins property is consistently defined in the codebase, ensuring that its usage does not require additional null checks. This addresses and resolves the concern about potential undefined errors.

However, there is still an inconsistency between the openGraph.images and twitter.images properties that needs to be addressed to maintain metadata consistency across platforms.

🔗 Analysis chain

Improved Open Graph metadata with article details.

The addition of readTime, author, and date to the Open Graph image URL enhances the metadata, aligning with the PR objective. Good use of encodeURIComponent for proper URL encoding.

However, there are two points to consider:

  1. The twitter.images property hasn't been updated to match the new format used in openGraph.images. This could lead to inconsistency in metadata across platforms.

Consider updating the twitter.images property to match:

twitter: {description: post.excerpt,images: [`/og?title=${encodeURIComponent(post.title)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(post.user.name)}&date=${post.updatedAt}`],},
  1. The readTimeMins property is used without checking if it exists, which could potentially lead to errors if the property is undefined.

Consider adding a null check or providing a default value:

readTime=${post.readTimeMins??0}

Let's verify the existence and type of the readTimeMins property:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg --type typescript "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg --type typescript "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 402


Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 1935

Comment on lines +3 to +44
export const Stars = (
props: React.JSX.IntrinsicAttributes & React.SVGProps<SVGSVGElement>,
) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={1131}
height={601}
fill="none"
{...props}
>
<path
fill="#fff"
fillOpacity={0.2}
d="M104.227 331.67a4.949 4.949 0 1 1-9.896 0 4.949 4.949 0 1 1 9.896 0ZM866.23 36.452a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM151.009 220.963a2.25 2.25 0 1 1-4.5.002 2.25 2.25 0 0 1 4.5-.002ZM1110.04 374.873c0 1.242-1.01 2.25-2.25 2.25a2.246 2.246 0 0 1-2.25-2.25c0-1.243 1-2.25 2.25-2.25 1.24 0 2.25 1.007 2.25 2.25ZM358.828 85.055a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM1111.83 21.151a2.245 2.245 0 1 1-4.49 0 2.245 2.245 0 1 1 4.49 0ZM1096.54 149.859c0 1.243-1.01 2.25-2.25 2.25a2.251 2.251 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM729.484 111.157a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0ZM20.56 2.25a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M31.565 330.348a2.251 2.251 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM34.12 230.333a2.25 2.25 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM63.181 215.232a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.761 4.434ZM30.719 260.798a2.25 2.25 0 0 1 .76-4.436 2.251 2.251 0 0 1-.76 4.436ZM59.623 156.175a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.762 4.434ZM97.22 149.847a2.25 2.25 0 0 1 .762-4.436 2.25 2.25 0 0 1-.761 4.436ZM1077.05 141.685c.69-.572.78-1.588.2-2.27a1.6 1.6 0 0 0-2.26-.201 1.598 1.598 0 0 0-.2 2.271 1.6 1.6 0 0 0 2.26.2ZM1039.43 80.706c.69-.571.78-1.588.2-2.27a1.61 1.61 0 1 0-2.47 2.07c.58.682 1.59.772 2.27.2ZM1016.01 81.843a1.612 1.612 0 0 0-2.07-2.47 1.606 1.606 0 0 0-.2 2.27 1.61 1.61 0 0 0 2.27.2ZM1052.52 98.335a1.611 1.611 0 1 0-2.07-2.472 1.611 1.611 0 0 0 2.07 2.472ZM996.929 44.008a1.612 1.612 0 0 0-2.07-2.47 1.611 1.611 0 1 0 2.07 2.47ZM971.378 53.651a1.611 1.611 0 1 0-2.068-2.471 1.611 1.611 0 0 0 2.068 2.471Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M4.498 444.841a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M1128.37 438.118a2.256 2.256 0 0 1-1.84-2.598 2.255 2.255 0 0 1 2.6-1.838 2.25 2.25 0 1 1-.76 4.436Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M831.276 591.549a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.949 4.949 0 1 1 9.896 0ZM36.886 525.845a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.95 4.95 0 0 1 4.948-4.95 4.95 4.95 0 0 1 4.948 4.95ZM1030.1 580.749c0 1.242-1.01 2.25-2.25 2.25a2.252 2.252 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM599.166 562.748a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M462.42 584.349a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM363.458 598.75a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM343.666 572.648a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM394.046 596.95a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM286.088 586.149a2.249 2.249 0 1 1-4.498 0 2.25 2.25 0 1 1 4.498 0ZM273.493 550.147a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
</svg>
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider improving responsiveness of the Stars component

The Stars component is well-structured and uses TypeScript for type safety. However, the fixed dimensions (width: 1131, height: 601) might limit its responsiveness across different screen sizes.

Consider making the component more responsive by:

  1. Accepting width and height as optional props with default values.
  2. Using percentage values or viewBox for scaling.

Here's an example of how you could modify the component:

exportconstStars=({
width =1131,
height =601,
...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1131 601"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);

This change allows the component to be more flexible while maintaining its aspect ratio.

Comment threadapp/og/route.tsx
Comment on lines +24 to +31
const regularFontData = await fetch(
new URL("@/assets/Lato-Regular.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

const boldFontData = await fetch(
new URL("@/assets/Lato-Bold.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Suggestion: Fetch font data in parallel to improve performance

Currently, the font data for regular and bold fonts is fetched sequentially, which can lead to increased response times. Fetching both fonts in parallel will optimize performance by reducing the total fetch time.

Apply this diff to fetch font data in parallel:

- const regularFontData = await fetch(- new URL("@/assets/Lato-Regular.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());-- const boldFontData = await fetch(- new URL("@/assets/Lato-Bold.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());+ const [regularFontData, boldFontData] = await Promise.all([+ fetch(new URL("@/assets/Lato-Regular.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ fetch(new URL("@/assets/Lato-Bold.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ ]);
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constregularFontData=awaitfetch(
newURL("@/assets/Lato-Regular.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
constboldFontData=awaitfetch(
newURL("@/assets/Lato-Bold.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
const[regularFontData,boldFontData]=awaitPromise.all([
fetch(newURL("@/assets/Lato-Regular.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
fetch(newURL("@/assets/Lato-Bold.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
]);

Comment threadapp/og/route.tsx
Comment on lines +198 to +200
if (isNaN(date.getTime())) {
throw new Error("Invalid date");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Replace unsafe isNaN with Number.isNaN

Using the global isNaN function is unsafe because it performs type coercion, which may lead to unexpected results. The Number.isNaN method provides a more reliable check by ensuring the value is of the Number type and is actually NaN.

Apply this diff to fix the issue:

- if (isNaN(date.getTime())) {+ if (Number.isNaN(date.getTime())) {
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(isNaN(date.getTime())){
thrownewError("Invalid date");
}
if(Number.isNaN(date.getTime())){
thrownewError("Invalid date");
}
🧰 Tools
🪛 Biome

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@NiallJoeMaher
NiallJoeMaher merged commit 48708f0 into codu-code:developOct 17, 2024
@NiallJoeMaher
NiallJoeMaher deleted the feat/add-user-data-to-open-graph-images branch October 17, 2024 21:45
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@NiallJoeMaher
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Add user data to open graph images - #1144

Merged
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images
Oct 17, 2024
Merged

Add user data to open graph images#1144
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images

Conversation

@NiallJoeMaher

Copy link
Copy Markdown
Contributor

✨ Codu Pull Request 💻

Pull Request details

  • Add article information to Open Graph image
  • Update styles
  • Add custom fonts to the design
  • Refactor design
  • Remove from users profile

Any Breaking changes

  • None

Associated Screenshots

New Open Graph with new branding

* Add Lato fonts for image
* Remove unused images
* Add background SVGs as components
* Update user profile and articles to account for updates
@NiallJoeMaher
NiallJoeMaher requested a review from a team as a code ownerOctober 17, 2024 21:36
@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

@NiallJoeMaher is attempting to deploy a commit to the Codú Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitaiBot commented Oct 17, 2024

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces several modifications across multiple files to enhance metadata structures and improve accessibility. Key changes include updates to the generateMetadata functions for user profiles and articles, adding more descriptive titles and structured open graph metadata. The GET function in the routing file now requires additional query parameters with enhanced error handling. New React components for rendering graphics have been added, and error handling in an image processing function has been improved.

Changes

File PathChange Summary
app/(app)/[username]/page.tsxUpdated generateMetadata and Page functions for improved metadata and accessibility; added h1 for better structure.
app/(app)/articles/[slug]/page.tsxEnhanced generateMetadata for articles with additional context; updated image metadata parameters.
app/og/route.tsxModified GET function to require four query parameters; added error handling and new helper function formatDate.
cdk/lambdas/uploadResize/index.jsImproved error handling in resizeImage function; no changes to public entity declarations.
components/background/background.tsxIntroduced new components Stars and Waves for SVG rendering with TypeScript support.

Possibly related PRs

🐇 In the meadow, bright and fair,
New metadata fills the air.
With stars that twinkle, waves that flow,
Our profiles shine, as they grow!
Error handling, sleek and neat,
In CodeRabbit's world, it’s quite the treat! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

NameStatusPreviewCommentsUpdated (UTC)
codu✅ Ready (Inspect)Visit Preview💬 Add feedbackOct 17, 2024 9:43pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
app/(app)/[username]/page.tsx (2)

33-43: Enhanced Open Graph metadata structure.

The changes to the openGraph metadata are well-implemented:

  1. The type is now correctly set to "profile".
  2. The images array now contains a detailed object, which is more informative for the Open Graph protocol.
  3. The dynamic alt text improves accessibility.

Consider adding a username property to the Open Graph metadata, as it's specific to user profiles:

 openGraph: {
title,
description,
type: "profile",
+ username: username,
images: [
// ...
],
siteName: "Codú",
},

47-50: Improved Twitter card metadata, but consider consistency.

The addition of the card property enhances the Twitter metadata. However, the images array format is inconsistent with the openGraph images.

For consistency, consider updating the twitter.images to match the openGraph.images format:

 twitter: {
card: "summary_large_image",
title,
description,
- images: ["/images/og/home-og.png"],+ images: [+ {+ url: "/images/og/home-og.png",+ width: 1200,+ height: 630,+ alt: `${name || username}'s profile on Codú`,+ },+ ],
},

This change would provide more detailed image information for Twitter cards as well.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 556ae96 and 613c640.

⛔ Files ignored due to path filters (8)
  • assets/Lato-Bold.ttf is excluded by !**/*.ttf, !**/*.ttf
  • assets/Lato-Regular.ttf is excluded by !**/*.ttf, !**/*.ttf
  • public/images/og/noise.png is excluded by !**/*.png, !**/*.png
  • public/images/og/noise.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/planet.png is excluded by !**/*.png, !**/*.png
  • public/images/og/planet.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/stars.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/waves.svg is excluded by !**/*.svg, !**/*.svg
📒 Files selected for processing (5)
  • app/(app)/[username]/page.tsx (2 hunks)
  • app/(app)/articles/[slug]/page.tsx (1 hunks)
  • app/og/route.tsx (2 hunks)
  • cdk/lambdas/uploadResize/index.js (1 hunks)
  • components/background/background.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • cdk/lambdas/uploadResize/index.js
🧰 Additional context used
🪛 Biome
app/og/route.tsx

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (5)
app/(app)/[username]/page.tsx (3)

26-27: Improved metadata construction for better SEO and sharing.

The changes to title and description enhance the metadata by providing more context and using fallbacks. This is beneficial for SEO and when sharing the profile on various platforms.


120-123: Improved accessibility with semantic heading.

The addition of the h1 element with the sr-only class significantly enhances the page's accessibility. This provides a clear, high-level description of the page content for screen reader users without affecting the visual layout.


Line range hint 1-123: Overall assessment: Excellent improvements to metadata and accessibility.

The changes in this file successfully address the PR objectives by enhancing the Open Graph metadata, improving accessibility, and refining the overall structure. The modifications to the generateMetadata function and the Page component's return statement are particularly noteworthy for their positive impact on SEO, social media sharing, and screen reader compatibility.

A few minor suggestions were made for further improvement:

  1. Adding a username property to the Open Graph metadata.
  2. Ensuring consistency between the openGraph and twitter image formats.

These changes significantly enhance the user profile representation and align well with best practices for web development.

components/background/background.tsx (2)

1-64: Overall assessment: Well-structured components with room for improvement

The Stars and Waves components are well-implemented, type-safe React components that provide reusable SVG graphics. They align with the PR objective of enhancing the visual identity and improving the representation of content.

Positive aspects:

  1. Use of TypeScript for type safety.
  2. Flexible prop handling with spread operator.
  3. Reusable and easily integrable components.

Areas for improvement:

  1. Enhance responsiveness by allowing dynamic sizing.
  2. Consider simplifying the complex path in the Waves component for better performance and maintainability.

These components contribute to the visual enhancement mentioned in the PR objectives. However, to fully meet the goal of incorporating article information into Open Graph images, ensure that these components are properly integrated with the article data rendering logic elsewhere in the codebase.

To confirm the integration of these components with article data, you could run:

✅ Verification successful

Integration Confirmed: Stars and Waves components are utilized in Open Graph functionality

The Stars and Waves components are successfully integrated within the app/og/route.tsx file, ensuring they contribute to the generation of Open Graph images as intended. This alignment supports the PR objective of enhancing visual identity and improving content representation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" --type tsx --type ts | rg -i "article|opengraph|og"

Length of output: 101


Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" -g '*.tsx' -g '*.ts'| rg -i "article|opengraph|og"

Length of output: 225


46-64: 🛠️ Refactor suggestion

Enhance responsiveness and consider simplifying the Waves component

The Waves component is well-structured but has some areas for improvement:

  1. Fixed dimensions may limit responsiveness.

  2. The single path element is quite complex, which might affect performance and maintainability.

  3. Improve responsiveness:
    Similar to the Stars component, consider accepting width and height as optional props and use viewBox for scaling. For example:

    exportconstWaves=({
    width =1200,
    height =638,
    ...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1200 638"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);
  4. Consider path complexity:
    The single path element is very complex. If possible, consider breaking it down into multiple simpler paths or using a different approach to create the wave effect. This could improve performance and make the component easier to maintain and modify in the future.

To assess the impact of the complex path on performance, you could run a performance profiling tool. Here's a script to check if there are any performance-related comments in the codebase:

Comment on lines +41 to +47
images: [
`/og?title=${encodeURIComponent(
post.title,
)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(
post.user.name,
)}&date=${post.updatedAt}`,
],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

readTimeMins is properly defined and usage is safe.

The readTimeMins property is consistently defined in the codebase, ensuring that its usage does not require additional null checks. This addresses and resolves the concern about potential undefined errors.

However, there is still an inconsistency between the openGraph.images and twitter.images properties that needs to be addressed to maintain metadata consistency across platforms.

🔗 Analysis chain

Improved Open Graph metadata with article details.

The addition of readTime, author, and date to the Open Graph image URL enhances the metadata, aligning with the PR objective. Good use of encodeURIComponent for proper URL encoding.

However, there are two points to consider:

  1. The twitter.images property hasn't been updated to match the new format used in openGraph.images. This could lead to inconsistency in metadata across platforms.

Consider updating the twitter.images property to match:

twitter: {description: post.excerpt,images: [`/og?title=${encodeURIComponent(post.title)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(post.user.name)}&date=${post.updatedAt}`],},
  1. The readTimeMins property is used without checking if it exists, which could potentially lead to errors if the property is undefined.

Consider adding a null check or providing a default value:

readTime=${post.readTimeMins??0}

Let's verify the existence and type of the readTimeMins property:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg --type typescript "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg --type typescript "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 402


Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 1935

Comment on lines +3 to +44
export const Stars = (
props: React.JSX.IntrinsicAttributes & React.SVGProps<SVGSVGElement>,
) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={1131}
height={601}
fill="none"
{...props}
>
<path
fill="#fff"
fillOpacity={0.2}
d="M104.227 331.67a4.949 4.949 0 1 1-9.896 0 4.949 4.949 0 1 1 9.896 0ZM866.23 36.452a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM151.009 220.963a2.25 2.25 0 1 1-4.5.002 2.25 2.25 0 0 1 4.5-.002ZM1110.04 374.873c0 1.242-1.01 2.25-2.25 2.25a2.246 2.246 0 0 1-2.25-2.25c0-1.243 1-2.25 2.25-2.25 1.24 0 2.25 1.007 2.25 2.25ZM358.828 85.055a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM1111.83 21.151a2.245 2.245 0 1 1-4.49 0 2.245 2.245 0 1 1 4.49 0ZM1096.54 149.859c0 1.243-1.01 2.25-2.25 2.25a2.251 2.251 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM729.484 111.157a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0ZM20.56 2.25a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M31.565 330.348a2.251 2.251 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM34.12 230.333a2.25 2.25 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM63.181 215.232a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.761 4.434ZM30.719 260.798a2.25 2.25 0 0 1 .76-4.436 2.251 2.251 0 0 1-.76 4.436ZM59.623 156.175a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.762 4.434ZM97.22 149.847a2.25 2.25 0 0 1 .762-4.436 2.25 2.25 0 0 1-.761 4.436ZM1077.05 141.685c.69-.572.78-1.588.2-2.27a1.6 1.6 0 0 0-2.26-.201 1.598 1.598 0 0 0-.2 2.271 1.6 1.6 0 0 0 2.26.2ZM1039.43 80.706c.69-.571.78-1.588.2-2.27a1.61 1.61 0 1 0-2.47 2.07c.58.682 1.59.772 2.27.2ZM1016.01 81.843a1.612 1.612 0 0 0-2.07-2.47 1.606 1.606 0 0 0-.2 2.27 1.61 1.61 0 0 0 2.27.2ZM1052.52 98.335a1.611 1.611 0 1 0-2.07-2.472 1.611 1.611 0 0 0 2.07 2.472ZM996.929 44.008a1.612 1.612 0 0 0-2.07-2.47 1.611 1.611 0 1 0 2.07 2.47ZM971.378 53.651a1.611 1.611 0 1 0-2.068-2.471 1.611 1.611 0 0 0 2.068 2.471Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M4.498 444.841a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M1128.37 438.118a2.256 2.256 0 0 1-1.84-2.598 2.255 2.255 0 0 1 2.6-1.838 2.25 2.25 0 1 1-.76 4.436Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M831.276 591.549a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.949 4.949 0 1 1 9.896 0ZM36.886 525.845a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.95 4.95 0 0 1 4.948-4.95 4.95 4.95 0 0 1 4.948 4.95ZM1030.1 580.749c0 1.242-1.01 2.25-2.25 2.25a2.252 2.252 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM599.166 562.748a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M462.42 584.349a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM363.458 598.75a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM343.666 572.648a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM394.046 596.95a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM286.088 586.149a2.249 2.249 0 1 1-4.498 0 2.25 2.25 0 1 1 4.498 0ZM273.493 550.147a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
</svg>
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider improving responsiveness of the Stars component

The Stars component is well-structured and uses TypeScript for type safety. However, the fixed dimensions (width: 1131, height: 601) might limit its responsiveness across different screen sizes.

Consider making the component more responsive by:

  1. Accepting width and height as optional props with default values.
  2. Using percentage values or viewBox for scaling.

Here's an example of how you could modify the component:

exportconstStars=({
width =1131,
height =601,
...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1131 601"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);

This change allows the component to be more flexible while maintaining its aspect ratio.

Comment threadapp/og/route.tsx
Comment on lines +24 to +31
const regularFontData = await fetch(
new URL("@/assets/Lato-Regular.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

const boldFontData = await fetch(
new URL("@/assets/Lato-Bold.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Suggestion: Fetch font data in parallel to improve performance

Currently, the font data for regular and bold fonts is fetched sequentially, which can lead to increased response times. Fetching both fonts in parallel will optimize performance by reducing the total fetch time.

Apply this diff to fetch font data in parallel:

- const regularFontData = await fetch(- new URL("@/assets/Lato-Regular.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());-- const boldFontData = await fetch(- new URL("@/assets/Lato-Bold.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());+ const [regularFontData, boldFontData] = await Promise.all([+ fetch(new URL("@/assets/Lato-Regular.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ fetch(new URL("@/assets/Lato-Bold.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ ]);
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constregularFontData=awaitfetch(
newURL("@/assets/Lato-Regular.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
constboldFontData=awaitfetch(
newURL("@/assets/Lato-Bold.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
const[regularFontData,boldFontData]=awaitPromise.all([
fetch(newURL("@/assets/Lato-Regular.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
fetch(newURL("@/assets/Lato-Bold.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
]);

Comment threadapp/og/route.tsx
Comment on lines +198 to +200
if (isNaN(date.getTime())) {
throw new Error("Invalid date");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Replace unsafe isNaN with Number.isNaN

Using the global isNaN function is unsafe because it performs type coercion, which may lead to unexpected results. The Number.isNaN method provides a more reliable check by ensuring the value is of the Number type and is actually NaN.

Apply this diff to fix the issue:

- if (isNaN(date.getTime())) {+ if (Number.isNaN(date.getTime())) {
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(isNaN(date.getTime())){
thrownewError("Invalid date");
}
if(Number.isNaN(date.getTime())){
thrownewError("Invalid date");
}
🧰 Tools
🪛 Biome

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@NiallJoeMaher
NiallJoeMaher merged commit 48708f0 into codu-code:developOct 17, 2024
@NiallJoeMaher
NiallJoeMaher deleted the feat/add-user-data-to-open-graph-images branch October 17, 2024 21:45
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@NiallJoeMaher
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Add user data to open graph images - #1144

Merged
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images
Oct 17, 2024
Merged

Add user data to open graph images#1144
NiallJoeMaher merged 3 commits into
codu-code:developfrom
NiallJoeMaher:feat/add-user-data-to-open-graph-images

Conversation

@NiallJoeMaher

Copy link
Copy Markdown
Contributor

✨ Codu Pull Request 💻

Pull Request details

  • Add article information to Open Graph image
  • Update styles
  • Add custom fonts to the design
  • Refactor design
  • Remove from users profile

Any Breaking changes

  • None

Associated Screenshots

New Open Graph with new branding

* Add Lato fonts for image
* Remove unused images
* Add background SVGs as components
* Update user profile and articles to account for updates
@NiallJoeMaher
NiallJoeMaher requested a review from a team as a code ownerOctober 17, 2024 21:36
@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

@NiallJoeMaher is attempting to deploy a commit to the Codú Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitaiBot commented Oct 17, 2024

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces several modifications across multiple files to enhance metadata structures and improve accessibility. Key changes include updates to the generateMetadata functions for user profiles and articles, adding more descriptive titles and structured open graph metadata. The GET function in the routing file now requires additional query parameters with enhanced error handling. New React components for rendering graphics have been added, and error handling in an image processing function has been improved.

Changes

File PathChange Summary
app/(app)/[username]/page.tsxUpdated generateMetadata and Page functions for improved metadata and accessibility; added h1 for better structure.
app/(app)/articles/[slug]/page.tsxEnhanced generateMetadata for articles with additional context; updated image metadata parameters.
app/og/route.tsxModified GET function to require four query parameters; added error handling and new helper function formatDate.
cdk/lambdas/uploadResize/index.jsImproved error handling in resizeImage function; no changes to public entity declarations.
components/background/background.tsxIntroduced new components Stars and Waves for SVG rendering with TypeScript support.

Possibly related PRs

🐇 In the meadow, bright and fair,
New metadata fills the air.
With stars that twinkle, waves that flow,
Our profiles shine, as they grow!
Error handling, sleek and neat,
In CodeRabbit's world, it’s quite the treat! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Oct 17, 2024

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

NameStatusPreviewCommentsUpdated (UTC)
codu✅ Ready (Inspect)Visit Preview💬 Add feedbackOct 17, 2024 9:43pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
app/(app)/[username]/page.tsx (2)

33-43: Enhanced Open Graph metadata structure.

The changes to the openGraph metadata are well-implemented:

  1. The type is now correctly set to "profile".
  2. The images array now contains a detailed object, which is more informative for the Open Graph protocol.
  3. The dynamic alt text improves accessibility.

Consider adding a username property to the Open Graph metadata, as it's specific to user profiles:

 openGraph: {
title,
description,
type: "profile",
+ username: username,
images: [
// ...
],
siteName: "Codú",
},

47-50: Improved Twitter card metadata, but consider consistency.

The addition of the card property enhances the Twitter metadata. However, the images array format is inconsistent with the openGraph images.

For consistency, consider updating the twitter.images to match the openGraph.images format:

 twitter: {
card: "summary_large_image",
title,
description,
- images: ["/images/og/home-og.png"],+ images: [+ {+ url: "/images/og/home-og.png",+ width: 1200,+ height: 630,+ alt: `${name || username}'s profile on Codú`,+ },+ ],
},

This change would provide more detailed image information for Twitter cards as well.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 556ae96 and 613c640.

⛔ Files ignored due to path filters (8)
  • assets/Lato-Bold.ttf is excluded by !**/*.ttf, !**/*.ttf
  • assets/Lato-Regular.ttf is excluded by !**/*.ttf, !**/*.ttf
  • public/images/og/noise.png is excluded by !**/*.png, !**/*.png
  • public/images/og/noise.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/planet.png is excluded by !**/*.png, !**/*.png
  • public/images/og/planet.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/stars.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/waves.svg is excluded by !**/*.svg, !**/*.svg
📒 Files selected for processing (5)
  • app/(app)/[username]/page.tsx (2 hunks)
  • app/(app)/articles/[slug]/page.tsx (1 hunks)
  • app/og/route.tsx (2 hunks)
  • cdk/lambdas/uploadResize/index.js (1 hunks)
  • components/background/background.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • cdk/lambdas/uploadResize/index.js
🧰 Additional context used
🪛 Biome
app/og/route.tsx

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (5)
app/(app)/[username]/page.tsx (3)

26-27: Improved metadata construction for better SEO and sharing.

The changes to title and description enhance the metadata by providing more context and using fallbacks. This is beneficial for SEO and when sharing the profile on various platforms.


120-123: Improved accessibility with semantic heading.

The addition of the h1 element with the sr-only class significantly enhances the page's accessibility. This provides a clear, high-level description of the page content for screen reader users without affecting the visual layout.


Line range hint 1-123: Overall assessment: Excellent improvements to metadata and accessibility.

The changes in this file successfully address the PR objectives by enhancing the Open Graph metadata, improving accessibility, and refining the overall structure. The modifications to the generateMetadata function and the Page component's return statement are particularly noteworthy for their positive impact on SEO, social media sharing, and screen reader compatibility.

A few minor suggestions were made for further improvement:

  1. Adding a username property to the Open Graph metadata.
  2. Ensuring consistency between the openGraph and twitter image formats.

These changes significantly enhance the user profile representation and align well with best practices for web development.

components/background/background.tsx (2)

1-64: Overall assessment: Well-structured components with room for improvement

The Stars and Waves components are well-implemented, type-safe React components that provide reusable SVG graphics. They align with the PR objective of enhancing the visual identity and improving the representation of content.

Positive aspects:

  1. Use of TypeScript for type safety.
  2. Flexible prop handling with spread operator.
  3. Reusable and easily integrable components.

Areas for improvement:

  1. Enhance responsiveness by allowing dynamic sizing.
  2. Consider simplifying the complex path in the Waves component for better performance and maintainability.

These components contribute to the visual enhancement mentioned in the PR objectives. However, to fully meet the goal of incorporating article information into Open Graph images, ensure that these components are properly integrated with the article data rendering logic elsewhere in the codebase.

To confirm the integration of these components with article data, you could run:

✅ Verification successful

Integration Confirmed: Stars and Waves components are utilized in Open Graph functionality

The Stars and Waves components are successfully integrated within the app/og/route.tsx file, ensuring they contribute to the generation of Open Graph images as intended. This alignment supports the PR objective of enhancing visual identity and improving content representation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" --type tsx --type ts | rg -i "article|opengraph|og"

Length of output: 101


Script:

#!/bin/bash# Search for usage of Stars and Waves components in relation to article or Open Graph related files
rg -i "Stars|Waves" -g '*.tsx' -g '*.ts'| rg -i "article|opengraph|og"

Length of output: 225


46-64: 🛠️ Refactor suggestion

Enhance responsiveness and consider simplifying the Waves component

The Waves component is well-structured but has some areas for improvement:

  1. Fixed dimensions may limit responsiveness.

  2. The single path element is quite complex, which might affect performance and maintainability.

  3. Improve responsiveness:
    Similar to the Stars component, consider accepting width and height as optional props and use viewBox for scaling. For example:

    exportconstWaves=({
    width =1200,
    height =638,
    ...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1200 638"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);
  4. Consider path complexity:
    The single path element is very complex. If possible, consider breaking it down into multiple simpler paths or using a different approach to create the wave effect. This could improve performance and make the component easier to maintain and modify in the future.

To assess the impact of the complex path on performance, you could run a performance profiling tool. Here's a script to check if there are any performance-related comments in the codebase:

Comment on lines +41 to +47
images: [
`/og?title=${encodeURIComponent(
post.title,
)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(
post.user.name,
)}&date=${post.updatedAt}`,
],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

readTimeMins is properly defined and usage is safe.

The readTimeMins property is consistently defined in the codebase, ensuring that its usage does not require additional null checks. This addresses and resolves the concern about potential undefined errors.

However, there is still an inconsistency between the openGraph.images and twitter.images properties that needs to be addressed to maintain metadata consistency across platforms.

🔗 Analysis chain

Improved Open Graph metadata with article details.

The addition of readTime, author, and date to the Open Graph image URL enhances the metadata, aligning with the PR objective. Good use of encodeURIComponent for proper URL encoding.

However, there are two points to consider:

  1. The twitter.images property hasn't been updated to match the new format used in openGraph.images. This could lead to inconsistency in metadata across platforms.

Consider updating the twitter.images property to match:

twitter: {description: post.excerpt,images: [`/og?title=${encodeURIComponent(post.title)}&readTime=${post.readTimeMins}&author=${encodeURIComponent(post.user.name)}&date=${post.updatedAt}`],},
  1. The readTimeMins property is used without checking if it exists, which could potentially lead to errors if the property is undefined.

Consider adding a null check or providing a default value:

readTime=${post.readTimeMins??0}

Let's verify the existence and type of the readTimeMins property:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg --type typescript "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg --type typescript "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 402


Script:

#!/bin/bash# Description: Check for the existence and usage of readTimeMins property in the codebase# Test 1: Check if readTimeMins is defined in any type definitionsecho"Checking for readTimeMins in type definitions:"
rg "readTimeMins.*:" -g "!*.test.ts" -g "!*.spec.ts"# Test 2: Check for usage of readTimeMins in the codebaseecho"\nChecking for usage of readTimeMins:"
rg "\.readTimeMins" -g "!*.test.ts" -g "!*.spec.ts"

Length of output: 1935

Comment on lines +3 to +44
export const Stars = (
props: React.JSX.IntrinsicAttributes & React.SVGProps<SVGSVGElement>,
) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={1131}
height={601}
fill="none"
{...props}
>
<path
fill="#fff"
fillOpacity={0.2}
d="M104.227 331.67a4.949 4.949 0 1 1-9.896 0 4.949 4.949 0 1 1 9.896 0ZM866.23 36.452a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM151.009 220.963a2.25 2.25 0 1 1-4.5.002 2.25 2.25 0 0 1 4.5-.002ZM1110.04 374.873c0 1.242-1.01 2.25-2.25 2.25a2.246 2.246 0 0 1-2.25-2.25c0-1.243 1-2.25 2.25-2.25 1.24 0 2.25 1.007 2.25 2.25ZM358.828 85.055a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0ZM1111.83 21.151a2.245 2.245 0 1 1-4.49 0 2.245 2.245 0 1 1 4.49 0ZM1096.54 149.859c0 1.243-1.01 2.25-2.25 2.25a2.251 2.251 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM729.484 111.157a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0ZM20.56 2.25a2.25 2.25 0 1 1-4.5.001 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M31.565 330.348a2.251 2.251 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM34.12 230.333a2.25 2.25 0 0 1 .761-4.436 2.25 2.25 0 0 1-.76 4.436ZM63.181 215.232a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.761 4.434ZM30.719 260.798a2.25 2.25 0 0 1 .76-4.436 2.251 2.251 0 0 1-.76 4.436ZM59.623 156.175a2.25 2.25 0 1 1 .762-4.434 2.25 2.25 0 0 1-.762 4.434ZM97.22 149.847a2.25 2.25 0 0 1 .762-4.436 2.25 2.25 0 0 1-.761 4.436ZM1077.05 141.685c.69-.572.78-1.588.2-2.27a1.6 1.6 0 0 0-2.26-.201 1.598 1.598 0 0 0-.2 2.271 1.6 1.6 0 0 0 2.26.2ZM1039.43 80.706c.69-.571.78-1.588.2-2.27a1.61 1.61 0 1 0-2.47 2.07c.58.682 1.59.772 2.27.2ZM1016.01 81.843a1.612 1.612 0 0 0-2.07-2.47 1.606 1.606 0 0 0-.2 2.27 1.61 1.61 0 0 0 2.27.2ZM1052.52 98.335a1.611 1.611 0 1 0-2.07-2.472 1.611 1.611 0 0 0 2.07 2.472ZM996.929 44.008a1.612 1.612 0 0 0-2.07-2.47 1.611 1.611 0 1 0 2.07 2.47ZM971.378 53.651a1.611 1.611 0 1 0-2.068-2.471 1.611 1.611 0 0 0 2.068 2.471Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M4.498 444.841a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M1128.37 438.118a2.256 2.256 0 0 1-1.84-2.598 2.255 2.255 0 0 1 2.6-1.838 2.25 2.25 0 1 1-.76 4.436Z"
/>
<path
fill="#fff"
fillOpacity={0.2}
d="M831.276 591.549a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.949 4.949 0 1 1 9.896 0ZM36.886 525.845a4.95 4.95 0 0 1-4.948 4.951 4.95 4.95 0 0 1-4.948-4.951 4.95 4.95 0 0 1 4.948-4.95 4.95 4.95 0 0 1 4.948 4.95ZM1030.1 580.749c0 1.242-1.01 2.25-2.25 2.25a2.252 2.252 0 0 1-2.25-2.25c0-1.243 1.01-2.25 2.25-2.25s2.25 1.007 2.25 2.25ZM599.166 562.748a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
<path
fill="#fff"
fillOpacity={0.27}
d="M462.42 584.349a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM363.458 598.75a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM343.666 572.648a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM394.046 596.95a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001ZM286.088 586.149a2.249 2.249 0 1 1-4.498 0 2.25 2.25 0 1 1 4.498 0ZM273.493 550.147a2.25 2.25 0 1 1-4.499.001 2.25 2.25 0 0 1 4.499-.001Z"
/>
</svg>
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider improving responsiveness of the Stars component

The Stars component is well-structured and uses TypeScript for type safety. However, the fixed dimensions (width: 1131, height: 601) might limit its responsiveness across different screen sizes.

Consider making the component more responsive by:

  1. Accepting width and height as optional props with default values.
  2. Using percentage values or viewBox for scaling.

Here's an example of how you could modify the component:

exportconstStars=({
width =1131,
height =601,
...props}: React.SVGProps<SVGSVGElement>&{width?: number;height?: number})=>(<svgxmlns="http://www.w3.org/2000/svg"width={width}height={height}viewBox="0 0 1131 601"preserveAspectRatio="xMidYMid meet"fill="none"{...props}>{/* ... rest of the SVG content ... */}</svg>);

This change allows the component to be more flexible while maintaining its aspect ratio.

Comment threadapp/og/route.tsx
Comment on lines +24 to +31
const regularFontData = await fetch(
new URL("@/assets/Lato-Regular.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

const boldFontData = await fetch(
new URL("@/assets/Lato-Bold.ttf", import.meta.url),
).then((res) => res.arrayBuffer());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Suggestion: Fetch font data in parallel to improve performance

Currently, the font data for regular and bold fonts is fetched sequentially, which can lead to increased response times. Fetching both fonts in parallel will optimize performance by reducing the total fetch time.

Apply this diff to fetch font data in parallel:

- const regularFontData = await fetch(- new URL("@/assets/Lato-Regular.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());-- const boldFontData = await fetch(- new URL("@/assets/Lato-Bold.ttf", import.meta.url),- ).then((res) => res.arrayBuffer());+ const [regularFontData, boldFontData] = await Promise.all([+ fetch(new URL("@/assets/Lato-Regular.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ fetch(new URL("@/assets/Lato-Bold.ttf", import.meta.url)).then((res) => res.arrayBuffer()),+ ]);
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constregularFontData=awaitfetch(
newURL("@/assets/Lato-Regular.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
constboldFontData=awaitfetch(
newURL("@/assets/Lato-Bold.ttf",import.meta.url),
).then((res)=>res.arrayBuffer());
const[regularFontData,boldFontData]=awaitPromise.all([
fetch(newURL("@/assets/Lato-Regular.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
fetch(newURL("@/assets/Lato-Bold.ttf",import.meta.url)).then((res)=>res.arrayBuffer()),
]);

Comment threadapp/og/route.tsx
Comment on lines +198 to +200
if (isNaN(date.getTime())) {
throw new Error("Invalid date");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Replace unsafe isNaN with Number.isNaN

Using the global isNaN function is unsafe because it performs type coercion, which may lead to unexpected results. The Number.isNaN method provides a more reliable check by ensuring the value is of the Number type and is actually NaN.

Apply this diff to fix the issue:

- if (isNaN(date.getTime())) {+ if (Number.isNaN(date.getTime())) {
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(isNaN(date.getTime())){
thrownewError("Invalid date");
}
if(Number.isNaN(date.getTime())){
thrownewError("Invalid date");
}
🧰 Tools
🪛 Biome

[error] 198-198: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@NiallJoeMaher
NiallJoeMaher merged commit 48708f0 into codu-code:developOct 17, 2024
@NiallJoeMaher
NiallJoeMaher deleted the feat/add-user-data-to-open-graph-images branch October 17, 2024 21:45
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@NiallJoeMaher