Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Enricobarbieri1997/og images dynamic generation #3995

Open
wants to merge 7 commits into
base: stage
Choose a base branch
from

Conversation

EnricoBarbieri1997
Copy link
Collaborator

What is the purpose of the change:

This PR introduces open graph parameters for various pages on the site and dynamic image preview for some of them

Linear Task

https://linear.app/osmosis/issue/POL-1986/custom-thumbnail-generation-prototype

Brief Changelog

  • Move getBaseUrl to url utils file
  • Add image generation edge function
  • Add open graph parameters

Copy link

vercel bot commented Dec 6, 2024

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

Name Status Preview Comments Updated (UTC)
osmosis-frontend ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 6, 2024 0:50am
3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
osmosis-frontend-datadog ⬜️ Ignored (Inspect) Visit Preview Dec 6, 2024 0:50am
osmosis-frontend-dev ⬜️ Ignored (Inspect) Visit Preview Dec 6, 2024 0:50am
osmosis-testnet ⬜️ Ignored (Inspect) Dec 6, 2024 0:50am

Copy link

vercel bot commented Dec 6, 2024

Someone is attempting to deploy a commit to the OsmoLabs Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Dec 6, 2024

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/web/pages/api/og-images/assets/[denom].tsx

Oops! Something went wrong! :(

ESLint: 8.50.0

ESLint couldn't find the config "next/core-web-vitals" to extend from. Please check that the name of the config is correct.

The config "next/core-web-vitals" was referenced from the config file in "/packages/web/.eslintrc.json".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

Walkthrough

The pull request introduces several changes across multiple files, primarily focusing on the generation of Open Graph images for cryptocurrency tokens. A new API endpoint is created to handle requests for these images, utilizing the edge runtime. Additionally, modifications are made to the AssetInfoPage component to improve the handling of page titles and Open Graph metadata. A new utility function for loading Google Fonts is added, and the getBaseUrl function is refactored for better modularity and clarity.

Changes

File Path Change Summary
packages/web/pages/api/og-images/assets/[denom].tsx Added an API endpoint for generating Open Graph images based on token denomination, with error handling and dynamic font loading.
packages/web/pages/assets/[denom].tsx Updated AssetInfoPage to use a new pageTitle variable for setting the page and Open Graph titles, and added an image URL.
packages/web/utils/og-images.ts Introduced loadGoogleFont function for fetching Google Fonts with error handling.
packages/web/utils/trpc.ts Replaced inline getBaseUrl function with an import statement from ~/utils/url.
packages/web/utils/url.ts Added getBaseUrl function to determine the base URL based on the environment.

Possibly related PRs

Suggested reviewers

  • JoseRFelix
  • jonator

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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (1)
packages/web/utils/og-images.ts (1)

5-5: Consider removing console.log in production code.

The console.log(url); statement may not be necessary in production and could expose internal URLs in logs.

If logging is not required, consider removing this line to clean up the console output.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2294d05 and f9201f7.

⛔ Files ignored due to path filters (2)
  • packages/web/package.json is excluded by !**/*.json
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock, !**/*.lock
📒 Files selected for processing (5)
  • packages/web/pages/api/og-images/assets/[denom].tsx (1 hunks)
  • packages/web/pages/assets/[denom].tsx (3 hunks)
  • packages/web/utils/og-images.ts (1 hunks)
  • packages/web/utils/trpc.ts (1 hunks)
  • packages/web/utils/url.ts (1 hunks)
🔇 Additional comments (4)
packages/web/pages/api/og-images/assets/[denom].tsx (2)

71-73: Verify lineHeight smaller than fontSize may cause text clipping.

The lineHeight is set to "60px", which is less than the fontSize of "70px". This may lead to text being clipped or not rendered properly.

Please verify if this styling produces the desired visual effect or adjust the lineHeight accordingly.


92-94: Verify lineHeight smaller than fontSize may cause text clipping.

The lineHeight is set to "30px", which is less than the fontSize of "54px". This may lead to text being clipped or not rendered properly.

Please verify if this styling produces the desired visual effect or adjust the lineHeight accordingly.

packages/web/utils/url.ts (1)

1-5: LGTM!

The getBaseUrl function is correctly implemented, providing the appropriate base URL based on the environment.

packages/web/utils/trpc.ts (1)

30-30: LGTM!

Importing getBaseUrl from ~/utils/url enhances code modularity and maintainability.

}
const token = tokenDetails;
const title = token.coinName;
const formattedTokenPrice = tokenPrice ? tokenPrice.toString(2) : "";
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect number formatting in 'formattedTokenPrice'.

The method toString(2) converts the number to a binary string. To format the price to two decimal places, use toFixed(2) instead.

Apply this diff to fix the issue:

-const formattedTokenPrice = tokenPrice ? tokenPrice.toString(2) : "";
+const formattedTokenPrice = tokenPrice ? tokenPrice.toFixed(2) : "";
📝 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
const formattedTokenPrice = tokenPrice ? tokenPrice.toString(2) : "";
const formattedTokenPrice = tokenPrice ? tokenPrice.toFixed(2) : "";

Comment on lines +27 to +30
const tokenDetails = getAsset({
assetLists: AssetLists,
anyDenom: tokenDenom,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for missing token details.

If getAsset does not find a matching asset, tokenDetails might be undefined, leading to errors when accessing its properties later.

Add a check to handle the case where tokenDetails is undefined.

Apply this diff:

 const tokenDetails = getAsset({
   assetLists: AssetLists,
   anyDenom: tokenDenom,
 });
+ if (!tokenDetails) {
+   return new Response("Asset not found", { status: 404 });
+ }
📝 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
const tokenDetails = getAsset({
assetLists: AssetLists,
anyDenom: tokenDenom,
});
const tokenDetails = getAsset({
assetLists: AssetLists,
anyDenom: tokenDenom,
});
if (!tokenDetails) {
return new Response("Asset not found", { status: 404 });
}

Comment on lines +54 to +55
fontFamily: "Inter",
}}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Inconsistent fontFamily name: 'Inter' vs 'Geist'.

The fontFamily is set to "Inter", but in the fonts array, the font is named "Geist". Ensure that the fontFamily matches the name defined in the fonts array to correctly apply the font.

Either change the fontFamily to "Geist" or update the name in the fonts array to "Inter".

Apply this diff to set the fontFamily to "Geist":

  style={{
-   fontFamily: "Inter",
+   fontFamily: "Geist",
  }}

Alternatively, change the name in the fonts array to "Inter":

          fonts: [
            {
-             name: "Geist",
+             name: "Inter",
              data: await loadGoogleFont(
                "Inter",
                token.coinDenom.toString() + title + formattedTokenPrice
              ),
              style: "normal",
            },
          ],

Committable suggestion skipped: line range outside the PR's diff.

@@ -0,0 +1,19 @@
export async function loadGoogleFont(font: string, text: string) {
const url = `https://fonts.googleapis.com/css2?family=${font}&text=${encodeURIComponent(
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential security issue: Encode font parameter to prevent injection attacks.

The font parameter is concatenated into the URL without encoding, which could lead to injection attacks if font contains special characters.

Apply this diff to encode font using encodeURIComponent:

 export async function loadGoogleFont(font: string, text: string) {
-  const url = `https://fonts.googleapis.com/css2?family=${font}&text=${encodeURIComponent(
+  const url = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(font)}&text=${encodeURIComponent(
     text
   )}`;
📝 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
const url = `https://fonts.googleapis.com/css2?family=${font}&text=${encodeURIComponent(
const url = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(font)}&text=${encodeURIComponent(

Comment on lines +181 to +183
url: `${getBaseUrl(true)}/api/og-images/assets/${
asset.coinDenom
}`,
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure asset.coinDenom is URL-encoded when constructing the image URL.

To handle special characters in asset.coinDenom, it's advisable to encode it when constructing the URL.

Apply this diff to encode asset.coinDenom:

                   {
                     url: `${getBaseUrl(true)}/api/og-images/assets/${
-                      asset.coinDenom
+                      encodeURIComponent(asset.coinDenom)
                     }`,
                     alt: title,
                   },
📝 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
url: `${getBaseUrl(true)}/api/og-images/assets/${
asset.coinDenom
}`,
url: `${getBaseUrl(true)}/api/og-images/assets/${
encodeURIComponent(asset.coinDenom)
}`,

Comment on lines +178 to +179
description: details?.description?.substring(0, 120) + "...",
images: [
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent 'undefined' in Open Graph description when details.description is absent.

When details.description is undefined, the expression adds "..." to undefined, resulting in "undefined..." in the Open Graph description.

Modify the code to handle undefined descriptions gracefully.

Apply this diff to fix the issue:

              openGraph={{
                title: pageTitle,
-               description: details?.description?.substring(0, 120) + "...",
+               description: details?.description
+                 ? details.description.substring(0, 120) + "..."
+                 : undefined,
                images: [
📝 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
description: details?.description?.substring(0, 120) + "...",
images: [
description: details?.description
? details.description.substring(0, 120) + "..."
: undefined,
images: [

Sign up for free to 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