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

Added image upload handling to CTA Card #1421

Merged
merged 5 commits into from
Jan 27, 2025
Merged

Added image upload handling to CTA Card #1421

merged 5 commits into from
Jan 27, 2025

Conversation

ronaldlangeveld
Copy link
Member

@ronaldlangeveld ronaldlangeveld commented Jan 27, 2025

ref https://linear.app/ghost/issue/PLG-323/add-image-upload-handling-to-cta-card

Summary by CodeRabbit

  • New Features

    • Enhanced Call To Action (CTA) card with new media upload and management capabilities.
    • Added ability to upload and remove images within the CTA card.
    • Integrated new props for improved media handling in the CTA card.
  • Tests

    • Added end-to-end tests for CTA card image upload and removal functionality.
    • Implemented test for image preview visibility after upload.

Copy link

coderabbitai bot commented Jan 27, 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.

packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx

Oops! Something went wrong! :(

ESLint: 8.57.0

ESLint couldn't find the config "react-app" to extend from. Please check that the name of the config is correct.

The config "react-app" was referenced from the config file in "/packages/koenig-lexical/.eslintrc.cjs".

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

Walkthrough

The pull request introduces enhanced media handling capabilities for the Call To Action (CTA) card in the Koenig-Lexical component. The changes focus on adding new props and methods to support image upload and removal functionality within the CtaCard and CallToActionNodeComponent. The modifications include adding onFileChange, setFileInputRef, and onRemoveMedia props, implementing file upload logic, and creating corresponding end-to-end tests to verify the new image management features.

Changes

File Change Summary
packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx Added new props: onFileChange, setFileInputRef, onRemoveMedia; updated prop types and default props; modified handleButtonColor for consistency.
packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx Introduced new methods: handleImageChange, onFileChange, onRemoveMedia; added fileInputRef and imageUploader; expanded context extraction for file upload capabilities.
packages/koenig-lexical/test/e2e/cards/cta-card.test.js Added new e2e tests for adding and removing CTA card image; included necessary imports for file path handling.

Possibly related PRs

Poem

🐰 A rabbit's tale of upload glee,
Media dancing, wild and free!
Click and choose, then watch it soar,
CTA cards now have so much more!
Hop, hop, hooray for image fun! 🖼️

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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.

@ronaldlangeveld ronaldlangeveld marked this pull request as ready for review January 27, 2025 06:14
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

🧹 Nitpick comments (3)
packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx (2)

93-95: Add file validation before upload.

Consider adding file type and size validation before proceeding with the upload.

 const onFileChange = async (e) => {
+    const files = e.target.files;
+    const file = files[0];
+    
+    if (!file.type.startsWith('image/')) {
+        editor.update(() => {
+            const node = $getNodeByKey(nodeKey);
+            node.uploadError = 'Please select an image file';
+        });
+        return;
+    }
+    
+    if (file.size > 5 * 1024 * 1024) { // 5MB limit
+        editor.update(() => {
+            const node = $getNodeByKey(nodeKey);
+            node.uploadError = 'Image size should be less than 5MB';
+        });
+        return;
+    }
+
     handleImageChange(e.target.files);
 };

97-103: Clear error states when removing media.

Consider clearing any error states when removing media to ensure a clean slate.

 const onRemoveMedia = () => {
     editor.update(() => {
         const node = $getNodeByKey(nodeKey);
         node.imageUrl = '';
         node.hasImage = false;
+        node.uploadError = null;
+        node.isLoading = false;
     });
 };
packages/koenig-lexical/test/e2e/cards/cta-card.test.js (1)

213-231: LGTM! Comprehensive test coverage for image functionality.

The test effectively covers:

  1. Image upload workflow
  2. Blob URL verification
  3. Image removal

However, consider adding tests for:

  1. Error scenarios (invalid file types, upload failures)
  2. Loading states
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5329fa2 and 35722e7.

📒 Files selected for processing (3)
  • packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (4 hunks)
  • packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx (4 hunks)
  • packages/koenig-lexical/test/e2e/cards/cta-card.test.js (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx

[error] 125-125: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

🔇 Additional comments (4)
packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx (2)

29-40: LGTM! Context and ref setup is well implemented.

The implementation correctly uses React hooks and context for file upload functionality.


120-134: LGTM! Props are correctly passed to CtaCard.

The implementation properly integrates the new image handling functionality with the CtaCard component.

🧰 Tools
🪛 Biome (1.9.4)

[error] 125-125: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (2)

82-85: LGTM! Props are well-defined with proper types and defaults.

The implementation:

  1. Correctly adds new image handling props
  2. Includes proper PropTypes definitions
  3. Provides appropriate default values

Also applies to: 337-340, 359-362


143-147: LGTM! MediaUploadSetting integration is correct.

The component properly utilizes the new image handling props.

Comment on lines +83 to +91
const handleImageChange = async (files) => {
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;
});
};
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 error handling and loading state management.

The image upload implementation should include:

  1. Error handling for failed uploads
  2. Loading state management for better UX
  3. File validation before upload

Consider this implementation:

 const handleImageChange = async (files) => {
+    try {
+        editor.update(() => {
+            const node = $getNodeByKey(nodeKey);
+            node.isLoading = true;
+        });
+
         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.isLoading = false;
         });
+    } catch (error) {
+        editor.update(() => {
+            const node = $getNodeByKey(nodeKey);
+            node.isLoading = false;
+            node.uploadError = error.message;
+        });
+    }
 };
📝 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 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;
});
};
const handleImageChange = async (files) => {
try {
editor.update(() => {
const node = $getNodeByKey(nodeKey);
node.isLoading = true;
});
const result = await imageUploader.upload(files);
editor.update(() => {
const node = $getNodeByKey(nodeKey);
node.imageUrl = result?.[0].url;
node.hasImage = true;
node.isLoading = false;
});
} catch (error) {
editor.update(() => {
const node = $getNodeByKey(nodeKey);
node.isLoading = false;
node.uploadError = error.message;
});
}
};

@codecov-commenter
Copy link

codecov-commenter commented Jan 27, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 90.83%. Comparing base (8c9fb13) to head (5c18f35).
Report is 28 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1421      +/-   ##
==========================================
+ Coverage   90.81%   90.83%   +0.02%     
==========================================
  Files         184      185       +1     
  Lines       17164    17224      +60     
  Branches     1899     1913      +14     
==========================================
+ Hits        15587    15645      +58     
- Misses       1567     1569       +2     
  Partials       10       10              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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 (3)
packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx (2)

94-104: Consider adding type checking for files.

While the handlers work correctly, consider adding type checking for the files to ensure only valid image files are processed:

 const onFileChange = async (e) => {
+    const files = e.target.files;
+    if (!files || !files.length) return;
+    
+    const file = files[0];
+    if (!file.type.startsWith('image/')) {
+        console.error('Invalid file type. Please upload an image.');
+        return;
+    }
+
     handleImageChange(e.target.files);
 };

131-131: Avoid assignment in expression.

The assignment in the ref callback makes the code less readable and was flagged by static analysis.

-setFileInputRef={ref => fileInputRef.current = ref}
+setFileInputRef={(ref) => {
+    fileInputRef.current = ref;
+}}
🧰 Tools
🪛 Biome (1.9.4)

[error] 131-131: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

packages/koenig-lexical/test/e2e/cards/cta-card.test.js (1)

213-231: Consider adding more test cases for robustness.

While the current test covers the basic flow, consider adding tests for:

  1. Invalid file types
  2. Upload failures
  3. Multiple file selection

Example test case for invalid file type:

test('rejects invalid file types', async function () {
    const filePath = path.relative(process.cwd(), __dirname + '/../fixtures/invalid.txt');
    
    await focusEditor(page);
    await insertCard(page, {cardName: 'call-to-action'});
    
    const fileChooserPromise = page.waitForEvent('filechooser');
    await page.click('[data-testid="media-upload-placeholder"]');
    
    const fileChooser = await fileChooserPromise;
    await fileChooser.setFiles([filePath]);
    
    const imgLocator = page.locator('[data-kg-card="call-to-action"] img[src^="blob:"]');
    await expect(imgLocator).not.toBeVisible();
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d835bd7 and 4a05742.

📒 Files selected for processing (3)
  • packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (5 hunks)
  • packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx (4 hunks)
  • packages/koenig-lexical/test/e2e/cards/cta-card.test.js (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx

[error] 131-131: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

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

3-3: LGTM! Required imports and context for file upload functionality.

The additions of useRef and fileUploader are appropriate for implementing file upload handling.

Also applies to: 29-29


37-40: Add error handling and loading state management.

The image upload implementation should include error handling and loading states for better user experience.

Also applies to: 84-92

packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (3)

83-85: LGTM! Props follow consistent naming convention.

The new props for file handling are well-named and consistent with the existing prop naming pattern.


143-143: LGTM! Proper prop forwarding to MediaUploadSetting.

The file handling props are correctly passed to the MediaUploadSetting component.

Also applies to: 146-147


339-341: LGTM! Complete PropTypes and defaultProps definitions.

The new props are properly typed with PropTypes and have appropriate default values.

Also applies to: 361-363

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

♻️ Duplicate comments (1)
packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx (1)

84-92: ⚠️ Potential issue

Add error handling and loading state management.

The image upload implementation should include error handling and loading state management for better UX.

 const handleImageChange = async (files) => {
+    try {
+        editor.update(() => {
+            const node = $getNodeByKey(nodeKey);
+            node.isLoading = true;
+        });
+
         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.isLoading = false;
         });
+    } catch (error) {
+        editor.update(() => {
+            const node = $getNodeByKey(nodeKey);
+            node.isLoading = false;
+            node.uploadError = error.message;
+        });
+    }
 };
🧹 Nitpick comments (2)
packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx (1)

132-132: Avoid assignment in expression.

The file input ref assignment should be moved out of the JSX for better readability.

-                setFileInputRef={ref => fileInputRef.current = ref}
+                setFileInputRef={ref => {
+                    fileInputRef.current = ref;
+                }}
🧰 Tools
🪛 Biome (1.9.4)

[error] 132-132: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

packages/koenig-lexical/test/e2e/cards/cta-card.test.js (1)

267-283: Add assertions for image dimensions and loading state.

The image preview test should verify:

  • Loading state during upload
  • Final image dimensions
  • Error state visibility
 test('has image preview', async function () {
     const filePath = path.relative(process.cwd(), __dirname + `/../fixtures/large-image.jpeg`);

     await focusEditor(page);
     await insertCard(page, {cardName: 'call-to-action'});

     const fileChooserPromise = page.waitForEvent('filechooser');
     await page.click('[data-testid="media-upload-placeholder"]');
     const fileChooser = await fileChooserPromise;
     await fileChooser.setFiles([filePath]);

+    // Verify loading state
+    await expect(page.locator('[data-testid="media-upload-loading"]')).toBeVisible();
+
     await page.waitForSelector('[data-testid="media-upload-filled"]');
     const previewImage = await page.locator('[data-testid="media-upload-filled"] img');
     await expect(previewImage).toBeVisible();
+
+    // Verify image dimensions
+    const dimensions = await previewImage.evaluate((img) => ({
+        width: img.naturalWidth,
+        height: img.naturalHeight
+    }));
+    expect(dimensions.width).toBeGreaterThan(0);
+    expect(dimensions.height).toBeGreaterThan(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 4a05742 and 5c18f35.

📒 Files selected for processing (2)
  • packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx (4 hunks)
  • packages/koenig-lexical/test/e2e/cards/cta-card.test.js (3 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx

[error] 132-132: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node 20.11.1

Comment on lines +94 to +96
const onFileChange = async (e) => {
handleImageChange(e.target.files);
};
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 file validation before upload.

The file input handler should validate the files before uploading.

 const onFileChange = async (e) => {
+    const files = e.target.files;
+    if (!files || files.length === 0) {
+        return;
+    }
+
+    const file = files[0];
+    const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
+    if (!validTypes.includes(file.type)) {
+        editor.update(() => {
+            const node = $getNodeByKey(nodeKey);
+            node.uploadError = 'Invalid file type. Please upload an image.';
+        });
+        return;
+    }
+
     handleImageChange(e.target.files);
 };
📝 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 onFileChange = async (e) => {
handleImageChange(e.target.files);
};
const onFileChange = async (e) => {
const files = e.target.files;
if (!files || files.length === 0) {
return;
}
const file = files[0];
const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!validTypes.includes(file.type)) {
editor.update(() => {
const node = $getNodeByKey(nodeKey);
node.uploadError = 'Invalid file type. Please upload an image.';
});
return;
}
handleImageChange(e.target.files);
};

Comment on lines +213 to +231
test('can add and remove CTA Card image', async function () {
const filePath = path.relative(process.cwd(), __dirname + `/../fixtures/large-image.jpeg`);

await focusEditor(page);
await insertCard(page, {cardName: 'call-to-action'});

const fileChooserPromise = page.waitForEvent('filechooser');

await page.click('[data-testid="media-upload-placeholder"]');

const fileChooser = await fileChooserPromise;
await fileChooser.setFiles([filePath]);

const imgLocator = page.locator('[data-kg-card="call-to-action"] img[src^="blob:"]');
const imgElement = await imgLocator.first();
await expect(imgElement).toHaveAttribute('src', /blob:/);
await page.click('[data-testid="media-upload-remove"]');
await expect(imgLocator).not.toBeVisible();
});
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 cases for error scenarios.

The image upload tests should cover error scenarios such as:

  • Invalid file types
  • Upload failures
  • Network errors

Here's an example test case to add:

test('shows error for invalid file type', async function () {
    const filePath = path.relative(process.cwd(), __dirname + '/../fixtures/invalid.txt');

    await focusEditor(page);
    await insertCard(page, {cardName: 'call-to-action'});

    const fileChooserPromise = page.waitForEvent('filechooser');
    await page.click('[data-testid="media-upload-placeholder"]');
    const fileChooser = await fileChooserPromise;
    await fileChooser.setFiles([filePath]);

    await expect(page.locator('[data-testid="upload-error"]')).toBeVisible();
    await expect(page.locator('[data-testid="upload-error"]')).toHaveText('Invalid file type. Please upload an image.');
});

@ronaldlangeveld ronaldlangeveld merged commit 94b551a into main Jan 27, 2025
2 checks passed
@ronaldlangeveld ronaldlangeveld deleted the plg-323 branch January 27, 2025 10:41
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.

2 participants