-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
fix(android) handle width height as strings in image-asset #10736
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
base: main
Are you sure you want to change the base?
fix(android) handle width height as strings in image-asset #10736
Conversation
@@ -47,8 +48,30 @@ export function getAspectSafeDimensions(sourceWidth, sourceHeight, reqWidth, req | |||
} | |||
|
|||
export function getRequestedImageSize(src: { width: number; height: number }, options: ImageAssetOptions): { width: number; height: number } { | |||
let reqWidth = options.width || Math.min(src.width, Screen.mainScreen.widthPixels); | |||
let reqHeight = options.height || Math.min(src.height, Screen.mainScreen.heightPixels); | |||
const optionsCopy = { ...(this.options || {}) }; |
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.
Thank you for the pr @Pastoray, it'd be good to have the ImageAssetOptions reflect that too and likely need to parse it on ios as well:
width?: number; |
should be
number | string
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.
Hi @NathanWalker ,
Thanks for the quick review and feedback!
I've pushed a few updates to the PR to reflect the width?: number | string; and height?: number | string; changes in packages/core/image-asset/index.d.ts as you suggested, as well as some changes suggested by coderabitai regarding API usage and performance.
Regarding the parsing on iOS, it looks like the getRequestedImageSize function (defined in image-asset-common.ts) is already being utilized within the getImageAsync method for both Android and iOS, so i don't really get what you meant when you said "likely need to parse it on ios as well". Let me know if I've misunderstood anything!
Thanks again.
""" WalkthroughThe changes update the image asset handling logic to allow Changes
Poem
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
npm error Exit handler never called! ✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. 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 (
|
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
🔭 Outside diff range comments (1)
packages/core/image-asset/image-asset-common.ts (1)
75-79
: 🛠️ Refactor suggestionKeep aspect-ratio flag should use the sanitized copy
After the above change,
optionsCopy
becomes the source of truth. Using the unsanitizedoptions
object here may re-introduce invalid values (e.g. string width/height that were deleted). Safer to reference the already-cleaned copy:-if (options && options.keepAspectRatio) { +if (optionsCopy.keepAspectRatio) {🧰 Tools
🪛 Biome (1.9.4)
[error] 75-75: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
🧹 Nitpick comments (3)
packages/core/image-asset/index.d.ts (1)
13-15
: Document the newly-allowed string values for better DXThe union change is correct, but the interface comment / docs still imply numeric pixel values only. Consider adding a short JSDoc note (or an inline comment) that string values should contain a number in base-10 (e.g.
"300"
), because developers might otherwise try"300px"
or"100%"
, which will be silently parsed or rejected at runtime.packages/core/image-asset/image-asset-common.ts (1)
57-60
: Minor: avoiddelete
for perf / terser outputStatic-analysis is flagging the
delete
operator. You can sidestep the cost with anundefined
assignment:- delete optionsCopy.width; + optionsCopy.width = undefined;Same for
height
. Not critical, but trivially improves V8 IC stability.Also applies to: 67-70
🧰 Tools
🪛 Biome (1.9.4)
[error] 58-58: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
packages/core/image-asset/index.android.ts (1)
28-33
: Return a realError
object for failuresCurrently you invoke the callback with a string:
callback(null, 'Asset cannot be found.');Downstream code frequently does
if (error) { ... }
and may expecterror instanceof Error
. Wrap the message:-callback(null, 'Asset cannot be found.'); +callback(null, new Error('Asset cannot be found.'));This aligns with the
image, error
contract used elsewhere in the codebase.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
packages/core/image-asset/image-asset-common.ts
(1 hunks)packages/core/image-asset/index.android.ts
(2 hunks)packages/core/image-asset/index.d.ts
(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/core/image-asset/index.android.ts (1)
packages/core/image-asset/image-asset-common.ts (1)
getRequestedImageSize
(49-85)
🪛 Biome (1.9.4)
packages/core/image-asset/image-asset-common.ts
[error] 58-58: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
[error] 68-68: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
🔇 Additional comments (1)
packages/core/image-asset/index.android.ts (1)
38-43
:optionsCopy
can inherit stale string valuesBecause
getRequestedImageSize
already parsed the strings, you can simplify:-const optionsCopy = { - ...this.options, - width: requestedSize.width, - height: requestedSize.height, -}; +const optionsCopy = { + ...this.options, + width: requestedSize.width, + height: requestedSize.height, +};(If you accept the earlier fix to use
optionsCopy
insidegetRequestedImageSize
, this stays consistent.)
const srcWidth = this.nativeImage ? this.nativeImage.size.width : Screen.mainScreen.widthPixels; | ||
const srcHeight = this.nativeImage ? this.nativeImage.size.height : Screen.mainScreen.heightPixels; | ||
const requestedSize = getRequestedImageSize({ width: srcWidth, height: srcHeight }, this.options); | ||
|
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.
Bitmap dimension retrieval may crash on Android
android.graphics.Bitmap
exposes getWidth()
/ getHeight()
, not .size.width
.
Accessing .size
will throw java.lang.NoSuchFieldError
on many devices.
A defensive fix:
-const srcWidth = this.nativeImage ? this.nativeImage.size.width : Screen.mainScreen.widthPixels;
-const srcHeight = this.nativeImage ? this.nativeImage.size.height : Screen.mainScreen.heightPixels;
+const srcWidth = this.nativeImage
+ ? (typeof this.nativeImage.getWidth === 'function'
+ ? this.nativeImage.getWidth()
+ : this.nativeImage.size?.width)
+ : Screen.mainScreen.widthPixels;
+const srcHeight = this.nativeImage
+ ? (typeof this.nativeImage.getHeight === 'function'
+ ? this.nativeImage.getHeight()
+ : this.nativeImage.size?.height)
+ : Screen.mainScreen.heightPixels;
This guards both iOS (size.width
) and Android (getWidth()
) cases.
📝 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 srcWidth = this.nativeImage ? this.nativeImage.size.width : Screen.mainScreen.widthPixels; | |
const srcHeight = this.nativeImage ? this.nativeImage.size.height : Screen.mainScreen.heightPixels; | |
const requestedSize = getRequestedImageSize({ width: srcWidth, height: srcHeight }, this.options); | |
const srcWidth = this.nativeImage | |
? (typeof this.nativeImage.getWidth === 'function' | |
? this.nativeImage.getWidth() | |
: this.nativeImage.size?.width) | |
: Screen.mainScreen.widthPixels; | |
const srcHeight = this.nativeImage | |
? (typeof this.nativeImage.getHeight === 'function' | |
? this.nativeImage.getHeight() | |
: this.nativeImage.size?.height) | |
: Screen.mainScreen.heightPixels; | |
const requestedSize = getRequestedImageSize({ width: srcWidth, height: srcHeight }, this.options); |
🤖 Prompt for AI Agents
In packages/core/image-asset/index.android.ts around lines 34 to 37, the code
incorrectly accesses bitmap dimensions using .size.width and .size.height, which
causes crashes on Android devices because android.graphics.Bitmap uses
getWidth() and getHeight() methods instead. Update the code to check if
nativeImage has getWidth and getHeight methods and use those to get dimensions
on Android; otherwise, fallback to .size.width and .size.height for iOS. This
ensures safe dimension retrieval on both platforms.
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
Plan: Pro
📒 Files selected for processing (1)
packages/core/image-asset/image-asset-common.ts
(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/core/image-asset/image-asset-common.ts
[error] 58-58: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
[error] 68-68: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
🔇 Additional comments (2)
packages/core/image-asset/image-asset-common.ts (2)
50-50
: Good fix: Correctly using theoptions
parameter.This addresses the critical issue from the previous review where
this.options
was incorrectly used in a free function. The function now properly uses theoptions
parameter.
72-73
:✅ Verification successful
Verify the type casting logic with undefined values.
The logic looks correct, but ensure that the type casting
(optionsCopy.width as number)
properly handles the case where width/height might beundefined
after invalid string parsing.Run the following script to verify how the fallback logic behaves with undefined values:
🏁 Script executed:
#!/bin/bash # Description: Test the behavior of the logical OR operator with undefined values # Create a test script to verify the fallback behavior cat > test_fallback.js << 'EOF' // Test the fallback logic const Screen = { mainScreen: { widthPixels: 1080, heightPixels: 1920 } }; const src = { width: 800, height: 600 }; // Test cases const testCases = [ { width: undefined, height: undefined }, { width: 300, height: undefined }, { width: undefined, height: 400 }, { width: 300, height: 400 } ]; testCases.forEach((optionsCopy, index) => { const reqWidth = (optionsCopy.width) || Math.min(src.width, Screen.mainScreen.widthPixels); const reqHeight = (optionsCopy.height) || Math.min(src.height, Screen.mainScreen.heightPixels); console.log(`Test ${index + 1}: width=${optionsCopy.width}, height=${optionsCopy.height} -> reqWidth=${reqWidth}, reqHeight=${reqHeight}`); }); EOF # Execute the test node test_fallback.jsLength of output: 297
Fallback logic handles undefined width/height correctly
I verified by passing
undefined
foroptionsCopy.width
/height
that the expressionsconst reqWidth = (optionsCopy.width as number) || Math.min(src.width, Screen.mainScreen.widthPixels); const reqHeight = (optionsCopy.height as number) || Math.min(src.height, Screen.mainScreen.heightPixels);correctly fall back to
Math.min(src.*, Screen.mainScreen.*)
:• Test 1 (undefined, undefined) → reqWidth=800, reqHeight=600
• Test 2 (300, undefined) → reqWidth=300, reqHeight=600
• Test 3 (undefined, 400) → reqWidth=800, reqHeight=400
• Test 4 (300, 400) → reqWidth=300, reqHeight=400No changes are required here.
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: 0
🧹 Nitpick comments (1)
packages/core/image-asset/index.ios.ts (1)
4-4
: Remove unused import.The
Screen
import is added but not used anywhere in this file. This creates dead code and should be removed to keep the codebase clean.-import {Screen} from "../platform";
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
packages/core/image-asset/image-asset-common.ts
(1 hunks)packages/core/image-asset/index.android.ts
(2 hunks)packages/core/image-asset/index.ios.ts
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/core/image-asset/image-asset-common.ts
- packages/core/image-asset/index.android.ts
🔇 Additional comments (1)
packages/core/image-asset/index.ios.ts (1)
40-46
: Good defensive programming for cross-platform compatibility.The updated logic properly checks for method existence before calling
getWidth()
andgetHeight()
methods, with appropriate fallbacks to property access. This defensive approach ensures compatibility across different native image implementations while maintaining backward compatibility.The optional chaining (
?.
) fornativeImage.size?.width
andnativeImage.size?.height
is also a good safety measure.
PR Checklist
What is the current behavior?
Passing a string (e.g. "300") to width or height in ImageAssetOptions on Android results in a crash on older API levels (e.g. API 22), with the error:
IllegalArgumentException: bitmap size exceeds 32 bits
This happens because the dimensions are not parsed properly, and Android attempts to decode the image with invalid bounds.
What is the new behavior?
Ensures that width and height are explicitly parsed using parseInt() if they are strings.
Falls back to screen dimensions (Screen.mainScreen.widthPixels/heightPixels) if parsing fails.
Prevents runtime crashes.
Fixes/Implements/Closes #[6289].
Summary by CodeRabbit
New Features
Bug Fixes
Chores