Skip to content

Improve user widget rendering and handle null cases #2376

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

Merged
merged 1 commit into from
Jan 22, 2025

Conversation

mohitb35
Copy link
Collaborator

Enhance the rendering logic for user widgets by passing the user slug for a more recognizable URL and preventing user=undefined in the iframe URL when the user is null.

- passes user slug for user in order to have a more recognizable url
- prevents possibility of `user=undefined` in iframe url
Copy link

vercel bot commented Jan 22, 2025

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

Name Status Preview Comments Updated (UTC)
planet-webapp-multi-tenancy-setup ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 22, 2025 4:14am
2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
planet-webapp ⬜️ Ignored (Inspect) Jan 22, 2025 4:14am
planet-webapp-temp ⬜️ Ignored (Inspect) Jan 22, 2025 4:14am

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

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.

npm warn config production Use --omit=dev instead.
npm error code ERESOLVE
npm error ERESOLVE could not resolve
npm error
npm error While resolving: eslint-config-airbnb@18.2.1
npm error Found: eslint@8.57.1
npm error node_modules/eslint
npm error dev eslint@"^8.26.0" from the root project
npm error peer eslint@"6 || 7 || 8" from @emotion/eslint-plugin@11.12.0
npm error node_modules/@emotion/eslint-plugin
npm error dev @emotion/eslint-plugin@"^11.12.0" from the root project
npm error 15 more (@eslint-community/eslint-utils, ...)
npm error
npm error Could not resolve dependency:
npm error peer eslint@"^5.16.0 || ^6.8.0 || ^7.2.0" from eslint-config-airbnb@18.2.1
npm error node_modules/eslint-config-airbnb
npm error dev eslint-config-airbnb@"^18.2.0" from the root project
npm error
npm error Conflicting peer dependency: eslint@7.32.0
npm error node_modules/eslint
npm error peer eslint@"^5.16.0 || ^6.8.0 || ^7.2.0" from eslint-config-airbnb@18.2.1
npm error node_modules/eslint-config-airbnb
npm error dev eslint-config-airbnb@"^18.2.0" from the root project
npm error
npm error Fix the upstream dependency conflict, or retry
npm error this command with --force or --legacy-peer-deps
npm error to accept an incorrect (and potentially broken) dependency resolution.
npm error
npm error
npm error For a full report see:
npm error /root/.npm/_logs/2025-01-22T04_03_58_151Z-eresolve-report.txt
npm error A complete log of this run can be found in: /root/.npm/_logs/2025-01-22T04_03_58_151Z-debug-0.log

Walkthrough

The pull request introduces modifications to the ProfilePage component's rendering logic in the widgets.tsx file. The changes primarily focus on adjusting the conditional rendering conditions for a widget iframe, specifically altering how the user object is checked and referenced. The primary modifications include changing the user existence check and updating the data source for the iframe URL from user.id to user.slug.

Changes

File Change Summary
pages/sites/[slug]/[locale]/profile/widgets.tsx - Modified user existence check from user?.isPrivate === false to user !== null
- Retained user.isPrivate check within the new conditional block
- Updated iframe source URL to use user.slug instead of user.id

Poem

🐰 A Rabbit's Render Tale 🌐

In widgets' realm, a change takes flight,
From nullable checks to a clearer sight,
Slug replaces ID with gentle grace,
A profile's window, now finds its place!

🔧 Code hops, logic leaps! 🐾


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 1

🧹 Nitpick comments (2)
pages/sites/[slug]/[locale]/profile/widgets.tsx (2)

57-69: Simplify the conditional rendering structure.

The null check is a good addition, but we can improve the code structure:

  1. Remove the unnecessary Fragment
  2. Simplify the nested conditions
-      {user !== null && (
-        <>
-          {user.isPrivate === false ? (
-            <div className={styles.widgetsContainer}>
-              <iframe
-                src={`${process.env.WIDGET_URL}?user=${user.slug}&tenantkey=${tenantConfig.id}`}
-                className={styles.widgetIFrame}
-              />
-            </div>
-          ) : (
-            <EmbedModal {...embedModalProps} />
-          )}
-        </>
-      )}
+      {user !== null &&
+        (user.isPrivate ? (
+          <EmbedModal {...embedModalProps} />
+        ) : (
+          <div className={styles.widgetsContainer}>
+            <iframe
+              src={`${process.env.WIDGET_URL}?user=${user.slug}&tenantkey=${tenantConfig.id}`}
+              className={styles.widgetIFrame}
+            />
+          </div>
+        ))
+      }
🧰 Tools
🪛 Biome (1.9.4)

[error] 58-69: Avoid using unnecessary Fragment.

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.
Unsafe fix: Remove the Fragment

(lint/complexity/noUselessFragments)


57-69: Improve type safety for user object properties.

Consider adding type guards to ensure safe access to user properties:

interface User {
  slug: string;
  isPrivate: boolean;
  // ... other properties
}

// Add type guard
function isValidUser(user: any): user is User {
  return user && 
    typeof user.slug === 'string' && 
    typeof user.isPrivate === 'boolean';
}

// Use in component
{user !== null && isValidUser(user) && (
  // ... rest of the code
)}

This ensures that required properties exist and are of the correct type before accessing them.

🧰 Tools
🪛 Biome (1.9.4)

[error] 58-69: Avoid using unnecessary Fragment.

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.
Unsafe fix: Remove the Fragment

(lint/complexity/noUselessFragments)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b10701 and 5874a7e.

📒 Files selected for processing (1)
  • pages/sites/[slug]/[locale]/profile/widgets.tsx (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
pages/sites/[slug]/[locale]/profile/widgets.tsx

[error] 58-69: Avoid using unnecessary Fragment.

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.
Unsafe fix: Remove the Fragment

(lint/complexity/noUselessFragments)

Comment on lines +61 to +64
<iframe
src={`${process.env.WIDGET_URL}?user=${user.slug}&tenantkey=${tenantConfig.id}`}
className={styles.widgetIFrame}
/>
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 22, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance iframe security and accessibility.

While using user.slug improves URL readability, the iframe implementation needs security and accessibility improvements:

 <iframe
-  src={`${process.env.WIDGET_URL}?user=${user.slug}&tenantkey=${tenantConfig.id}`}
+  src={`${process.env.WIDGET_URL}?user=${encodeURIComponent(user.slug)}&tenantkey=${encodeURIComponent(tenantConfig.id)}`}
   className={styles.widgetIFrame}
+  title="User Widget"
+  sandbox="allow-scripts allow-same-origin"
+  referrerPolicy="no-referrer"
 />

The changes:

  1. Encode URL parameters to prevent injection
  2. Add title for accessibility
  3. Add sandbox and referrerPolicy for security
📝 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
<iframe
src={`${process.env.WIDGET_URL}?user=${user.slug}&tenantkey=${tenantConfig.id}`}
className={styles.widgetIFrame}
/>
<iframe
src={`${process.env.WIDGET_URL}?user=${encodeURIComponent(user.slug)}&tenantkey=${encodeURIComponent(tenantConfig.id)}`}
className={styles.widgetIFrame}
title="User Widget"
sandbox="allow-scripts allow-same-origin"
referrerPolicy="no-referrer"
/>

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

These are not user content, but come from an api response.

Further sanitization is unnecessary.

Copy link
Contributor

Choose a reason for hiding this comment

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

@mohitb35 I understand - since these values come from validated API responses, additional URL encoding is unnecessary. Thank you for the clarification.


✏️ Learnings added
Learnt from: mohitb35
PR: Plant-for-the-Planet-org/planet-webapp#2376
File: pages/sites/[slug]/[locale]/profile/widgets.tsx:61-64
Timestamp: 2025-01-22T04:07:44.805Z
Learning: In the Plant-for-the-Planet webapp, URL parameters `user.slug` and `tenantConfig.id` used in iframe URLs are validated API response data and don't require additional URL encoding or sanitization.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@mohitb35 mohitb35 removed the request for review from sunilsabatp January 22, 2025 05:36
Copy link
Contributor

@mariahosfeld mariahosfeld left a comment

Choose a reason for hiding this comment

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

Looks good, can create a widget without issue.

@mariahosfeld mariahosfeld merged commit 36cb55c into develop Jan 22, 2025
9 checks passed
@mariahosfeld mariahosfeld deleted the feature/widgets-logic-update branch January 22, 2025 07:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants