Skip to content

Conversation

flang
Copy link

@flang flang commented Aug 19, 2025

Close #23

Summary by CodeRabbit

  • New Features

    • Cropped images now preserve the source image format when detectable (JPEG/PNG/etc.).
    • Cropping flow is now asynchronous and waits for format detection before exporting.
  • Bug Fixes

    • Per-source MIME type detection with caching for consistent exports and performance.
    • Improved error handling and logging during image load and crop completion.
    • Reliable fallback to PNG if format detection fails.

@flang flang requested review from javier-godoy and paodb August 19, 2025 13:49
Copy link

coderabbitai bot commented Aug 19, 2025

Walkthrough

Adds per-source MIME-type detection and caching, makes _updateCroppedImage async, and uses the detected MIME type (falling back to image/png) when encoding the cropped canvas; callers now handle Promise rejections.

Changes

Cohort / File(s) Summary of Changes
Image crop async + MIME detection
src/main/resources/META-INF/resources/frontend/src/image-crop.tsx
Converts public _updateCroppedImage to public async _updateCroppedImage; adds private `#mimeTypeCache: Map<string,string

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Preserve original image format when cropping (JPEGs not converted to PNGs) (#23)

Possibly related PRs

Suggested reviewers

  • javier-godoy
  • paodb
  • mlopezFC

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ed0e45b and 5c3f93a.

📒 Files selected for processing (1)
  • src/main/resources/META-INF/resources/frontend/src/image-crop.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/resources/META-INF/resources/frontend/src/image-crop.tsx
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch issue-23

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:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

@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

🧹 Nitpick comments (1)
src/main/resources/META-INF/resources/frontend/src/image-crop.tsx (1)

210-264: Avoid stale-crop races introduced by async MIME detection

Now that _updateCroppedImage awaits network, a slower earlier call could dispatch a cropped image after a newer call, overwriting the latest result. Guard dispatches with a request sequence.

Apply this diff inside the method:

-	public async _updateCroppedImage(crop: PixelCrop|PercentCrop) {
+	public async _updateCroppedImage(crop: PixelCrop|PercentCrop) {
+			// Guard against out-of-order async completions
+			const seq = ++this.#updateSeq;
 			const image = this.querySelector("img");
 			if (crop && image) {
 				crop = convertToPixelCrop(crop, image.width, image.height);
@@
-					// dispatch the event containing cropped image
-					this.fireCroppedImageEvent(croppedImageDataUri);
+					// Only dispatch if this is still the latest update
+					if (seq === this.#updateSeq) {
+						this.fireCroppedImageEvent(croppedImageDataUri);
+					}
 				}
 			}
 	}

Add the backing field elsewhere in the class:

#updateSeq = 0;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a226022 and 615e37a.

📒 Files selected for processing (1)
  • src/main/resources/META-INF/resources/frontend/src/image-crop.tsx (4 hunks)
🔇 Additional comments (4)
src/main/resources/META-INF/resources/frontend/src/image-crop.tsx (4)

73-73: Good: prevent unhandled Promise rejections in onImageLoad

Chaining .catch(console.error) avoids noisy console errors and aligns with the new async flow.


126-126: Good: non-blocking error handling on crop completion

Consistent with the async update; avoids unhandled rejections during user interactions.


255-259: Preserving source MIME in toDataURL meets the PR objective

Using the detected type (with 'image/png' fallback) ensures JPEGs remain JPEGs when possible. With the normalization change above, this will also handle parameterized headers and common aliases reliably.


210-210: Verified async signature usage: no action required

  • The only invocations of _updateCroppedImage are in src/main/resources/META-INF/resources/frontend/src/image-crop.tsx (lines 73 and 126).
  • Both calls already chain .catch(console.error) for error handling.
  • No other callers assume synchronous behavior.

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

♻️ Duplicate comments (1)
src/main/resources/META-INF/resources/frontend/src/image-crop.tsx (1)

166-225: Normalize MIME (strip parameters, handle data: with comma) to prevent silent PNG fallback

Canvas toDataURL only recognizes bare types (e.g., "image/jpeg"). If you pass something like "image/jpeg; charset=binary" or parse a data URL that uses a comma delimiter (common in SVG), the browser will silently fall back to PNG, undermining the PR goal in those cases. Minimal normalization keeps logic simple while avoiding regressions.

Apply this minimal diff inside the method:

@@
-    // Case 1: data URL (e.g., data:image/png;base64,...)
+    // Case 1: data URL (e.g., data:image/png;base64,... or data:image/svg+xml,<...>)
     if (img.src.startsWith("data:")) {
-      const semiIndex = img.src.indexOf(";");
-      if (semiIndex > 5) {
-        const mimeType = img.src.substring(5, semiIndex);
-        this.#mimeTypeCache?.set(cacheKey, mimeType);
-        return mimeType;
-      }
-      this.#mimeTypeCache?.set(cacheKey, null);
-      return null;
+      const m = /^data:([^;,]+)[;,]/i.exec(img.src);
+      const mt = m ? m[1].trim().toLowerCase() : null;
+      const norm = mt === "image/jpg" ? "image/jpeg" : mt;
+      this.#mimeTypeCache?.set(cacheKey, norm);
+      return norm;
     }
@@
-    const headRes = await fetch(img.src, { method: "HEAD" });
-    let mimeType = headRes.headers.get("Content-Type");
-    if (mimeType) {
-      this.#mimeTypeCache?.set(cacheKey, mimeType);
-      return mimeType;
-    }
+    const headRes = await fetch(img.src, { method: "HEAD" });
+    let mimeType = headRes.headers.get("Content-Type");
+    if (mimeType) {
+      const base = mimeType.split(";")[0].trim().toLowerCase();
+      const norm = base === "image/jpg" ? "image/jpeg" : base;
+      this.#mimeTypeCache?.set(cacheKey, norm);
+      return norm;
+    }
@@
-    const blobRes = await fetch(img.src);
+    const blobRes = await fetch(img.src, { cache: "force-cache" });
     const blob = await blobRes.blob();
-    mimeType = blob.type || null;
-    this.#mimeTypeCache?.set(cacheKey, mimeType);
-    return mimeType;
+    const base = (blob.type || "").split(";")[0].trim().toLowerCase() || null;
+    const norm = base === "image/jpg" ? "image/jpeg" : base;
+    this.#mimeTypeCache?.set(cacheKey, norm);
+    return norm;

Notes:

  • Keeps logic simple (no broad alias tables), per your preference, while fixing common pitfalls that cause PNG fallback.
  • Optional: If you want stricter behavior, return null for unsupported types so the caller explicitly defaults to image/png instead of passing through unknown types like application/octet-stream.
🧹 Nitpick comments (2)
src/main/resources/META-INF/resources/frontend/src/image-crop.tsx (2)

227-281: Avoid stale events when multiple async updates overlap (latest-wins guard)

With the async MIME lookup, multiple _updateCroppedImage calls can race; an earlier request might resolve after a later one and dispatch an outdated crop. Add a simple sequence guard so only the latest invocation fires the event.

Apply this diff within the method:

 public async _updateCroppedImage(crop: PixelCrop|PercentCrop) {
-      const image = this.querySelector("img");
+      // Increment sequence to identify the latest in-flight update
+      const seq = ++this.#updateSeq;
+      const image = this.querySelector("img");
@@
-          // dispatch the event containing cropped image
-          this.fireCroppedImageEvent(croppedImageDataUri);
+          // dispatch only if this is still the latest update
+          if (seq === this.#updateSeq) {
+            this.fireCroppedImageEvent(croppedImageDataUri);
+          }

And add this field to the class (outside the selected range):

// Monotonic sequence to keep only the latest async crop result
#updateSeq = 0;

This keeps behavior deterministic when users drag the crop rapidly.


272-276: Nit: Pass quality only for lossy formats

Quality is only meaningful for image/jpeg (and image/webp). For other types it’s ignored; passing it is harmless but slightly noisy.

Optional tweak:

-      let croppedImageDataUri = canvas.toDataURL(imgMimeType, 1.0);
+      const needsQuality = imgMimeType === "image/jpeg" || imgMimeType === "image/webp";
+      const croppedImageDataUri = needsQuality
+        ? canvas.toDataURL(imgMimeType, 1.0)
+        : canvas.toDataURL(imgMimeType);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 615e37a and ed0e45b.

📒 Files selected for processing (1)
  • src/main/resources/META-INF/resources/frontend/src/image-crop.tsx (5 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: flang
PR: FlowingCode/ImageCrop#27
File: src/main/resources/META-INF/resources/frontend/src/image-crop.tsx:0-0
Timestamp: 2025-08-19T15:50:59.505Z
Learning: In the ImageCrop add-on project, flang prefers to keep MIME type handling simple without normalization of Content-Type headers or alias mapping, focusing on the core caching performance improvement.
📚 Learning: 2025-08-19T15:50:59.505Z
Learnt from: flang
PR: FlowingCode/ImageCrop#27
File: src/main/resources/META-INF/resources/frontend/src/image-crop.tsx:0-0
Timestamp: 2025-08-19T15:50:59.505Z
Learning: In the ImageCrop add-on project, flang prefers to keep MIME type handling simple without normalization of Content-Type headers or alias mapping, focusing on the core caching performance improvement.

Applied to files:

  • src/main/resources/META-INF/resources/frontend/src/image-crop.tsx
🔇 Additional comments (2)
src/main/resources/META-INF/resources/frontend/src/image-crop.tsx (2)

28-30: Solid perf win with per-src MIME cache

Good addition. This avoids repeated HEAD/GET on the same image and keeps the hot path fast once resolved.


76-76: Call sites correctly handle async; verify downstream expectations of event timing

Switching to an async update path means the "cropped-image" event will fire later than before (network-dependent for non-data URLs). Please verify that any server listeners or UI flows relying on immediate availability still behave as expected.

Suggested validation:

  • Manually crop rapidly several times; ensure the final event corresponds to the last crop.
  • Confirm server-side code does not assume synchronous dispatch within onComplete/onLoad.

Also applies to: 128-130

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.

JPEGs are silently converted to PNGs
1 participant