Skip to content

Remove image filtering #3523

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

Closed
wants to merge 2 commits into from
Closed

Remove image filtering #3523

wants to merge 2 commits into from

Conversation

john-traas
Copy link
Contributor

@john-traas john-traas commented Apr 10, 2025

Summary by CodeRabbit

  • New Features
    • Added an option to enable or disable image pasting in the text editor.
    • When image pasting is disabled, pasted content will automatically filter out images.
  • Refactor
    • Improved handling and processing of pasted images from various sources for more robust paste event support.

Review:

  • Commits are atomic
  • Commits have the correct type for the changes made
  • Commits with breaking changes are marked as such

Browsers tested:

(Check any that applies, it's ok to leave boxes unchecked if testing something didn't seem relevant.)

Windows:

  • Chrome
  • Edge
  • Firefox

Linux:

  • Chrome
  • Firefox

macOS:

  • Chrome
  • Firefox
  • Safari

Mobile:

  • Chrome on Android
  • iOS

Copy link

coderabbitai bot commented Apr 10, 2025

📝 Walkthrough

Walkthrough

The changes introduce a new allowImages boolean property to the ProsemirrorAdapter component, which determines whether images can be pasted into the editor. The image inserter plugin and its paste event handling logic are updated to accept this parameter, enabling conditional filtering of image nodes from pasted content. Additional utility functions are implemented to detect, filter, and process images from HTML clipboard content, supporting both data URLs and external image URLs. The code now dispatches a custom event when images are pasted, and includes improvements for handling image removal and thumbnail generation.

Changes

File(s) Change Summary
src/components/text-editor/prosemirror-adapter/plugins/image/inserter.ts Added allowImages parameter to control image pasting; updated paste handling to filter images if disallowed; introduced utilities for image node detection, filtering, and processing; refactored image removal logic; added thumbnail support.
src/components/text-editor/prosemirror-adapter/prosemirror-adapter.tsx Added allowImages boolean property to the component; passed this prop to the image inserter plugin during initialization to enable/disable image pasting.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ProsemirrorAdapter
    participant ImageInserterPlugin
    participant Clipboard
    participant EventDispatcher

    User->>ProsemirrorAdapter: Paste content (with/without images)
    ProsemirrorAdapter->>ImageInserterPlugin: Handle paste event (allowImages)
    ImageInserterPlugin->>Clipboard: Extract HTML/image sources
    alt allowImages is false
        ImageInserterPlugin->>ImageInserterPlugin: Filter out image nodes
        ImageInserterPlugin-->>ProsemirrorAdapter: Insert filtered content
    else allowImages is true
        ImageInserterPlugin->>ImageInserterPlugin: Detect image sources
        alt Data URL
            ImageInserterPlugin->>ImageInserterPlugin: Decode to Blob/File
        else External URL
            ImageInserterPlugin->>ImageInserterPlugin: Fetch as Blob/File
        end
        ImageInserterPlugin->>EventDispatcher: Dispatch imagePasted event
        ImageInserterPlugin-->>ProsemirrorAdapter: Insert content (with images)
    end
Loading

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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.
  • @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.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Documentation has been published to https://lundalogik.github.io/lime-elements/versions/PR-3523/

@john-traas john-traas force-pushed the remove-image-filtering branch from 2c2af9b to 42a1689 Compare April 15, 2025 14:50
@john-traas john-traas marked this pull request as ready for review April 15, 2025 15:18
@Copilot Copilot AI review requested due to automatic review settings April 15, 2025 15:18
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

Comments suppressed due to low confidence (1)

src/components/text-editor/prosemirror-adapter/plugins/image/inserter.ts:102

  • The function 'isImageNode' is referenced in 'filterImageNodes' but is not defined within the current scope. Please ensure that it is properly defined or imported so that image filtering works as intended.
if (!isImageNode(child)) {

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f7382de and 680576f.

📒 Files selected for processing (2)
  • src/components/text-editor/prosemirror-adapter/plugins/image/inserter.ts (6 hunks)
  • src/components/text-editor/prosemirror-adapter/prosemirror-adapter.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.tsx`: Our `.tsx` files are typically using StencilJS, not React.

**/*.tsx: Our .tsx files are typically using StencilJS, not React.

  • src/components/text-editor/prosemirror-adapter/prosemirror-adapter.tsx
`**/*.{ts,tsx}`: Imports from other files in the same module (lime-elements) must use relative paths. Using absolute paths for imports will cause the production build to fail.

**/*.{ts,tsx}: Imports from other files in the same module (lime-elements) must use relative paths. Using absolute paths for imports will cause the production build to fail.

  • src/components/text-editor/prosemirror-adapter/prosemirror-adapter.tsx
  • src/components/text-editor/prosemirror-adapter/plugins/image/inserter.ts
🧠 Learnings (1)
📓 Common learnings
Learnt from: FredrikWallstrom
PR: Lundalogik/lime-elements#3464
File: src/components/text-editor/prosemirror-adapter/plugins/image/inserter.ts:58-67
Timestamp: 2025-03-04T14:44:40.706Z
Learning: In the image inserter plugin for the text editor's ProseMirror adapter, only standard image nodes (where node.type.name === 'image') are intentionally handled, as custom image-like nodes are not within the current scope.
🪛 Biome (1.9.4)
src/components/text-editor/prosemirror-adapter/prosemirror-adapter.tsx

[error] 124-124: This type annotation is trivially inferred from its initialization.

Safe fix: Remove the type annotation.

(lint/style/noInferrableTypes)

src/components/text-editor/prosemirror-adapter/plugins/image/inserter.ts

[error] 337-337: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

🪛 GitHub Check: Lint
src/components/text-editor/prosemirror-adapter/plugins/image/inserter.ts

[failure] 339-339:
Unexpected console statement


[failure] 378-378:
Unexpected console statement


[failure] 436-436:
Unexpected console statement


[failure] 469-469:
'urlToBlob' is assigned a value but never used. Allowed unused vars must match /^h$/u


[failure] 478-478:
Unexpected console statement


[failure] 492-492:
'createOptimizedThumbnail' is assigned a value but never used. Allowed unused vars must match /^h$/u


[failure] 494-494:
No magic number: 300


[failure] 495-495:
No magic number: 300


[failure] 496-496:
No magic number: 0.7


[failure] 529-529:
Unexpected console statement

🪛 ESLint
src/components/text-editor/prosemirror-adapter/plugins/image/inserter.ts

[error] 339-339: Unexpected console statement.

(no-console)


[error] 378-378: Unexpected console statement.

(no-console)


[error] 436-436: Unexpected console statement.

(no-console)


[error] 469-469: 'urlToBlob' is assigned a value but never used. Allowed unused vars must match /^h$/u.

(@typescript-eslint/no-unused-vars)


[error] 478-478: Unexpected console statement.

(no-console)


[error] 492-492: 'createOptimizedThumbnail' is assigned a value but never used. Allowed unused vars must match /^h$/u.

(@typescript-eslint/no-unused-vars)


[error] 494-494: No magic number: 300.

(no-magic-numbers)


[error] 495-495: No magic number: 300.

(no-magic-numbers)


[error] 496-496: No magic number: 0.7.

(no-magic-numbers)


[error] 529-529: Unexpected console statement.

(no-console)

🪛 GitHub Actions: Pull Request Checks
src/components/text-editor/prosemirror-adapter/plugins/image/inserter.ts

[error] 469-469: 'urlToBlob' is declared but its value is never read.


[error] 492-492: 'createOptimizedThumbnail' is declared but its value is never read.

🔇 Additional comments (3)
src/components/text-editor/prosemirror-adapter/plugins/image/inserter.ts (3)

26-27: Question alignment with PR objective.

You introduced an allowImages parameter to toggle image pasting, but the PR objective mentions removing image filtering. Are you sure you want to introduce this flag instead of removing the filtering logic entirely?

Also applies to: 32-32


138-141: Add null/undefined checks for fileInfoId.

When extracting fileInfoId, confirm that removedImage.attrs.fileInfoId is present. Otherwise, you might run into undefined attribute issues.

Also applies to: 147-147


440-461: Ensure consistent event properties.

dispatchImagePastedEvent is constructing the event detail with imageInserterFactory. Confirm that consumers expect the same shape of data (File + base64?). If not, you may need to unify the event schema.

Comment on lines +403 to +438
/**
* Process an external URL image
*
* @param view - The editor view
* @param url - The URL of the image
*/
const processExternalUrlImage = (view: EditorView, url: string): void => {
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(
`Failed to fetch image: ${response.statusText}`,
);
}

return response.blob();
})
.then((blob) => {
const fileType = blob.type || 'image/png';
const extension = fileType.split('/')[1] || 'png';
const fileName =
url.split('/').pop() ||
`external-image-${Date.now()}.${extension}`;
const file = new File([blob], fileName, { type: fileType });

const reader = new FileReader();
reader.onloadend = () => {
dispatchImagePastedEvent(view, reader.result as string, file);
};

reader.readAsDataURL(blob);
})
.catch((error) => {
console.error('Error processing external image:', error);
});
};
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Likewise, avoid console statements.

Line 436 logs errors to console. For consistency, handle them gracefully or rethrow them for higher-level handling.

🧰 Tools
🪛 GitHub Check: Lint

[failure] 436-436:
Unexpected console statement

🪛 ESLint

[error] 436-436: Unexpected console statement.

(no-console)

Comment on lines +344 to +361
/**
* Detect the type of image source
*
* @param src - The image source
* @returns The detected source type
*/
const detectImageSourceType = (
src: string,
): 'data-url' | 'external-url' | 'unknown' => {
if (src.startsWith('data:image/')) {
return 'data-url';
} else if (/^https?:\/\//i.exec(src) || src.startsWith('//')) {
return 'external-url';
} else {
return 'unknown';
}
};

Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Potentially simplify detection logic.

detectImageSourceType merges all unexpected patterns into 'unknown'. If you never handle 'unknown' meaningfully (beyond logging), consider refining or removing that flow.

Comment on lines +60 to +91
/**
* Check if a given ProseMirror node or fragment contains any image nodes.
* @param node - The ProseMirror node or fragment to check.
* @returns A boolean indicating whether the node contains any image nodes.
*/
const isImageNode = (node: Node | Fragment): boolean => {
if (node instanceof Node) {
if (node.type.name === 'image') {
return true;
}

let found = false;
node.content.forEach((child) => {
if (isImageNode(child)) {
found = true;
}
});

return found;
} else if (node instanceof Fragment) {
let found = false;
node.forEach((child) => {
if (isImageNode(child)) {
found = true;
}
});

return found;
}

return false;
};
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider efficiency of recursion.

While isImageNode works, note that it traverses potentially large content trees. Consider short-circuiting whenever a child image node is found to avoid unnecessary deeper traversals.

Comment on lines +250 to +263
if (!allowImages) {
const filteredSlice = new Slice(
filterImageNodes(slice.content),
slice.openStart,
slice.openEnd,
);

if (filteredSlice.content.childCount < slice.content.childCount) {
const { state, dispatch } = view;
const tr = state.tr.replaceSelection(filteredSlice);
dispatch(tr);

return 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

Reevaluate the image filtering logic.

When allowImages is false, you are fully removing image nodes from pasted content. This might conflict with the stated goal of “Remove image filtering.” Confirm whether you want to entirely block images or simply limit their usage.

Comment on lines +286 to +297
const htmlContent = clipboardData.getData('text/html');
if (htmlContent) {
const imagesSources = extractImagesFromHTML(htmlContent);
if (imagesSources.length > 0) {
for (const src of imagesSources) {
processImageSource(view, src);
}
}
}

return false;
};
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Check for potential XSS in HTML content.

Extracting HTML image sources can be risky if malicious scripts hide in data URLs. Ensure your system properly sanitizes or validates the HTML to avoid XSS concerns.

Comment on lines +299 to +342
/**
* Extract image sources from HTML content
*
* @param htmlContent - The HTML content to extract images from
* @returns An array of image source URLs
*/
const extractImagesFromHTML = (htmlContent: string): string[] => {
const sources: string[] = [];
const tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlContent;

const imgElements = tempDiv.querySelectorAll('img');
imgElements.forEach((img) => {
const src = img.getAttribute('src');
if (src) {
sources.push(src);
}
});

return sources;
};

/**
* Process an image source by detecting its type and handling it accordingly
*
* @param view - The ProseMirror editor view
* @param src - The image source URL or data URL
*/
const processImageSource = (view: EditorView, src: string): void => {
const sourceType = detectImageSourceType(src);

switch (sourceType) {
case 'data-url':
processDataUrlImage(view, src);
break;
case 'external-url':
processExternalUrlImage(view, src);
break;
case 'unknown':
default:
console.warn('Unknown image source type:', src);
break;
}
};
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Combine 'unknown' and 'default' switch cases.

You have both:

case 'unknown':
    console.warn('Unknown image source type:', src);
    break;
default:
    console.warn('Unknown image source type:', src);
    break;

This duplication violates the "noUselessSwitchCase" lint rule. Consider removing one case or merging them.

-case 'unknown':
-    console.warn('Unknown image source type:', src);
-    break;
default:
    console.warn('Unknown image source type:', src);
    break;
📝 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
/**
* Extract image sources from HTML content
*
* @param htmlContent - The HTML content to extract images from
* @returns An array of image source URLs
*/
const extractImagesFromHTML = (htmlContent: string): string[] => {
const sources: string[] = [];
const tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlContent;
const imgElements = tempDiv.querySelectorAll('img');
imgElements.forEach((img) => {
const src = img.getAttribute('src');
if (src) {
sources.push(src);
}
});
return sources;
};
/**
* Process an image source by detecting its type and handling it accordingly
*
* @param view - The ProseMirror editor view
* @param src - The image source URL or data URL
*/
const processImageSource = (view: EditorView, src: string): void => {
const sourceType = detectImageSourceType(src);
switch (sourceType) {
case 'data-url':
processDataUrlImage(view, src);
break;
case 'external-url':
processExternalUrlImage(view, src);
break;
case 'unknown':
default:
console.warn('Unknown image source type:', src);
break;
}
};
/**
* Extract image sources from HTML content
*
* @param htmlContent - The HTML content to extract images from
* @returns An array of image source URLs
*/
const extractImagesFromHTML = (htmlContent: string): string[] => {
const sources: string[] = [];
const tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlContent;
const imgElements = tempDiv.querySelectorAll('img');
imgElements.forEach((img) => {
const src = img.getAttribute('src');
if (src) {
sources.push(src);
}
});
return sources;
};
/**
* Process an image source by detecting its type and handling it accordingly
*
* @param view - The ProseMirror editor view
* @param src - The image source URL or data URL
*/
const processImageSource = (view: EditorView, src: string): void => {
const sourceType = detectImageSourceType(src);
switch (sourceType) {
case 'data-url':
processDataUrlImage(view, src);
break;
case 'external-url':
processExternalUrlImage(view, src);
break;
default:
console.warn('Unknown image source type:', src);
break;
}
};
🧰 Tools
🪛 Biome (1.9.4)

[error] 337-337: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

🪛 GitHub Check: Lint

[failure] 339-339:
Unexpected console statement

🪛 ESLint

[error] 339-339: Unexpected console statement.

(no-console)

@@ -107,6 +166,8 @@
const { state, dispatch } = view;
const { schema } = state;

// create a blob URL from the base64 data
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Clarify the comment.

This comment (“create a blob URL from the base64 data”) is incomplete. The subsequent code does not actually create a URL.createObjectURL; it just uses the raw base64 string. Consider rewording.

- // create a blob URL from the base64 data
+ // using the base64 data directly to create an image placeholder node
📝 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
// create a blob URL from the base64 data
// using the base64 data directly to create an image placeholder node

Comment on lines +484 to 535
/**
* Creates a smaller thumbnail from an image data URL
* @param dataUrl - Original image data URL
* @param maxWidth - Maximum width of thumbnail
* @param maxHeight - Maximum height of thumbnail
* @param quality - JPEG quality (0-1)
* @returns Promise resolving to a smaller thumbnail data URL
*/
const createOptimizedThumbnail = (
dataUrl: string,
maxWidth = 300,
maxHeight = 300,
quality = 0.7,
): Promise<string> => {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
// Calculate new dimensions while maintaining aspect ratio
let width = img.width;
let height = img.height;

if (width > maxWidth) {
height = (height * maxWidth) / width;
width = maxWidth;
}

if (height > maxHeight) {
width = (width * maxHeight) / height;
height = maxHeight;
}

// Create canvas and draw resized image
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);

// Convert to JPEG for better compression
const thumbnailDataUrl = canvas.toDataURL('image/jpeg', quality);
resolve(thumbnailDataUrl);
};

// Handle potential loading errors
img.onerror = () => {
console.warn('Failed to create thumbnail, using original');
resolve(dataUrl);
};

img.src = dataUrl;
});
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove unused function or call it.

createOptimizedThumbnail is never invoked. If you intend to compress large images, integrate it. Otherwise, remove to avoid dead code. Also, lines 494, 495, and 496 will trigger "no-magic-number" lint issues; consider making them configurable constants.

-const createOptimizedThumbnail = (...)
+// If needed, export or integrate usage, or remove entirely

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Check: Lint

[failure] 492-492:
'createOptimizedThumbnail' is assigned a value but never used. Allowed unused vars must match /^h$/u


[failure] 494-494:
No magic number: 300


[failure] 495-495:
No magic number: 300


[failure] 496-496:
No magic number: 0.7


[failure] 529-529:
Unexpected console statement

🪛 ESLint

[error] 492-492: 'createOptimizedThumbnail' is assigned a value but never used. Allowed unused vars must match /^h$/u.

(@typescript-eslint/no-unused-vars)


[error] 494-494: No magic number: 300.

(no-magic-numbers)


[error] 495-495: No magic number: 300.

(no-magic-numbers)


[error] 496-496: No magic number: 0.7.

(no-magic-numbers)


[error] 529-529: Unexpected console statement.

(no-console)

🪛 GitHub Actions: Pull Request Checks

[error] 492-492: 'createOptimizedThumbnail' is declared but its value is never read.

Comment on lines +368 to +401
const processDataUrlImage = (view: EditorView, dataUrl: string): void => {
// Extract mime type from data URL
const mimeMatch = /^data:([^;]+);/.exec(dataUrl);
const mimeType = mimeMatch ? mimeMatch[1] : 'image/png';
const extension = mimeType.split('/')[1] || 'png';

// Create a blob from the data URL
const regex = /^data:([^;]+);base64,(.+)$/;
const matches = regex.exec(dataUrl);
if (!matches) {
console.error('Invalid data URL format');

return;
}

const base64Data = matches[2];
const binaryString = atob(base64Data);
const bytes = new Uint8Array(binaryString.length);

for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}

const blob = new Blob([bytes], { type: mimeType });
const fileName = `pasted-image-${Date.now()}.${extension}`;
const file = new File([blob], fileName, { type: mimeType });

const reader = new FileReader();
reader.onloadend = () => {
dispatchImagePastedEvent(view, reader.result as string, file);
};

reader.readAsDataURL(blob);
};
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Avoid console statements in production code.

Line 378 logs errors to console. Many coding standards discourage console.error in production. Consider a better logging mechanism or user-facing error notification.

- console.error('Invalid data URL format');
+ // Possibly dispatch an event or handle the error more gracefully
📝 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 processDataUrlImage = (view: EditorView, dataUrl: string): void => {
// Extract mime type from data URL
const mimeMatch = /^data:([^;]+);/.exec(dataUrl);
const mimeType = mimeMatch ? mimeMatch[1] : 'image/png';
const extension = mimeType.split('/')[1] || 'png';
// Create a blob from the data URL
const regex = /^data:([^;]+);base64,(.+)$/;
const matches = regex.exec(dataUrl);
if (!matches) {
console.error('Invalid data URL format');
return;
}
const base64Data = matches[2];
const binaryString = atob(base64Data);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const blob = new Blob([bytes], { type: mimeType });
const fileName = `pasted-image-${Date.now()}.${extension}`;
const file = new File([blob], fileName, { type: mimeType });
const reader = new FileReader();
reader.onloadend = () => {
dispatchImagePastedEvent(view, reader.result as string, file);
};
reader.readAsDataURL(blob);
};
const processDataUrlImage = (view: EditorView, dataUrl: string): void => {
// Extract mime type from data URL
const mimeMatch = /^data:([^;]+);/.exec(dataUrl);
const mimeType = mimeMatch ? mimeMatch[1] : 'image/png';
const extension = mimeType.split('/')[1] || 'png';
// Create a blob from the data URL
const regex = /^data:([^;]+);base64,(.+)$/;
const matches = regex.exec(dataUrl);
if (!matches) {
// Possibly dispatch an event or handle the error more gracefully
return;
}
const base64Data = matches[2];
const binaryString = atob(base64Data);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const blob = new Blob([bytes], { type: mimeType });
const fileName = `pasted-image-${Date.now()}.${extension}`;
const file = new File([blob], fileName, { type: mimeType });
const reader = new FileReader();
reader.onloadend = () => {
dispatchImagePastedEvent(view, reader.result as string, file);
};
reader.readAsDataURL(blob);
};
🧰 Tools
🪛 GitHub Check: Lint

[failure] 378-378:
Unexpected console statement

🪛 ESLint

[error] 378-378: Unexpected console statement.

(no-console)

Comment on lines +120 to +125
/**
* Set to `true` to allow images to be pasted into the editor.
*/
@Prop()
allowImages: boolean = false;

Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Remove trivially inferred type annotation.

Line 124 triggers a lint warning: 'boolean = false' does not need a type annotation. Simply do @Prop() allowImages = false;.

- @Prop()
- allowImages: boolean = false;
+ @Prop()
+ allowImages = false;
📝 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
/**
* Set to `true` to allow images to be pasted into the editor.
*/
@Prop()
allowImages: boolean = false;
/**
* Set to `true` to allow images to be pasted into the editor.
*/
@Prop()
allowImages = false;
🧰 Tools
🪛 Biome (1.9.4)

[error] 124-124: This type annotation is trivially inferred from its initialization.

Safe fix: Remove the type annotation.

(lint/style/noInferrableTypes)

@john-traas john-traas marked this pull request as draft April 16, 2025 12:13
@john-traas
Copy link
Contributor Author

I'm going to close this PR as it includes code that does more than we're going to allow for the moment.
Changes will instead be made in lime building blocks to handle what we currently allow.

@john-traas john-traas closed this Apr 16, 2025
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.

1 participant