Skip to content

Conversation

@sanne-san
Copy link
Contributor

@coderabbitai
Copy link

coderabbitai bot commented Feb 11, 2025

Warning

Rate limit exceeded

@ronaldlangeveld has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 8 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between d028e71 and dc8346b.

📒 Files selected for processing (2)
  • packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (2 hunks)
  • packages/kg-default-nodes/test/nodes/call-to-action.test.js (3 hunks)

Walkthrough

This pull request introduces updates to the call-to-action rendering logic. It adds validation for the buttonColor and backgroundColor properties in the ctaCardTemplate and renderCallToActionNode functions, defaulting to 'accent' and 'white' respectively if the provided values are missing or do not match the expected pattern. The changes also adjust how styles are applied by conditionally constructing the buttonStyle and reorganizing the HTML structure from a single div to a table layout that includes additional semantic containers. Furthermore, modifications have been made to the emailCTATemplate function by incorporating a new renderContent function and updating the layout structure. Updates in the test suite include new assertions for the imageWidth and imageHeight properties as well as adjustments to checks verifying the background color representation in the exported HTML.

Possibly related PRs


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

@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: 3

🧹 Nitpick comments (1)
packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (1)

6-9: Consider expanding color validation to support more formats.

The current regex pattern only allows letters, numbers, and hyphens, which might reject valid CSS color values like hex colors (#FF5733), RGB/RGBA, or HSL/HSLA formats. Consider using a more comprehensive color validation approach.

-    if (!dataset.buttonColor || !dataset.buttonColor.match(/^[a-zA-Z\d-]+$/)) {
+    const isValidColor = (color) => {
+        // Allow named colors, hex, rgb(a), hsl(a)
+        const colorRegex = /^(#[0-9A-Fa-f]{3,8}|rgb\(.*\)|rgba\(.*\)|hsl\(.*\)|hsla\(.*\)|[a-zA-Z\d-]+)$/;
+        return color && colorRegex.test(color);
+    };
+    if (!isValidColor(dataset.buttonColor)) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1396afb and 57244a7.

📒 Files selected for processing (1)
  • packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node 20.11.1

Comment on lines 12 to 14
const buttonStyle = dataset.buttonColor === 'accent'
? `style="color: ${dataset.buttonTextColor};"`
: `style="background-color: ${dataset.buttonColor}; color: ${dataset.buttonTextColor};"`;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security: Sanitize color values before interpolation.

Direct interpolation of user input (buttonColor, buttonTextColor) into style attributes could lead to XSS vulnerabilities. Ensure these values are properly sanitized.

+    const sanitizeColor = (color) => {
+        // Implement color value sanitization
+        return color.replace(/[^#,().\d\w%-]/g, '');
+    };
+
     const buttonStyle = dataset.buttonColor === 'accent' 
-        ? `style="color: ${dataset.buttonTextColor};"` 
-        : `style="background-color: ${dataset.buttonColor}; color: ${dataset.buttonTextColor};"`;
+        ? `style="color: ${sanitizeColor(dataset.buttonTextColor)};"` 
+        : `style="background-color: ${sanitizeColor(dataset.buttonColor)}; color: ${sanitizeColor(dataset.buttonTextColor)};"`;
📝 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 buttonStyle = dataset.buttonColor === 'accent'
? `style="color: ${dataset.buttonTextColor};"`
: `style="background-color: ${dataset.buttonColor}; color: ${dataset.buttonTextColor};"`;
const sanitizeColor = (color) => {
// Implement color value sanitization
return color.replace(/[^#,().\d\w%-]/g, '');
};
const buttonStyle = dataset.buttonColor === 'accent'
? `style="color: ${sanitizeColor(dataset.buttonTextColor)};"`
: `style="background-color: ${sanitizeColor(dataset.buttonColor)}; color: ${sanitizeColor(dataset.buttonTextColor)};"`;

Comment on lines 17 to 41
<div class="kg-card kg-cta-card kg-cta-bg-${dataset.backgroundColor} kg-cta-${dataset.layout}" data-layout="${dataset.layout}">
${dataset.hasSponsorLabel ? `
<div class="kg-sponsor-label">
<div class="kg-cta-sponsor-label">
Sponsored
</div>
` : ''}
<div class="kg-cta-content">
${dataset.hasImage ? `
<div class="kg-cta-image-container">
<img src="${dataset.imageUrl}" alt="CTA Image">
</div>
` : ''}
<div class="kg-cta-content-inner">
<div class="kg-cta-text">
${dataset.textValue}
</div>
${dataset.showButton ? `
<a href="${dataset.buttonUrl}" class="kg-cta-button ${buttonAccent}"
${buttonStyle}>
${dataset.buttonText}
</a>
` : ''}
</div>
</div>
</div>
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance security and accessibility.

  1. URLs are directly interpolated without sanitization, which could lead to XSS vulnerabilities.
  2. The image alt text is generic and not customizable, which impacts accessibility.
+    const sanitizeUrl = (url) => {
+        try {
+            const parsed = new URL(url);
+            return parsed.toString();
+        } catch {
+            return '#';
+        }
+    };
+
     return `
         <div class="kg-card kg-cta-card kg-cta-bg-${dataset.backgroundColor} kg-cta-${dataset.layout}" data-layout="${dataset.layout}">
             ${dataset.hasSponsorLabel ? `
                 <div class="kg-cta-sponsor-label">
                     Sponsored
                 </div>
             ` : ''}
             <div class="kg-cta-content">
                 ${dataset.hasImage ? `
                     <div class="kg-cta-image-container">
-                        <img src="${dataset.imageUrl}" alt="CTA Image">
+                        <img src="${sanitizeUrl(dataset.imageUrl)}" alt="${dataset.imageAltText || 'CTA Image'}">
                     </div>
                 ` : ''}
                 <div class="kg-cta-content-inner">
                     <div class="kg-cta-text">
                         ${dataset.textValue}
                     </div>
                     ${dataset.showButton ? `
-                        <a href="${dataset.buttonUrl}" class="kg-cta-button ${buttonAccent}"
+                        <a href="${sanitizeUrl(dataset.buttonUrl)}" class="kg-cta-button ${buttonAccent}"
📝 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
<div class="kg-card kg-cta-card kg-cta-bg-${dataset.backgroundColor} kg-cta-${dataset.layout}" data-layout="${dataset.layout}">
${dataset.hasSponsorLabel ? `
<div class="kg-sponsor-label">
<div class="kg-cta-sponsor-label">
Sponsored
</div>
` : ''}
<div class="kg-cta-content">
${dataset.hasImage ? `
<div class="kg-cta-image-container">
<img src="${dataset.imageUrl}" alt="CTA Image">
</div>
` : ''}
<div class="kg-cta-content-inner">
<div class="kg-cta-text">
${dataset.textValue}
</div>
${dataset.showButton ? `
<a href="${dataset.buttonUrl}" class="kg-cta-button ${buttonAccent}"
${buttonStyle}>
${dataset.buttonText}
</a>
` : ''}
</div>
</div>
</div>
const sanitizeUrl = (url) => {
try {
const parsed = new URL(url);
return parsed.toString();
} catch {
return '#';
}
};
return `
<div class="kg-card kg-cta-card kg-cta-bg-${dataset.backgroundColor} kg-cta-${dataset.layout}" data-layout="${dataset.layout}">
${dataset.hasSponsorLabel ? `
<div class="kg-cta-sponsor-label">
Sponsored
</div>
` : ''}
<div class="kg-cta-content">
${dataset.hasImage ? `
<div class="kg-cta-image-container">
<img src="${sanitizeUrl(dataset.imageUrl)}" alt="${dataset.imageAltText || 'CTA Image'}">
</div>
` : ''}
<div class="kg-cta-content-inner">
<div class="kg-cta-text">
${dataset.textValue}
</div>
${dataset.showButton ? `
<a href="${sanitizeUrl(dataset.buttonUrl)}" class="kg-cta-button ${buttonAccent}"
${buttonStyle}>
${dataset.buttonText}
</a>
` : ''}
</div>
</div>
</div>
`;

Copy link

@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

♻️ Duplicate comments (4)
packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (4)

6-9: ⚠️ Potential issue

Enhance color validation and sanitization.

The current color validation is too restrictive and may reject valid color formats (hex, rgb, hsl). Additionally, the validation logic is duplicated with backgroundColor.

As suggested in previous reviews, implement a comprehensive color validation and sanitization solution:

+// At the top of the file
+const isValidColor = (color) => {
+    const colorRegex = /^(#[0-9A-Fa-f]{3,8}|rgb\(.*\)|rgba\(.*\)|hsl\(.*\)|hsla\(.*\)|[a-zA-Z\d-]+)$/;
+    return color && colorRegex.test(color);
+};
+
+const sanitizeColor = (color) => {
+    return color.replace(/[^#,().\d\w%-]/g, '');
+};
+
 // In ctaCardTemplate
-if (!dataset.buttonColor || !dataset.buttonColor.match(/^[a-zA-Z\d-]+$/)) {
+if (!isValidColor(dataset.buttonColor)) {
     dataset.buttonColor = 'accent';
 }

12-14: ⚠️ Potential issue

Security: Sanitize color values before interpolation.

Direct interpolation of user input (buttonColor, buttonTextColor) into style attributes could lead to XSS vulnerabilities.

Apply color sanitization before interpolation:

 const buttonStyle = dataset.buttonColor === 'accent' 
-    ? `style="color: ${dataset.buttonTextColor};"` 
-    : `style="background-color: ${dataset.buttonColor}; color: ${dataset.buttonTextColor};"`;
+    ? `style="color: ${sanitizeColor(dataset.buttonTextColor)};"` 
+    : `style="background-color: ${sanitizeColor(dataset.buttonColor)}; color: ${sanitizeColor(dataset.buttonTextColor)};"`;

17-41: ⚠️ Potential issue

Enhance security and accessibility in web template.

The template has security and accessibility concerns:

  1. URLs are directly interpolated without sanitization
  2. Image alt text is generic and not customizable

Apply URL sanitization and improve accessibility:

+const sanitizeUrl = (url) => {
+    try {
+        const parsed = new URL(url);
+        return parsed.toString();
+    } catch {
+        return '#';
+    }
+};

-<img src="${dataset.imageUrl}" alt="CTA Image">
+<img src="${sanitizeUrl(dataset.imageUrl)}" alt="${dataset.imageAltText || 'CTA Image'}">

-<a href="${dataset.buttonUrl}" class="kg-cta-button ${buttonAccent}"
+<a href="${sanitizeUrl(dataset.buttonUrl)}" class="kg-cta-button ${buttonAccent}"

161-164: 🛠️ Refactor suggestion

Refactor duplicated color validation.

The color validation logic is duplicated from the buttonColor validation.

Use the shared color validation function:

-if (!dataset.backgroundColor || !dataset.backgroundColor.match(/^[a-zA-Z\d-]+$/)) {
+if (!isValidColor(dataset.backgroundColor)) {
     dataset.backgroundColor = 'white';
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 57244a7 and 8eec344.

📒 Files selected for processing (1)
  • packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node 20.11.1

Comment on lines 52 to 126
const renderContent = () => {
if (dataset.layout === 'minimal') {
return `
<tr>
<td class="kg-cta-content">
<table border="0" cellpadding="0" cellspacing="0" width="100%" class="kg-cta-content-wrapper">
<tr>
${dataset.hasImage ? `
<td class="kg-cta-image-container" width="64">
<img src="${dataset.imageUrl}" alt="CTA Image" class="kg-cta-image" width="64">
</td>
` : ''}
<td class="kg-cta-content-inner">
<div class="kg-cta-text">
${dataset.textValue}
</div>
${dataset.showButton ? `
<a href="${dataset.buttonUrl}"
class="kg-cta-button ${dataset.buttonColor === 'accent' ? 'kg-style-accent' : ''}"
style="${buttonStyle}">
${dataset.buttonText}
</a>
` : ''}
</td>
</tr>
</table>
</td>
</tr>
`;
}

return `
<tr>
<td class="kg-cta-content">
<table border="0" cellpadding="0" cellspacing="0" width="100%" class="kg-cta-content-wrapper">
${dataset.hasImage ? `
<tr>
<td class="kg-cta-image-container">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td>
<img src="${dataset.imageUrl}" alt="CTA Image" class="kg-cta-image">
</td>
</tr>
</table>
</td>
</tr>
` : ''}
<tr>
<td class="kg-cta-text">
${dataset.textValue}
</td>
</tr>
${dataset.showButton ? `
<tr>
<td>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td>
<a href="${dataset.buttonUrl}"
class="kg-cta-button ${dataset.buttonColor === 'accent' ? 'kg-style-accent' : ''}"
style="${buttonStyle}">
${dataset.buttonText}
</a>
</td>
</tr>
</table>
</td>
</tr>
` : ''}
</table>
</td>
</tr>
`;
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor email template for maintainability and security.

The email template has several issues:

  1. Same security vulnerabilities as the web template (unsanitized URLs and colors)
  2. Complex nested table structure with duplicated code between layouts

Consider these improvements:

  1. Extract common table structures into reusable functions:
const renderImageSection = (imageUrl, altText, minimal = false) => `
    <tr>
        <td class="kg-cta-image-container"${minimal ? ' width="64"' : ''}>
            <img src="${sanitizeUrl(imageUrl)}" 
                 alt="${altText || 'CTA Image'}" 
                 class="kg-cta-image"
                 ${minimal ? ' width="64"' : ''}>
        </td>
    </tr>
`;
  1. Apply the same security measures as the web template:
-<img src="${dataset.imageUrl}" alt="CTA Image" class="kg-cta-image">
+<img src="${sanitizeUrl(dataset.imageUrl)}" alt="${dataset.imageAltText || 'CTA Image'}" class="kg-cta-image">

-<a href="${dataset.buttonUrl}" 
+<a href="${sanitizeUrl(dataset.buttonUrl)}" 

Copy link

@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: 2

🧹 Nitpick comments (2)
packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (2)

24-26: Enhance image accessibility with descriptive alt text.

The generic alt text "CTA Image" is not descriptive enough for screen readers. Consider adding a property to allow customized alt text.

-<img src="${dataset.imageUrl}" alt="CTA Image">
+<img src="${dataset.imageUrl}" alt="${dataset.imageAltText || 'Call to action promotional image'}">

51-125: Refactor duplicated button rendering logic.

The button rendering logic is duplicated between minimal and default layouts. Consider extracting it into a helper function.

+const renderButton = (dataset, buttonStyle) => `
+    <a href="${dataset.buttonUrl}" 
+       class="kg-cta-button ${dataset.buttonColor === 'accent' ? 'kg-style-accent' : ''}"
+       style="${buttonStyle}">
+        ${dataset.buttonText}
+    </a>
+`;

 const renderContent = () => {
     if (dataset.layout === 'minimal') {
         // ... minimal layout code ...
-        <a href="${dataset.buttonUrl}" 
-           class="kg-cta-button ${dataset.buttonColor === 'accent' ? 'kg-style-accent' : ''}"
-           style="${buttonStyle}">
-            ${dataset.buttonText}
-        </a>
+        ${renderButton(dataset, buttonStyle)}
         // ... rest of minimal layout code ...
     }
     // ... default layout code ...
-    <a href="${dataset.buttonUrl}" 
-       class="kg-cta-button ${dataset.buttonColor === 'accent' ? 'kg-style-accent' : ''}"
-       style="${buttonStyle}">
-        ${dataset.buttonText}
-    </a>
+    ${renderButton(dataset, buttonStyle)}
     // ... rest of default layout code ...
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8eec344 and aece70e.

📒 Files selected for processing (2)
  • packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (2 hunks)
  • packages/kg-default-nodes/test/nodes/call-to-action.test.js (1 hunks)
🔇 Additional comments (1)
packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (1)

6-14: Security: Sanitize color values before interpolation.

Direct interpolation of user input (buttonColor, buttonTextColor) into style attributes could lead to XSS vulnerabilities.

Comment on lines 160 to 163
// Add validation for backgroundColor
if (!dataset.backgroundColor || !dataset.backgroundColor.match(/^[a-zA-Z\d-]+$/)) {
dataset.backgroundColor = 'white';
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Align backgroundColor validation with buttonColor validation.

The validation pattern for backgroundColor is more restrictive than buttonColor. Consider using the same pattern for consistency.

-if (!dataset.backgroundColor || !dataset.backgroundColor.match(/^[a-zA-Z\d-]+$/)) {
+if (!dataset.backgroundColor || !dataset.backgroundColor.match(/^[a-zA-Z\d-]+|#([a-fA-F\d]{3}|[a-fA-F\d]{6})$/)) {
📝 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
// Add validation for backgroundColor
if (!dataset.backgroundColor || !dataset.backgroundColor.match(/^[a-zA-Z\d-]+$/)) {
dataset.backgroundColor = 'white';
}
// Add validation for backgroundColor
if (!dataset.backgroundColor || !dataset.backgroundColor.match(/^[a-zA-Z\d-]+|#([a-fA-F\d]{3}|[a-fA-F\d]{6})$/)) {
dataset.backgroundColor = 'white';
}

const html = element.outerHTML.toString();
html.should.containEql('data-layout="minimal"');
html.should.containEql('background-color: green');
html.should.containEql('kg-cta-bg-green');
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add test coverage for color validation.

The test suite should include cases for color validation, including:

  • Valid hex colors
  • Invalid color formats
  • Default color fallbacks
it('validates buttonColor format', editorTest(function () {
    const testCases = [
        {input: '#123', expected: '#123'},
        {input: '#123456', expected: '#123456'},
        {input: 'invalid<script>', expected: 'accent'},
        {input: undefined, expected: 'accent'}
    ];
    
    testCases.forEach(({input, expected}) => {
        const node = new CallToActionNode({...dataset, buttonColor: input});
        const {element} = node.exportDOM(exportOptions);
        if (expected === 'accent') {
            element.outerHTML.should.containEql('kg-style-accent');
        } else {
            element.outerHTML.should.containEql(`background-color: ${expected}`);
        }
    });
}));

ronaldlangeveld and others added 5 commits February 12, 2025 15:24
- In order for us to resize the images properly, we need to set the
  dimentions of the images in order for us to ratio it correctly when it
gets scaled for different disply types, eg email
Copy link

@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: 0

🧹 Nitpick comments (1)
packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js (1)

21-22: Consider adding type validation and constraints for image dimensions.

To ensure data integrity and prevent rendering issues:

  1. Add type validation to ensure numeric values
  2. Consider adding min/max constraints for valid dimensions
  3. Document the expected format (pixels, percentage, etc.)

Example enhancement:

-        {name: 'imageWidth', default: null},
-        {name: 'imageHeight', default: null},
+        {name: 'imageWidth', default: null, validate: value => value === null || (typeof value === 'number' && value > 0)},
+        {name: 'imageHeight', default: null, validate: value => value === null || (typeof value === 'number' && value > 0)},
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 96df53b and 19c7141.

📒 Files selected for processing (2)
  • packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js (1 hunks)
  • packages/kg-default-nodes/test/nodes/call-to-action.test.js (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/kg-default-nodes/test/nodes/call-to-action.test.js
🔇 Additional comments (1)
packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js (1)

21-22: LGTM! The new image dimension properties are a valuable addition.

The imageWidth and imageHeight properties will help with proper image rendering and layout in the CTA card.

Copy link

@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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 19c7141 and 3eb9140.

📒 Files selected for processing (1)
  • packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node 20.11.1
🔇 Additional comments (1)
packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx (1)

10-10: LGTM!

The import is correctly placed and properly utilized in the handleImageChange function.

Comment on lines 94 to 106
const handleImageChange = async (files) => {
const imgPreviewUrl = URL.createObjectURL(files[0]);
const {width, height} = await getImageDimensions(imgPreviewUrl);
const result = await imageUploader.upload(files);
// reset original src so it can be replaced with preview and upload progress
editor.update(() => {
const node = $getNodeByKey(nodeKey);
node.imageUrl = result?.[0].url;
node.hasImage = true;
node.imageWidth = width;
node.imageHeight = height;
});
};
Copy link

@coderabbitai coderabbitai bot Feb 13, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add cleanup for the preview URL to prevent memory leaks.

The preview URL created with URL.createObjectURL should be revoked after use to free up memory.

Apply this diff to add cleanup:

 const handleImageChange = async (files) => {
     const imgPreviewUrl = URL.createObjectURL(files[0]);
-    const {width, height} = await getImageDimensions(imgPreviewUrl);
-    const result = await imageUploader.upload(files);
-    // reset original src so it can be replaced with preview and upload progress
-    editor.update(() => {
-        const node = $getNodeByKey(nodeKey);
-        node.imageUrl = result?.[0].url;
-        node.hasImage = true;
-        node.imageWidth = width;
-        node.imageHeight = height;
-    });
+    try {
+        const {width, height} = await getImageDimensions(imgPreviewUrl);
+        const result = await imageUploader.upload(files);
+        // reset original src so it can be replaced with preview and upload progress
+        editor.update(() => {
+            const node = $getNodeByKey(nodeKey);
+            node.imageUrl = result?.[0].url;
+            node.hasImage = true;
+            node.imageWidth = width;
+            node.imageHeight = height;
+        });
+    } finally {
+        URL.revokeObjectURL(imgPreviewUrl);
+    }
 };
📝 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 handleImageChange = async (files) => {
const imgPreviewUrl = URL.createObjectURL(files[0]);
const {width, height} = await getImageDimensions(imgPreviewUrl);
const result = await imageUploader.upload(files);
// reset original src so it can be replaced with preview and upload progress
editor.update(() => {
const node = $getNodeByKey(nodeKey);
node.imageUrl = result?.[0].url;
node.hasImage = true;
node.imageWidth = width;
node.imageHeight = height;
});
};
const handleImageChange = async (files) => {
const imgPreviewUrl = URL.createObjectURL(files[0]);
try {
const {width, height} = await getImageDimensions(imgPreviewUrl);
const result = await imageUploader.upload(files);
// reset original src so it can be replaced with preview and upload progress
editor.update(() => {
const node = $getNodeByKey(nodeKey);
node.imageUrl = result?.[0].url;
node.hasImage = true;
node.imageWidth = width;
node.imageHeight = height;
});
} finally {
URL.revokeObjectURL(imgPreviewUrl);
}
};

Copy link
Member

Choose a reason for hiding this comment

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

Would be good to add this in, ObjectURLs will stick around in memory and can use quite a bit when storing large images

Copy link

Choose a reason for hiding this comment

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

@kevinansfield Thanks for confirming! I'll make sure to flag this in future reviews where ObjectURLs are used without proper cleanup.


✏️ Learnings added
Learnt from: kevinansfield
PR: TryGhost/Koenig#1442
File: packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx:94-106
Timestamp: 2025-02-13T09:53:46.951Z
Learning: When using URL.createObjectURL() to create preview URLs for images, always clean up using URL.revokeObjectURL() to prevent memory leaks, as ObjectURLs can consume significant memory especially with large images. Use try/finally to ensure cleanup happens even if an error occurs.

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.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Copy link

@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: 0

♻️ Duplicate comments (3)
packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (3)

7-14: ⚠️ Potential issue

Security: Color values need sanitization.

Direct interpolation of user input (buttonColor, buttonTextColor) into style attributes could lead to XSS vulnerabilities.

+    const sanitizeColor = (color) => {
+        return color.replace(/[^#,().\d\w%-]/g, '');
+    };

     const buttonStyle = dataset.buttonColor === 'accent'
-        ? `style="color: ${dataset.buttonTextColor};"`
-        : `style="background-color: ${dataset.buttonColor}; color: ${dataset.buttonTextColor};"`;
+        ? `style="color: ${sanitizeColor(dataset.buttonTextColor)};"`
+        : `style="background-color: ${sanitizeColor(dataset.buttonColor)}; color: ${sanitizeColor(dataset.buttonTextColor)};"`;

16-40: ⚠️ Potential issue

Security and accessibility improvements needed.

  1. URLs are directly interpolated without sanitization
  2. Image alt text is not customizable
+    const sanitizeUrl = (url) => {
+        try {
+            const parsed = new URL(url);
+            return parsed.toString();
+        } catch {
+            return '#';
+        }
+    };

-                        <img src="${dataset.imageUrl}" alt="CTA Image">
+                        <img src="${sanitizeUrl(dataset.imageUrl)}" alt="${dataset.imageAltText || 'CTA Image'}">

-                        <a href="${dataset.buttonUrl}" class="kg-cta-button ${buttonAccent}"
+                        <a href="${sanitizeUrl(dataset.buttonUrl)}" class="kg-cta-button ${buttonAccent}"

63-137: 🛠️ Refactor suggestion

Refactor email template for maintainability and security.

The email template has several issues:

  1. Same security vulnerabilities as the web template
  2. Complex nested table structure with duplicated code

Consider extracting common table structures and applying security measures as suggested in the web template.

🧹 Nitpick comments (1)
packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (1)

50-61: Extract image dimension logic to a separate function.

The image dimension calculation logic could be extracted to improve readability and reusability.

+    const calculateImageDimensions = (width, height) => {
+        if (!width || !height) {
+            return null;
+        }
+
+        const dimensions = { width, height };
+        return width >= 560 ? resizeImage(dimensions, { width: 560 }) : dimensions;
+    };

-    let imageDimensions;
-    if (dataset.imageWidth && dataset.imageHeight) {
-        imageDimensions = {
-            width: dataset.imageWidth,
-            height: dataset.imageHeight
-        };
-
-        if (dataset.imageWidth >= 560) {
-            imageDimensions = resizeImage(imageDimensions, {width: 560});
-        }
-    }
+    const imageDimensions = calculateImageDimensions(dataset.imageWidth, dataset.imageHeight);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3eb9140 and 3777a50.

📒 Files selected for processing (2)
  • packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (2 hunks)
  • packages/kg-default-nodes/test/nodes/call-to-action.test.js (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/kg-default-nodes/test/nodes/call-to-action.test.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node 20.11.1
🔇 Additional comments (2)
packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (2)

140-149: LGTM! Clean and semantic table structure.

The outer table structure follows email HTML best practices with proper semantic classes and good separation of concerns.


173-176: Align backgroundColor validation with buttonColor validation.

The validation pattern for backgroundColor is more restrictive than buttonColor.

-if (!dataset.backgroundColor || !dataset.backgroundColor.match(/^[a-zA-Z\d-]+$/)) {
+if (!dataset.backgroundColor || !dataset.backgroundColor.match(/^[a-zA-Z\d-]+|#([a-fA-F\d]{3}|[a-fA-F\d]{6})$/)) {

import {renderWithVisibility} from '../../utils/visibility';
import {resizeImage} from '../../utils/resize-image';

// TODO - this is a placeholder for the cta card web template
Copy link
Member

Choose a reason for hiding this comment

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

I think this can be removed now 😄

@ronaldlangeveld ronaldlangeveld merged commit b328a6c into main Feb 13, 2025
2 checks passed
@ronaldlangeveld ronaldlangeveld deleted the ctacard-rendering branch February 13, 2025 10:51
kevinansfield pushed a commit to TryGhost/Ghost that referenced this pull request May 27, 2025
* Updated html markup for CTA card frontend rendering

Ref https://linear.app/ghost/issue/PLG-337/create-cta-card-web-design

* Updated CTA card email rendering

Ref https://linear.app/ghost/issue/PLG-336/create-cta-card-email-design

* Fixed regex not taking hex color into account

* Added sponsorLabel to email

* Cleanup

* Updated email CTA card rendering

Ref https://linear.app/ghost/issue/PLG-336/create-cta-card-email-design

* Added image sizes to CTA Card Node

- In order for us to resize the images properly, we need to set the
  dimentions of the images in order for us to ratio it correctly when it
gets scaled for different disply types, eg email

* Added width / height loading to uploader

* Added height and width to email rendering

* Added cleanup to image change

ref TryGhost/Koenig#1442

* Added imageWidth and imageHeight to remove media

no issue

* Fixed test

* Cleanup todo comments

---------

Co-authored-by: Ronald Langeveld <[email protected]>
kevinansfield pushed a commit to TryGhost/Ghost that referenced this pull request May 28, 2025
* Updated html markup for CTA card frontend rendering

Ref https://linear.app/ghost/issue/PLG-337/create-cta-card-web-design

* Updated CTA card email rendering

Ref https://linear.app/ghost/issue/PLG-336/create-cta-card-email-design

* Fixed regex not taking hex color into account

* Added sponsorLabel to email

* Cleanup

* Updated email CTA card rendering

Ref https://linear.app/ghost/issue/PLG-336/create-cta-card-email-design

* Added image sizes to CTA Card Node

- In order for us to resize the images properly, we need to set the
  dimentions of the images in order for us to ratio it correctly when it
gets scaled for different disply types, eg email

* Added width / height loading to uploader

* Added height and width to email rendering

* Added cleanup to image change

ref TryGhost/Koenig#1442

* Added imageWidth and imageHeight to remove media

no issue

* Fixed test

* Cleanup todo comments

---------

Co-authored-by: Ronald Langeveld <[email protected]>
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.

3 participants