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

[PE-69] fix: image restoration fixed for new images in private bucket #5839

Open
wants to merge 15 commits into
base: preview
Choose a base branch
from

Conversation

Palanikannan1437
Copy link
Collaborator

@Palanikannan1437 Palanikannan1437 commented Oct 15, 2024

Description

  1. Image restoration fixed
  2. Image resize fixed for mobile
  3. Aspect ratio updated for old images

Summary by CodeRabbit

  • New Features

    • Enhanced handling of image attributes, including the introduction of an aspectRatio attribute.
    • Added a new command for restoring images based on their source.
    • Improved error handling during image loading with new state variables for tracking load errors.
  • Bug Fixes

    • Implemented validation to ensure only images with valid HTTP sources are processed for restoration.
  • Refactor

    • Streamlined code structure and improved clarity by renaming variables and consolidating types across components.
    • Updated logic for placeholder visibility based on editor state.

@Palanikannan1437 Palanikannan1437 marked this pull request as ready for review October 17, 2024 14:16
Copy link
Contributor

coderabbitai bot commented Oct 17, 2024

Walkthrough

The changes in this pull request introduce significant enhancements to image handling within the editor. Key modifications include the addition of a restoreImage command, improved naming conventions, and validation checks for image sources. The CustomImageBlock and CustomImageUploader components have been refactored to enhance error handling and streamline the props interface. New attributes, such as aspectRatio, have been added to various image-related components, improving the overall robustness and clarity of the image handling logic.

Changes

File Path Change Summary
packages/editor/src/core/extensions/custom-image/custom-image.ts Added restoreImage command, improved naming conventions, and introduced validation for image sources.
packages/editor/src/core/extensions/image/extension.tsx Renamed functions for clarity and added a new aspectRatio attribute in the addAttributes method.
packages/editor/src/core/extensions/custom-image/components/image-block.tsx Refactored CustomImageBlock to improve error handling during image loading and resizing. Introduced new state variables for better management of error states.
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx Restructured props interface for CustomImageUploader to enhance clarity while maintaining existing functionality.
packages/editor/src/core/extensions/image/image-extension-without-props.tsx Added aspectRatio attribute with default value null in the ImageExtensionWithoutProps function.
packages/editor/src/core/extensions/image/read-only-image.tsx Introduced aspectRatio attribute with default value null in the ReadOnlyImageExtension.
packages/editor/src/core/extensions/extensions.tsx Updated placeholder visibility logic to include checks for the imageComponent state.

Possibly related PRs

Suggested labels

🐛bug, 🌟improvement, ✨feature, ✍️editor

Suggested reviewers

  • SatishGandham
  • aaryan610

🐰 In the garden where images bloom,
A new aspect ratio dispels the gloom.
With clearer paths and error checks,
Our images shine, what a fine effect!
So hop along, let’s celebrate,
For the changes here are truly great! 🌼


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.

@Palanikannan1437 Palanikannan1437 marked this pull request as draft October 17, 2024 14:16
@Palanikannan1437 Palanikannan1437 self-assigned this Oct 17, 2024
@Palanikannan1437 Palanikannan1437 marked this pull request as ready for review October 17, 2024 14:29
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 (6)
packages/editor/src/core/extensions/image/image-extension-without-props.tsx (1)

14-16: Approved: Addition of aspectRatio attribute, but documentation needed.

The addition of the aspectRatio attribute is a good improvement and aligns with the PR objectives. It follows the existing code structure and provides flexibility for image handling.

However, to enhance code maintainability and clarity:

  1. Please add a comment explaining how aspectRatio will be used in conjunction with width and height.
  2. Consider documenting any specific logic or constraints related to these attributes (e.g., if aspectRatio takes precedence over height when width is set).
packages/editor/src/core/extensions/image/read-only-image.tsx (1)

21-23: LGTM! Consider adding a type annotation for consistency.

The addition of the aspectRatio attribute aligns well with the PR objectives and follows the existing pattern for image attributes. This change will allow for better control over image display, particularly for older images as mentioned in the PR description.

For consistency with the width and height attributes, consider adding a type annotation to the aspectRatio attribute. This would improve type safety and make the code more self-documenting. Here's a suggested modification:

 aspectRatio: {
-  default: null,
+  default: null as number | null,
 },
packages/editor/src/core/plugins/image/restore-image.ts (1)

28-30: Approve with minor suggestions for improvement

The added condition aligns well with the PR objective of fixing image restoration for new images. It effectively filters out images that are likely from a private bucket, allowing them to be handled differently.

However, I have a couple of suggestions for improvement:

  1. Consider including 'https' explicitly in the condition for clarity:

    if (!node.attrs.src.startsWith("http") && !node.attrs.src.startsWith("https")) return;
  2. The comment could be slightly more precise. Consider updating it to:

    // If the src is just an id (private bucket), we don't need to handle restoration here.
    // This will be handled when the image fails to load.

These minor changes would enhance the clarity and robustness of the code.

packages/editor/src/core/extensions/image/extension.tsx (2)

39-42: Improved image source validation with unnecessary logging

The addition of a check to ensure the image source starts with "http" is a good improvement for input validation. However, there's an unnecessary console.log statement that should be removed.

Consider removing the console.log statement on line 39:

- console.log("node", node.attrs.src.startsWith("http"));

73-75: New aspectRatio attribute added

The addition of the aspectRatio attribute with a default value of null is a good improvement. This can be useful for maintaining image proportions during resizing or layout adjustments.

Consider adding a brief comment explaining the purpose and usage of the aspectRatio attribute, for example:

aspectRatio: {
  default: null,
  // The aspect ratio of the image (width/height). Set to null for automatic calculation.
},
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (1)

Image resizing for mobile devices not addressed.

The CustomImageUploader component shows improvements in handling aspect ratios through the aspectRatio property. However, the PR objectives mention fixing image resizing for mobile devices and updating aspect ratios for older images, which are not reflected in the current changes.

  • Missing Image Resizing for Mobile Devices: No implementations found that handle responsive image resizing specific to mobile viewports.

Please address the image resizing functionality to ensure images display correctly across different device sizes.

🔗 Analysis chain

Line range hint 1-180: Overall improvements in type safety and code organization, but some PR objectives not addressed.

The changes in this file significantly improve type safety and code organization for the CustomImageUploader component. The new type definitions and prop structure enhance maintainability and readability.

However, I noticed that the PR objectives mention fixing image resizing for mobile devices and updating aspect ratios for older images. These specific changes are not evident in this file.

To ensure we're not missing any relevant changes, let's check for related files:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for files that might contain image resizing or aspect ratio logic
rg -t tsx -t ts "image.*resize|aspect.*ratio" --ignore-case

Length of output: 89


Script:

#!/bin/bash
# Search for files that might contain image resizing or aspect ratio logic
rg -g "*.ts" -g "*.tsx" "image.*resize|aspect.*ratio" --ignore-case

Length of output: 5752


Script:

#!/bin/bash
# Search for files that might contain image resizing logic with varied terminology
rg -g "*.ts" -g "*.tsx" "(image.*resize|resize.*image|responsive.*image|image.*dimensions)" --ignore-case

Length of output: 1237

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9530884 and 7f36c26.

📒 Files selected for processing (8)
  • packages/editor/src/core/extensions/custom-image/components/image-block.tsx (11 hunks)
  • packages/editor/src/core/extensions/custom-image/components/image-node.tsx (3 hunks)
  • packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (2 hunks)
  • packages/editor/src/core/extensions/custom-image/custom-image.ts (4 hunks)
  • packages/editor/src/core/extensions/image/extension.tsx (3 hunks)
  • packages/editor/src/core/extensions/image/image-extension-without-props.tsx (1 hunks)
  • packages/editor/src/core/extensions/image/read-only-image.tsx (1 hunks)
  • packages/editor/src/core/plugins/image/restore-image.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (18)
packages/editor/src/core/extensions/image/read-only-image.tsx (1)

Line range hint 1-38: Verify completeness of image handling improvements

While the addition of the aspectRatio attribute is a good step towards improving image handling, it's important to ensure that all objectives mentioned in the PR description are addressed:

  1. Image restoration for new images
  2. Image resizing correction for mobile devices
  3. Aspect ratio updates for older images

To ensure these objectives are fully met, please run the following checks:

Additionally, consider the following questions:

  1. How is the new aspectRatio attribute being used in the CustomImageNode component?
  2. Are there any other components or utilities that need to be updated to fully implement the image handling improvements mentioned in the PR description?
  3. Have appropriate tests been added or updated to cover these changes?

Consider documenting the rationale behind adding the aspectRatio attribute and how it relates to the overall image handling strategy in the project. This could be valuable for future maintenance and onboarding of new developers.

packages/editor/src/core/extensions/image/extension.tsx (3)

15-16: Improved function parameter naming

The renaming of delete to deleteImageFn and restore to restoreImageFn enhances code readability and clarity. These new names are more descriptive and better convey the purpose of these functions.


30-31: Consistent use of renamed functions in plugins

The TrackImageDeletionPlugin and TrackImageRestorationPlugin now correctly use the renamed deleteImageFn and restoreImageFn functions. This change maintains consistency with the earlier parameter renaming.


48-48: Consistent use of renamed restore function

The restoreImage function call has been correctly updated to use restoreImageFn, maintaining consistency with the earlier parameter renaming.

packages/editor/src/core/extensions/custom-image/components/image-node.tsx (5)

2-2: LGTM: Import statement updated correctly.

The addition of NodeViewProps to the import statement from @tiptap/react is consistent with the type changes in the file and necessary for the updated type definitions.


6-14: Excellent: New type definition enhances type safety and clarity.

The introduction of CustomImageComponentProps type is a great improvement:

  1. It consolidates all necessary properties for the component in one place.
  2. The use of NodeViewProps["node"] for the node property, combined with { attrs: ImageAttributes }, provides more specific and type-safe definitions.
  3. This change will make the component more maintainable and less prone to type-related errors.

16-16: Great job: Improved type definition for CustomImageNodeViewProps.

The updated CustomImageNodeViewProps type definition is a significant improvement:

  1. It extends both NodeViewProps and CustomImageComponentProps, providing a more comprehensive type for the CustomImageNode component.
  2. This change aligns perfectly with the goal of consolidating properties and enhancing type safety.
  3. It will make the component more robust and easier to maintain by ensuring all necessary props are included.

20-20: Well done: Improved variable access and effect dependencies.

The changes in the CustomImageNode component are beneficial:

  1. Destructuring src as remoteImageSrc from node.attrs (line 20) simplifies access to the image source throughout the component.
  2. Updating the useEffect dependency array to include remoteImageSrc (line 48) ensures proper reactivity when the image source changes.

These modifications enhance code readability and maintain correct component behavior.

Also applies to: 48-48


59-59: Good change, but needs clarification: Updated image source retrieval.

The modification to use editor?.commands?.getImageSource?.(remoteImageSrc) for the src prop is a good improvement:

  1. It leverages the editor's command system, which might provide additional processing or validation of the image source.
  2. This approach is more flexible and aligns better with the editor's architecture.

However, there are two points that need attention:

  1. The TypeScript error suppression comment (@ts-expect-error) suggests a type mismatch. It would be beneficial to address this type issue properly rather than suppressing it.
  2. The multiple optional chaining operators (?.) might make the code more fragile. Consider adding a fallback value or handling the case where the command doesn't exist.

To ensure the getImageSource command exists and is used correctly, please run the following verification script:

Could you please provide more context on why the TypeScript error suppression is necessary here? Is there a way to resolve this type mismatch without using @ts-expect-error?

packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (4)

8-8: LGTM: Import statement updated appropriately.

The new import for CustomImageComponentProps and getImageComponentImageFileMap aligns with the type changes in the component. This promotes better type safety and code organization.


10-15: LGTM: New type definition improves component interface.

The new CustomImageUploaderProps type effectively consolidates all required props for the CustomImageUploader component. This change enhances type safety and makes the component's interface more explicit. The included properties cover all necessary functionality for image uploading and handling.


17-17: LGTM: Component declaration updated to use new prop type.

The CustomImageUploader component now correctly uses the CustomImageUploaderProps type for its props. This change ensures type safety and consistency with the newly defined prop interface.


32-32: LGTM: Simplified imageEntityId extraction.

The imageEntityId is now directly destructured from node.attrs, which simplifies the code and improves readability. This change aligns well with the component's props structure.

packages/editor/src/core/extensions/custom-image/custom-image.ts (5)

44-45: Improved naming to avoid reserved keywords

Renaming delete to deleteImageFn and restore to restoreImageFn avoids potential conflicts with reserved keywords in JavaScript/TypeScript. This enhances code readability and prevents unexpected behavior.


89-94: Add keyboard shortcuts for better user navigation

The addKeyboardShortcuts() method introduces shortcuts for ArrowDown and ArrowUp to insert empty paragraphs at node boundaries. Ensure that these shortcuts enhance the user experience and do not interfere with existing editor functionalities.


107-109: Validate image source before restoration

The check if (!node.attrs.src.startsWith("http")) { return; } ensures only images with sources starting with "http" are processed. Since startsWith("http") covers both "http://" and "https://", this check is appropriate. However, consider if there are other valid URI schemes (e.g., data URIs) that should be included in the restoration process.

If other schemes should be included, you might need to adjust the condition accordingly.


186-188: Ensure restoreImage command aligns with expected usage

The restoreImage command is implemented to asynchronously call restoreImageFn(src). Ensure that this command is properly utilized within the editor and that any necessary error handling is in place to handle potential issues during image restoration.


96-102: Integrate image tracking plugins properly

The addProseMirrorPlugins() method now includes TrackImageDeletionPlugin and TrackImageRestorationPlugin, which handle image deletion and restoration. Verify that these plugins are correctly implemented and that they interact seamlessly with deleteImageFn and restoreImageFn.

To confirm the proper integration of the plugins, you can check for their correct instantiation and usage in the codebase:

@@ -181,11 +184,15 @@
window.addEventListener("mousemove", handleResize);
window.addEventListener("mouseup", handleResizeEnd);
window.addEventListener("mouseleave", handleResizeEnd);
window.addEventListener("touchmove", handleResize, { passive: false });
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Re-evaluate the necessity of { passive: false } in touch event listener

The handleResize function does not call e.preventDefault(). If you are not preventing the default touch behavior, you can remove { passive: false } to improve scrolling performance.

Apply this diff:

- window.addEventListener("touchmove", handleResize, { passive: false });
+ window.addEventListener("touchmove", handleResize);
📝 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
window.addEventListener("touchmove", handleResize, { passive: false });
window.addEventListener("touchmove", handleResize);

@@ -124,9 +125,10 @@
);
} else {
// as the aspect ratio in not stored for old images, we need to update the attrs
if (!aspectRatio) {
// or if aspectRatioCalculated from the image's width and height doesn't match stored aspectRatio then also we'll update the attrs
if (!nodeAspectRatio || nodeAspectRatio !== aspectRatioCalculated) {
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

Use tolerance when comparing floating-point numbers

Directly comparing floating-point numbers can lead to precision issues. Use an epsilon value to compare nodeAspectRatio and aspectRatioCalculated to account for minor differences.

Apply this diff:

+ const EPSILON = 0.00001;
  if (
    !nodeAspectRatio ||
-   nodeAspectRatio !== aspectRatioCalculated
+   Math.abs(nodeAspectRatio - aspectRatioCalculated) > EPSILON
  ) {
    // existing code
  }

Committable suggestion was skipped due to low confidence.

@@ -104,17 +105,17 @@
}

setEditorContainer(closestEditorContainer);
const aspectRatio = img.naturalWidth / img.naturalHeight;
const aspectRatioCalculated = img.naturalWidth / img.naturalHeight;
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 division by zero when calculating aspectRatioCalculated

When calculating aspectRatioCalculated, ensure that img.naturalHeight is not zero to avoid a potential division by zero error.

Apply this diff to add the check:

+ if (img.naturalHeight === 0) {
+   console.error("Image natural height is zero, cannot calculate aspect ratio.");
+   return;
+ }
  const aspectRatioCalculated = img.naturalWidth / img.naturalHeight;
📝 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 aspectRatioCalculated = img.naturalWidth / img.naturalHeight;
if (img.naturalHeight === 0) {
console.error("Image natural height is zero, cannot calculate aspect ratio.");
return;
}
const aspectRatioCalculated = img.naturalWidth / img.naturalHeight;

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

🧹 Outside diff range and nitpick comments (2)
packages/editor/src/core/extensions/image/extension.tsx (2)

39-42: Improved image source validation and consistent function usage

The addition of a check to ensure the image source starts with "http" is a good validation step. The use of restoreImageFn is consistent with the earlier renaming.

However, there's an unnecessary console.log statement that should be removed:

- console.log("node", node.attrs.src?.startsWith("http"));

Also applies to: 48-48


73-75: New aspectRatio attribute added

The addition of the aspectRatio attribute with a default value of null is a good enhancement. This can be useful for maintaining image proportions during resizing or display.

Consider adding a brief comment explaining the purpose and expected usage of this new attribute for better code documentation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7f36c26 and 7bed87e.

📒 Files selected for processing (3)
  • packages/editor/src/core/extensions/custom-image/custom-image.ts (4 hunks)
  • packages/editor/src/core/extensions/image/extension.tsx (3 hunks)
  • packages/editor/src/core/plugins/image/restore-image.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/editor/src/core/extensions/custom-image/custom-image.ts
  • packages/editor/src/core/plugins/image/restore-image.ts
🧰 Additional context used
🔇 Additional comments (3)
packages/editor/src/core/extensions/image/extension.tsx (3)

15-16: Improved function parameter naming

The renaming of delete to deleteImageFn and restore to restoreImageFn enhances code readability and clarity. This change makes the purpose of these functions more explicit and follows better naming conventions.


30-31: Consistent use of renamed functions in plugins

The deleteImageFn and restoreImageFn are now correctly used in the TrackImageDeletionPlugin and TrackImageRestorationPlugin respectively. This change maintains consistency with the earlier parameter renaming.


Line range hint 1-91: Overall improvements align with PR objectives

The changes in this file contribute significantly to the PR objectives of fixing image restoration and improving image handling. Key improvements include:

  1. Enhanced function naming for clarity
  2. Improved image source validation
  3. Addition of an aspectRatio attribute for better image display control

These modifications collectively enhance the image management capabilities of the editor, aligning well with the stated PR objectives.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7bed87e and 028443e.

📒 Files selected for processing (2)
  • packages/editor/src/core/extensions/custom-image/components/image-block.tsx (7 hunks)
  • packages/editor/src/core/extensions/custom-image/components/image-node.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/editor/src/core/extensions/custom-image/components/image-node.tsx
🧰 Additional context used
🔇 Additional comments (5)
packages/editor/src/core/extensions/custom-image/components/image-block.tsx (5)

75-75: Approve the new state variable with a note on naming

The introduction of onFirstLoadError is a good addition for tracking initial load errors. However, as previously suggested, consider renaming it to hasFirstLoadError or isFirstLoadError for clarity, as the current name might be misinterpreted as an event handler.


141-141: Approve the updated dependency array in handleImageLoad

Adding size.aspectRatio to the dependency array of handleImageLoad is a good improvement. This ensures that the function will react to changes in the aspect ratio, maintaining consistency between the component's state and its visual representation.


149-151: Approve the updates to useLayoutEffect

The addition of nodeAspectRatio to both the state update and the dependency array in useLayoutEffect is a good improvement. This ensures that the component's state is properly synchronized with the node's aspect ratio, enhancing the overall consistency of the image rendering.


164-164: Approve the updated dependency array in handleResize

Adding size.aspectRatio to the dependency array of handleResize is a good improvement. This ensures that the resize function always uses the most current aspect ratio, maintaining the correct proportions during image resizing.


Line range hint 1-313: Overall assessment: Approved with minor suggestions

The changes in this file significantly improve the image handling capabilities of the CustomImageBlock component, aligning well with the PR objectives. The enhancements in error handling, particularly for image restoration, and the improved reactivity to aspect ratio changes are noteworthy improvements.

Key points:

  1. The new onFirstLoadError state variable enhances error tracking (consider renaming for clarity).
  2. Updates to dependency arrays in handleImageLoad and handleResize improve reactivity.
  3. The useLayoutEffect hook now properly synchronizes with nodeAspectRatio.
  4. The enhanced error handling in the onError handler is a significant improvement, though consider implementing a retry limit to prevent potential infinite loops.

These changes should result in more robust image handling, particularly for new images, as stated in the PR objectives. The suggestions provided in the individual comments, if implemented, would further refine the component's functionality and reliability.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 028443e and dd7e726.

📒 Files selected for processing (2)
  • packages/editor/src/core/extensions/custom-image/components/image-block.tsx (7 hunks)
  • packages/editor/src/core/extensions/image/extension.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/editor/src/core/extensions/image/extension.tsx
🧰 Additional context used
🔇 Additional comments (6)
packages/editor/src/core/extensions/custom-image/components/image-block.tsx (6)

75-75: Existing comment is still valid

The existing comment suggesting to rename onFirstLoadError for clarity is still relevant and valid. Consider implementing this suggestion to improve code readability.


149-151: LGTM: Improved state synchronization

The addition of nodeAspectRatio to both the useLayoutEffect dependency array and the size state update is a good improvement. This ensures that the component's local state stays in sync with the node attributes, particularly when the aspect ratio changes.


164-164: LGTM: Correct dependency in handleResize

Adding size.aspectRatio to the dependency array of handleResize is a good practice. This ensures that the function is recreated when the aspect ratio changes, maintaining the correctness of the resize functionality.


187-188: Existing comment is still valid

The existing comment suggesting to re-evaluate the necessity of { passive: false } in the touch event listener is still relevant. Consider implementing this suggestion to potentially improve scrolling performance if preventDefault() is not being called in the handleResize function.

Also applies to: 194-195


212-212: LGTM: Improved error state handling

Including onFirstLoadError in the showImageLoader condition is a good improvement. This ensures that the image loader is displayed when there's an error during the initial load, providing better visual feedback to the user.


308-308: LGTM: Improved touch device support

Adding the onTouchStart event handler to the resize handle is a good improvement. This enhances the usability of the image resizing feature on touch devices, making the component more versatile across different platforms.

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

🧹 Outside diff range and nitpick comments (3)
packages/editor/src/core/extensions/extensions.tsx (1)

143-146: LGTM! Consider enhancing readability.

The addition of editor.isActive("imageComponent") to the shouldHidePlaceholder condition is logical and consistent with the existing pattern. This change aligns well with the PR objectives, particularly in improving image handling.

To enhance readability, consider extracting the conditions into an array and using the some() method. Here's a suggested refactor:

const activeComponents = ['table', 'codeBlock', 'image', 'imageComponent'];
const shouldHidePlaceholder = activeComponents.some(component => editor.isActive(component));

This approach makes it easier to add or remove components in the future without changing the logic structure.

packages/editor/src/core/extensions/custom-image/custom-image.ts (1)

107-114: Improved image source validation and restoration

The addition of a validation check for image sources starting with "http" enhances the robustness of the image handling process. The use of restoreImageFn is consistent with earlier renaming.

However, consider improving the error handling:

Instead of just logging the error, consider implementing a more robust error handling mechanism that informs the user or allows for retry attempts. For example:

imageSources.forEach(async (src) => {
  try {
    await restoreImageFn(src);
  } catch (error) {
    console.error("Error restoring image: ", error);
    // Inform the user about the failed restoration
    this.editor.commands.showNotification(`Failed to restore image: ${src}`, 'error');
    // Or add the failed src to a list for potential retry
  }
});
packages/editor/src/core/extensions/custom-image/components/image-block.tsx (1)

188-189: LGTM: Added touch event support for resizing

The addition of touch event listeners (touchmove and touchend) improves the component's functionality on touch devices, allowing for image resizing on mobile platforms. This is a valuable enhancement to the user experience.

Note: The past review comment suggesting the use of { passive: true } for the touchmove event listener has not been addressed. Consider adding this option to improve scrolling performance:

- window.addEventListener("touchmove", handleResize);
+ window.addEventListener("touchmove", handleResize, { passive: true });

Also applies to: 195-196

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between dd7e726 and 7d54131.

📒 Files selected for processing (4)
  • packages/editor/src/core/extensions/custom-image/components/image-block.tsx (7 hunks)
  • packages/editor/src/core/extensions/custom-image/custom-image.ts (4 hunks)
  • packages/editor/src/core/extensions/extensions.tsx (1 hunks)
  • packages/editor/src/core/extensions/image/extension.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/editor/src/core/extensions/image/extension.tsx
🧰 Additional context used
🔇 Additional comments (10)
packages/editor/src/core/extensions/custom-image/custom-image.ts (5)

25-25: LGTM: New restoreImage command added

The addition of the restoreImage command to the Commands interface is consistent with the PR objective of fixing image restoration. The command signature follows the existing pattern and is well-integrated into the interface.


44-45: Improved naming convention for delete and restore props

The renaming of delete to deleteImageFn and restore to restoreImageFn enhances code clarity and maintains consistency with the naming conventions used throughout the file. This change improves readability and makes the purpose of these props more explicit.


89-94: Enhanced user experience with keyboard shortcuts

The addition of keyboard shortcuts for ArrowDown and ArrowUp improves navigation around image blocks. The use of the insertEmptyParagraphAtNodeBoundaries helper function ensures consistent behavior across different node types. This enhancement aligns well with improving the overall usability of the editor.


96-101: Improved image tracking with ProseMirror plugins

The addition of TrackImageDeletionPlugin and TrackImageRestorationPlugin enhances the image handling capabilities of the editor. These plugins, utilizing the renamed deleteImageFn and restoreImageFn, provide a robust mechanism for tracking image deletion and restoration events. This change aligns well with the PR objectives and improves the overall functionality of the image extension.


185-187: LGTM: restoreImage command implementation

The implementation of the restoreImage command is consistent with the earlier interface definition and aligns well with the PR objectives. It correctly utilizes the restoreImageFn prop, maintaining consistency throughout the extension.

packages/editor/src/core/extensions/custom-image/components/image-block.tsx (5)

Line range hint 18-18: LGTM: Addition of aspectRatio to ImageAttributes

The addition of the aspectRatio property to the ImageAttributes type is a good improvement. It allows for better control and consistency in image rendering, especially when resizing.


75-76: LGTM: New state variables for error handling

The addition of hasErroredOnFirstLoad and hasTriedRestoringImageOnce state variables improves error handling during image loading. These variables provide clear indicators of the loading state and whether an image restoration attempt has been made.

Note: This change effectively addresses the past review comment about naming clarity for error-related variables.


150-152: LGTM: Aspect ratio update in useLayoutEffect

The addition of aspectRatio: nodeAspectRatio in the useLayoutEffect hook ensures that the component's state stays in sync with the node's attributes. This change is consistent with the earlier addition of the aspectRatio property and improves the overall consistency of the image handling logic.


241-260: LGTM: Improved error handling for image loading

The new error handling logic for image loading is a significant improvement. It properly checks for the existence of the restoreImage command and uses the new state variables to manage error states and restoration attempts. This implementation effectively addresses the concern raised in a past review comment about potential infinite loops by using the hasTriedRestoringImageOnce flag.

Key improvements:

  1. Checks for the existence of restoreImage command before attempting to use it.
  2. Uses hasTriedRestoringImageOnce to prevent multiple restoration attempts.
  3. Properly manages error states with setHasErroredOnFirstLoad and setFailedToLoadImage.
  4. Includes error logging for better debugging.

These changes enhance the robustness and reliability of the image loading process.


165-165: LGTM with a suggestion: Simplified handleResize dependency

The simplification of the handleResize dependency array to only include size.aspectRatio is good for performance. However, please verify that this doesn't omit any necessary dependencies that could affect the behavior of the handleResize function.

To ensure all necessary dependencies are included, let's analyze the handleResize function:

✅ Verification successful

Verified handleResize dependencies

After reviewing the handleResize function, the dependency array correctly includes only size.aspectRatio. No additional dependencies are necessary.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Extract the handleResize function and its dependencies
sed -n '/const handleResize/,/^  }/p' packages/editor/src/core/extensions/custom-image/components/image-block.tsx

Length of output: 1099

@Palanikannan1437 Palanikannan1437 changed the title fix: image restoration fixed for new images [PE-69] fix: image restoration fixed for new images Oct 18, 2024
@Palanikannan1437 Palanikannan1437 changed the title [PE-69] fix: image restoration fixed for new images [PE-69] fix: image restoration fixed for new images in private bucket Oct 18, 2024
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