Skip to content

Commit

Permalink
fix image double pasting issue on initial paste
Browse files Browse the repository at this point in the history
  • Loading branch information
reactoholic committed Jan 6, 2025
1 parent 237a0de commit 9a26fc7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
30 changes: 21 additions & 9 deletions src/core/ui/forms/MarkdownInput/FormikMarkdownField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export const FormikMarkdownField = ({
editor?.commands.setImage({ src: data.uploadFileOnStorageBucket, alt: 'pasted-image' });
},
onError: error => {
logError(error);
console.error(error.message);
},
});

Expand Down Expand Up @@ -141,17 +141,18 @@ export const FormikMarkdownField = ({
const handleOnPaste = useCallback(
(event: ClipboardEvent) => {
const clipboardData = event.clipboardData;
const items = clipboardData.items;
const items = clipboardData?.items;

if (!items) return;

const storageBucketId = storageConfig?.storageBucketId;

if (storageBucketId) {
let hasImage = false;
let imageProcessed = false;

for (const item of items) {
if (item.type.startsWith('image/')) {
// Process `image/png` first
if (item.kind === 'file' && item.type.startsWith('image/')) {
const file = item.getAsFile();
if (file) {
const reader = new FileReader();
Expand All @@ -168,14 +169,25 @@ export const FormikMarkdownField = ({
});
};

reader.readAsDataURL(file); // Read to trigger onLoad.
hasImage = true;
reader.readAsDataURL(file); // Read the file to trigger onLoad.
imageProcessed = true;
break; // Stop after processing the image.
}
}

// Process `text/html` only if there is no image
if (!imageProcessed && item.kind === 'string' && item.type === 'text/html') {
const htmlContent = clipboardData.getData('text/html');
if (htmlContent.includes('<img')) {
// If we find HTML with `<img>`, ignore it to avoid duplication.
imageProcessed = true;
break;
}
}
}

if (hasImage) {
event.preventDefault(); // Prevent default only if there's an image.
if (imageProcessed) {
event.preventDefault();
}
}
},
Expand Down Expand Up @@ -206,7 +218,7 @@ export const FormikMarkdownField = ({
(props: PropsWithChildren<InputBaseComponentProps>) => (
<MarkdownInput {...props} pasteImageHandler={handleImagePaste} />
),
[handleImagePaste]
[handleImagePaste, handleOnPaste]
);

const labelOffset = inputElement?.getLabelOffset();
Expand Down
4 changes: 4 additions & 0 deletions src/core/ui/forms/MarkdownInput/MarkdownInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ const proseMirrorStyles = {

const editorOptions: Partial<EditorOptions> = {
extensions: [StarterKit, ImageExtension, Link, Highlight, Iframe],
editorProps: {
// Prevents automatic pasting
handlePaste: () => true, // Returns true to stop the default handling
},
};

export const MarkdownInput = memo(
Expand Down

0 comments on commit 9a26fc7

Please sign in to comment.