-
Notifications
You must be signed in to change notification settings - Fork 2.5k
[WEB-2599] fix: image deletion on submit fixed in comments #5748
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
Conversation
WalkthroughThe changes in this pull request modify the Changes
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
fb1fdc3
to
0f7efb3
Compare
0f7efb3
to
50f4169
Compare
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (1)
packages/editor/src/core/plugins/image/delete-image.ts (1)
20-21
: Approve the change with a minor suggestion for improvement.The added conditional check effectively addresses the PR objective by preventing image deletion when the "skipImageDeletion" meta property is set to true. This solution is elegant and non-intrusive, maintaining backward compatibility while solving the specific issue.
Consider adding a brief comment explaining when and why the "skipImageDeletion" meta property should be set. This would improve code maintainability and help other developers understand the purpose of this check. For example:
// if the transaction has meta of skipImageDeletion get to true, then return (like while clearing the editor content programatically) +// This is used to prevent image deletion when submitting comments or in other scenarios where we want to preserve images if (transaction.getMeta("skipImageDeletion")) return;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
- packages/editor/src/core/hooks/use-editor.ts (1 hunks)
- packages/editor/src/core/plugins/image/delete-image.ts (1 hunks)
🔇 Additional comments (1)
packages/editor/src/core/plugins/image/delete-image.ts (1)
Line range hint
1-58
: Verify if additional changes are needed to fully resolve the issue.The implemented change effectively prevents image deletion when the "skipImageDeletion" meta property is set. However, to ensure that this fully resolves the issue described in the PR objectives, we should verify:
- That the "skipImageDeletion" meta property is correctly set when clearing the editor content during comment submission.
- That no other parts of the codebase need modification to fully implement this solution.
To help verify this, you can run the following script to check for usage of "skipImageDeletion" across the codebase:
This script will help identify if the "skipImageDeletion" property is being set correctly in the relevant parts of the codebase, particularly where the editor content is being cleared.
✅ Verification successful
Verification Successful: "skipImageDeletion" is correctly implemented.
All instances of "skipImageDeletion" are appropriately set during editor content clearing operations. No additional changes are required.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Search for usage of "skipImageDeletion" in the codebase # Search for "skipImageDeletion" in all TypeScript and JavaScript files echo "Searching for 'skipImageDeletion' usage:" rg --type-add 'web:*.{ts,tsx,js,jsx}' -t web 'skipImageDeletion' # Search for editor content clearing operations that might need to set "skipImageDeletion" echo "\nSearching for potential places where 'skipImageDeletion' should be set:" rg --type-add 'web:*.{ts,tsx,js,jsx}' -t web 'editor\s*\.\s*(commands\s*\.\s*clearContent|clear)'Length of output: 885
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (2)
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (2)
Line range hint
113-127
: LGTM with a minor suggestion.The simplification of the
getDisplayMessage
function looks good. It aligns with the removal of logic related to handling existing files, as mentioned in the AI-generated summary.Consider renaming the
isUploading
variable toisImageBeingUploaded
for consistency:- const isUploading = isImageBeingUploaded; + const isImageBeingUploaded = isImageBeingUploaded; if (failedToLoadImage) { return "Error loading image"; } - if (isUploading) { + if (isImageBeingUploaded) { return "Uploading..."; }This change would make the code more self-explanatory and consistent with the variable name used in the component's state.
Line range hint
1-165
: Overall, the component looks well-structured and functional.The
CustomImageUploader
component appears to be well-implemented, using modern React practices such as hooks and functional components. The changes made to thegetDisplayMessage
function simplify the logic without introducing any obvious issues.However, there are a few points to consider for future improvements:
Error Handling: The component handles a
failedToLoadImage
state, but it might be beneficial to add more robust error handling for upload failures.Accessibility: Consider adding appropriate ARIA attributes to improve accessibility, especially for the file input and the clickable div.
Internationalization: The displayed messages are hardcoded. If this application supports multiple languages, consider using a translation system.
Testing: Ensure that unit tests are updated or added to cover the changes in the
getDisplayMessage
function and the overall behavior of the component.These suggestions are not critical for the current PR but could be considered for future improvements to enhance the component's robustness and maintainability.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
- packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (2 hunks)
- packages/editor/src/core/hooks/use-read-only-editor.ts (1 hunks)
🔇 Additional comments (1)
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (1)
Line range hint
1-165
: Clarify the relationship between these changes and the PR objectives.The PR objectives mention fixing an issue with image deletion on comment submission. However, the changes in this file don't directly address that issue. Instead, they simplify the image upload component by removing logic related to handling existing files.
Could you please clarify:
- How do these changes in the
CustomImageUploader
component contribute to fixing the image deletion issue?- Are there other files not included in this review that more directly address the PR objectives?
- Is this simplification a side effect of changes made elsewhere, or is it intentional refactoring?
To help understand the context, let's check for related changes in other files:
This will help us identify other relevant files that might be part of this fix.
✅ Verification successful
Verified: The changes in
CustomImageUploader
do not directly address the image deletion issue. The image deletion functionality is handled in other parts of the codebase.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for files that might be related to comment submission or image handling rg -i -t typescript -t javascript "(comment.*submit|image.*delete|skipImageDeletion)" --glob '!**/node_modules/**'Length of output: 151
Script:
#!/bin/bash # Search for files related to comment submission or image deletion using file extensions rg -i "(comment.*submit|image.*delete|skipImageDeletion)" --glob '*.ts' --glob '*.tsx' --glob '*.js' --glob '*.jsx' --glob '**/*.ts' --glob '**/*.tsx' --glob '**/*.js' --glob '**/*.jsx' --glob '!**/node_modules/**'Length of output: 2285
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Outside diff range and nitpick comments (1)
packages/editor/src/core/hooks/use-file-upload.ts (1)
Line range hint
28-61
: Include all dependencies in the 'useCallback' dependency arrayThe
uploadFile
function depends ononUpload
,editor
, andloadImageFromFileSystem
, but onlyonUpload
is included in the dependency array. This could lead to stale references ifeditor
orloadImageFromFileSystem
change.Update the dependency array to include all dependencies:
const uploadFile = useCallback( async (file: File) => { // ... existing code ... }, - [onUpload] + [onUpload, editor, loadImageFromFileSystem] );
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (4)
- packages/editor/src/core/extensions/custom-image/components/image-block.tsx (1 hunks)
- packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (5 hunks)
- packages/editor/src/core/extensions/drop.tsx (3 hunks)
- packages/editor/src/core/hooks/use-file-upload.ts (4 hunks)
🔇 Additional comments (11)
packages/editor/src/core/extensions/drop.tsx (3)
44-44
: LGTM: Consistent use ofinsertImagesSafely
inhandleDrop
This change is consistent with the modification in
handlePaste
, replacinginsertImages
withinsertImagesSafely
. It aligns well with the PR objective and maintains consistency across the file.
Line range hint
57-85
: LGTM with suggestion: NewinsertImagesSafely
functionThe new
insertImagesSafely
function is a good addition that aligns with the PR objective of improving image handling. It includes safety checks to prevent insertion beyond document size and implements error handling for each image insertion, which improves robustness.However, I have one suggestion:
Consider adding a comment or log message in the catch block to provide more context about the error, such as the file name or size. This could help with debugging in the future. For example:
} catch (error) { - console.error(`Error while ${event}ing image:`, error); + console.error(`Error while ${event}ing image (${file.name}):`, error); }Also, I noticed that the function doesn't explicitly set the "skipImageDeletion" property as mentioned in the PR objectives. Could you clarify if this is handled elsewhere or if it needs to be addressed here?
Let's verify if "skipImageDeletion" is set elsewhere:
#!/bin/bash # Description: Check for usage of 'skipImageDeletion' in the codebase # Expected: At least one occurrence of 'skipImageDeletion' being set rg --type typescript --type tsx 'skipImageDeletion'
24-24
: LGTM: ReplacedinsertImages
withinsertImagesSafely
This change aligns with the PR objective of fixing image deletion on submit. The function signature matches the previous
insertImages
function, ensuring a smooth transition.Let's verify if this change is consistent across the codebase:
packages/editor/src/core/extensions/custom-image/components/image-block.tsx (3)
111-117
: LGTM: Improved handling of aspect ratio for imagesThis change addresses the case when
aspectRatio
is not provided (falsy), ensuring that it's set in both the component state and the node attributes. This improvement aligns with the PR objective of fixing image handling issues and should prevent problems with image resizing and display.
120-120
: LGTM: Correct dependency array updateAdding
aspectRatio
to the dependency array of theuseCallback
hook is a good change. It ensures that thehandleImageLoad
function is recreated whenaspectRatio
changes, guaranteeing that the function always has access to the latestaspectRatio
value. This update follows React best practices and helps prevent potential bugs related to stale closure values.
111-120
: Summary: Improved image handling with aspect ratioThese changes effectively address the PR objective of fixing image handling issues. The modifications improve the management of
aspectRatio
in theCustomImageBlock
component by:
- Ensuring that
aspectRatio
is set in both the component state and node attributes when it's initially undefined.- Updating the
useCallback
dependency array to properly react toaspectRatio
changes.These improvements should lead to more consistent and reliable image rendering and resizing in the editor. The changes are well-implemented, localized, and maintain the overall code quality and readability of the component.
packages/editor/src/core/hooks/use-file-upload.ts (1)
67-75
:⚠️ Potential issueAdd missing dependencies to the 'useDropZone' hook's callbacks
Within the
useDropZone
hook, functions likeonDragEnter
,onDragLeave
, and event handlers reference state variables but may not include all necessary dependencies, potentially causing inconsistencies.Ensure all dependencies are included:
const onDragEnter = useCallback(() => { setDraggedInside(true); - }, []); + }, [setDraggedInside]); const onDragLeave = useCallback(() => { setDraggedInside(false); - }, []); + }, [setDraggedInside]);Similarly, update the dependency array for
onDrop
:const onDrop = useCallback( async (e: DragEvent<HTMLDivElement>) => { // ... existing code ... }, - [uploader] + [uploader, editor, pos, setDraggedInside] );Likely invalid or redundant comment.
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (4)
75-79
: Passpos
touseDropZone
for accurate image placementAdding
pos: getPos()
to theuseDropZone
hook ensures that dropped images are inserted at the correct position within the editor. This change enhances the user experience by maintaining content flow.
112-112
: Dependencies ingetDisplayMessage
are accurateThe dependencies
[draggedInside, failedToLoadImage, isImageBeingUploaded]
in thegetDisplayMessage
useCallback
hook are correctly specified. This ensures the message updates appropriately when these variables change.
159-159
: Enable multiple image selection by addingmultiple
attributeAdding the
multiple
attribute to the<input>
element allows users to select and upload multiple images simultaneously, improving the image uploading experience.
104-106
: Verify error handling for multiple file uploadsWith the support for multiple file uploads, ensure that
uploadFirstImageAndInsertRemaining
handles errors gracefully for individual file uploads. This includes providing feedback if some files fail to upload while others succeed.
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (1)
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (1)
75-79
: LGTM: EnhanceduseDropZone
hook usage.The addition of
editor
andpos
parameters to theuseDropZone
hook provides more context, which can improve its functionality. This change aligns with the PR objectives of enhancing image handling.Consider destructuring
getPos
in the component's props to directly usegetPos()
instead ofgetPos: getPos,
. This would make the code slightly more concise:const { draggedInside, onDrop, onDragEnter, onDragLeave } = useDropZone({ uploader: uploadFile, editor, pos: getPos(), });
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
- packages/editor/src/core/extensions/custom-image/components/image-block.tsx (3 hunks)
- packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/editor/src/core/extensions/custom-image/components/image-block.tsx
🔇 Additional comments (5)
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (5)
8-8
: LGTM: New import for handling multiple image uploads.The addition of
uploadFirstImageAndInsertRemaining
import aligns with the PR objective of improving image handling in comments. This change supports the new functionality for multiple image uploads.
Line range hint
112-126
: LGTM: SimplifiedgetDisplayMessage
function.The removal of
existingFile
checks simplifies the logic, making the code more readable and maintainable. This change aligns with the PR objectives of improving image handling.
131-133
: LGTM: Improved component styling and interactivity.The addition of
cursor-default
to base styles and the modification of hover behavior based on the editor's editability improve the user experience by providing appropriate visual feedback. The conditional styling is a good practice that enhances the component's usability.
160-160
: LGTM: Enabled multiple file selection.The addition of the
multiple
attribute to the file input aligns perfectly with the PR objectives of supporting multiple image uploads. This simple change is crucial for enabling the new functionality.
Line range hint
1-163
: Overall assessment: Approved with minor suggestions.The changes in this file significantly improve the image upload functionality, aligning well with the PR objectives. Key improvements include:
- Support for multiple image uploads
- Enhanced error handling and user feedback
- Improved component styling and interactivity
The code is well-structured and follows good practices. However, there's one minor issue to address:
- Add a null check for
fileList
in theonFileChange
function to prevent potential runtime errors.Once this small change is implemented, the code will be ready for merging.
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx
Outdated
Show resolved
Hide resolved
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (1)
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (1)
103-106
: Unnecessarye.preventDefault()
inonChange
handlerCalling
e.preventDefault()
in theonChange
event handler for the input element is unnecessary, as thechange
event does not have a default action that needs to be prevented. Usinge.preventDefault()
here may have unintended side effects.Consider removing
e.preventDefault()
from theonFileChange
handler.Apply this diff to remove
e.preventDefault()
:async (e: ChangeEvent<HTMLInputElement>) => { - e.preventDefault(); const fileList = e.target.files; await uploadFirstImageAndInsertRemaining(editor, fileList, getPos(), uploadFile); },
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
- packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (6 hunks)
- packages/editor/src/core/hooks/use-file-upload.ts (4 hunks)
🔇 Additional comments (4)
packages/editor/src/core/hooks/use-file-upload.ts (3)
98-105
: Properly awaits 'uploadFirstImageAndInsertRemaining' in 'onDrop' handlerThe
onDrop
handler is now asynchronous and correctly awaitsuploadFirstImageAndInsertRemaining
, ensuring the upload process completes before proceeding.
147-149
: Previous issue regarding file type checking still appliesThe earlier feedback about simplifying the file type checking logic by filtering out non-image files instead of returning early is still applicable.
161-161
: Previous issue regarding awaiting 'uploaderFn' call still appliesThe
uploaderFn
returns a Promise and should be awaited to ensure the upload completes before proceeding. This issue was highlighted in a previous review and still needs to be addressed.packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (1)
103-108
: Previous comment about nullfileList
is still validThe previous review comment regarding adding a null check for
fileList
to prevent potential runtime errors is still applicable. Please consider adding a null check before proceeding.
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx
Outdated
Show resolved
Hide resolved
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx
Outdated
Show resolved
Hide resolved
There was a problem hiding this 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
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
- packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (6 hunks)
- packages/editor/src/core/hooks/use-file-upload.ts (4 hunks)
🧰 Additional context used
🔇 Additional comments (9)
packages/editor/src/core/hooks/use-file-upload.ts (4)
4-4
: LGTM: New import for enhanced image handling.The addition of
insertImagesSafely
import is appropriate for the new functionality implemented in this file.
67-75
: LGTM: EnhanceduseDropZone
hook signature.The updated hook signature with
editor
andpos
parameters, along with the Promise-baseduploader
type, aligns well with the asynchronous nature of the upload process and provides better control over image insertion.
98-107
: LGTM: Improved asynchronous handling inonDrop
.The
onDrop
callback has been correctly updated to handle the asynchronousuploadFirstImageAndInsertRemaining
function. The use ofawait
and the updated dependency array ensure proper execution and reactivity.
159-166
: LGTM: Effective implementation of multiple image insertion.The logic for inserting multiple images is well-implemented:
- Correct calculation of the insertion position for remaining images.
- Proper use of
insertImagesSafely
for error-resistant insertion.- Aligns with the PR objective of supporting multiple image uploads.
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (5)
8-8
: LGTM: New import for handling multiple image uploads.The addition of
uploadFirstImageAndInsertRemaining
import aligns with the PR objectives and enhances the component's capability to handle multiple image uploads.
75-79
: LGTM: EnhanceduseDropZone
hook usage.The addition of
editor
andpos
parameters to theuseDropZone
hook enhances its functionality, allowing for better integration with the editor's state and position.
Line range hint
115-129
: LGTM: Simplified display message logic.The
getDisplayMessage
function has been streamlined by removing references toexistingFile
. This simplification improves code readability and aligns with the overall changes in the component's file handling approach.
134-136
: LGTM: Improved cursor styling based on editor state.The changes in the component's styling effectively address the previous concern about conflicting cursor styles. The new implementation provides a more intuitive user experience by setting the cursor to
pointer
only when the editor is editable.
163-163
: LGTM: Added support for multiple file selection.The addition of the
multiple
attribute to the file input element is consistent with the PR objectives and the changes made in theonFileChange
callback. This enhancement allows users to select multiple images during the upload process.
// Upload the first image and insert the remaining images for uploading multiple image | ||
// post insertion of image-component | ||
export async function uploadFirstImageAndInsertRemaining( | ||
editor: Editor, | ||
fileList: FileList, | ||
pos: number, | ||
uploaderFn: (file: File) => Promise<void> | ||
) { | ||
const filteredFiles: File[] = []; | ||
for (let i = 0; i < fileList.length; i += 1) { | ||
const item = fileList.item(i); | ||
if (item && item.type.indexOf("image") !== -1 && isFileValid(item)) { | ||
filteredFiles.push(item); | ||
} | ||
} | ||
if (filteredFiles.length !== fileList.length) { | ||
console.warn("Some files were not images and have been ignored."); | ||
} | ||
if (filteredFiles.length === 0) { | ||
console.error("No image files found to upload"); | ||
return; | ||
} | ||
|
||
// Upload the first image | ||
const firstFile = filteredFiles[0]; | ||
uploaderFn(firstFile); | ||
|
||
// Insert the remaining images | ||
const remainingFiles = filteredFiles.slice(1); | ||
|
||
if (remainingFiles.length > 0) { | ||
const docSize = editor.state.doc.content.size; | ||
const posOfNextImageToBeInserted = Math.min(pos + 1, docSize); | ||
insertImagesSafely({ editor, files: remainingFiles, initialPos: posOfNextImageToBeInserted, event: "drop" }); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good implementation, but consider awaiting the first image upload.
The uploadFirstImageAndInsertRemaining
function is well-structured and handles multiple image uploads effectively. However, there's a potential issue:
- The upload of the first image (line 157) is not awaited, which could lead to race conditions with the insertion of remaining images.
Consider modifying line 157 to await the upload:
- uploaderFn(firstFile);
+ await uploaderFn(firstFile);
This ensures that the first image is fully uploaded before proceeding with the insertion of remaining images.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
// Upload the first image and insert the remaining images for uploading multiple image | |
// post insertion of image-component | |
export async function uploadFirstImageAndInsertRemaining( | |
editor: Editor, | |
fileList: FileList, | |
pos: number, | |
uploaderFn: (file: File) => Promise<void> | |
) { | |
const filteredFiles: File[] = []; | |
for (let i = 0; i < fileList.length; i += 1) { | |
const item = fileList.item(i); | |
if (item && item.type.indexOf("image") !== -1 && isFileValid(item)) { | |
filteredFiles.push(item); | |
} | |
} | |
if (filteredFiles.length !== fileList.length) { | |
console.warn("Some files were not images and have been ignored."); | |
} | |
if (filteredFiles.length === 0) { | |
console.error("No image files found to upload"); | |
return; | |
} | |
// Upload the first image | |
const firstFile = filteredFiles[0]; | |
uploaderFn(firstFile); | |
// Insert the remaining images | |
const remainingFiles = filteredFiles.slice(1); | |
if (remainingFiles.length > 0) { | |
const docSize = editor.state.doc.content.size; | |
const posOfNextImageToBeInserted = Math.min(pos + 1, docSize); | |
insertImagesSafely({ editor, files: remainingFiles, initialPos: posOfNextImageToBeInserted, event: "drop" }); | |
} | |
} | |
// Upload the first image and insert the remaining images for uploading multiple image | |
// post insertion of image-component | |
export async function uploadFirstImageAndInsertRemaining( | |
editor: Editor, | |
fileList: FileList, | |
pos: number, | |
uploaderFn: (file: File) => Promise<void> | |
) { | |
const filteredFiles: File[] = []; | |
for (let i = 0; i < fileList.length; i += 1) { | |
const item = fileList.item(i); | |
if (item && item.type.indexOf("image") !== -1 && isFileValid(item)) { | |
filteredFiles.push(item); | |
} | |
} | |
if (filteredFiles.length !== fileList.length) { | |
console.warn("Some files were not images and have been ignored."); | |
} | |
if (filteredFiles.length === 0) { | |
console.error("No image files found to upload"); | |
return; | |
} | |
// Upload the first image | |
const firstFile = filteredFiles[0]; | |
await uploaderFn(firstFile); | |
// Insert the remaining images | |
const remainingFiles = filteredFiles.slice(1); | |
if (remainingFiles.length > 0) { | |
const docSize = editor.state.doc.content.size; | |
const posOfNextImageToBeInserted = Math.min(pos + 1, docSize); | |
insertImagesSafely({ editor, files: remainingFiles, initialPos: posOfNextImageToBeInserted, event: "drop" }); | |
} | |
} |
async (e: ChangeEvent<HTMLInputElement>) => { | ||
e.preventDefault(); | ||
const fileList = e.target.files; | ||
if (!fileList) { | ||
return; | ||
} | ||
await uploadFirstImageAndInsertRemaining(editor, fileList, getPos(), uploadFile); | ||
}, | ||
[uploadFile] | ||
[uploadFile, editor, getPos] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM with a minor suggestion: Improved file change handling.
The changes in the onFileChange
callback effectively address multiple file uploads and include a null check for fileList
, which resolves the previous concern about potential runtime errors. The use of uploadFirstImageAndInsertRemaining
aligns with the PR objectives.
However, there's still a minor issue in the dependency array:
The uploadFile
dependency is listed twice in the dependency array. Please remove the duplicate to avoid potential confusion:
- [uploadFile, editor, getPos, uploadFile]
+ [uploadFile, editor, getPos]
Committable suggestion was skipped due to low confidence.
Description
true
while clearing the content of our editor via the editor ref APIs.Summary by CodeRabbit
Summary by CodeRabbit