-
Notifications
You must be signed in to change notification settings - Fork 16
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
Remove image filtering #3523
Conversation
📝 WalkthroughWalkthroughThe changes introduce a new Changes
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
Tip ⚡💬 Agentic Chat (Pro Plan, General Availability)
✨ Finishing Touches
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. 🪧 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
Documentation and Community
|
Documentation has been published to https://lundalogik.github.io/lime-elements/versions/PR-3523/ |
2c2af9b
to
42a1689
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.
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)) {
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: 12
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
📒 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 thatremovedImage.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 withimageInserterFactory
. Confirm that consumers expect the same shape of data (File + base64?). If not, you may need to unify the event schema.
/** | ||
* 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); | ||
}); | ||
}; |
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.
🧹 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)
/** | ||
* 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'; | ||
} | ||
}; | ||
|
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.
🧹 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.
/** | ||
* 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; | ||
}; |
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.
🧹 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.
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; | ||
} |
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.
🛠️ 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.
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; | ||
}; |
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.
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.
/** | ||
* 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; | ||
} | ||
}; |
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.
🧹 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.
/** | |
* 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 |
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.
🧹 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.
// create a blob URL from the base64 data | |
// using the base64 data directly to create an image placeholder node |
/** | ||
* 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; | ||
}); | ||
}; |
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.
🛠️ 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.
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); | ||
}; |
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.
🧹 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.
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)
/** | ||
* Set to `true` to allow images to be pasted into the editor. | ||
*/ | ||
@Prop() | ||
allowImages: boolean = false; | ||
|
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.
🧹 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.
/** | |
* 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)
I'm going to close this PR as it includes code that does more than we're going to allow for the moment. |
Summary by CodeRabbit
Review:
Browsers tested:
(Check any that applies, it's ok to leave boxes unchecked if testing something didn't seem relevant.)
Windows:
Linux:
macOS:
Mobile: