diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/BackgroundStyleApplicator.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/BackgroundStyleApplicator.kt index 3816dbd837db..55d478de987a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/BackgroundStyleApplicator.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/BackgroundStyleApplicator.kt @@ -93,6 +93,11 @@ public object BackgroundStyleApplicator { ensureBackgroundImageDrawable(view).backgroundImageLayers = backgroundImageLayers } + @JvmStatic + internal fun cancelBackgroundImageURLRequests(view: View) { + getBackgroundImage(view)?.cancelBackgroundImageURLRequests() + } + @JvmStatic internal fun setBackgroundSize(view: View, backgroundSizes: List?) { ensureBackgroundImageDrawable(view).backgroundSize = backgroundSizes diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/drawable/BackgroundImageDrawable.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/drawable/BackgroundImageDrawable.kt index 2acb45d374a0..7640f1b1fd97 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/drawable/BackgroundImageDrawable.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/drawable/BackgroundImageDrawable.kt @@ -16,6 +16,8 @@ import android.graphics.PixelFormat import android.graphics.Rect import android.graphics.RectF import android.graphics.drawable.Drawable +import com.facebook.common.logging.FLog +import com.facebook.react.common.ReactConstants import com.facebook.react.uimanager.FloatUtil import com.facebook.react.uimanager.LengthPercentage import com.facebook.react.uimanager.LengthPercentageType @@ -46,39 +48,62 @@ internal fun calculateBackgroundImageSize( imageHeight: Float, backgroundSize: BackgroundSize?, repeat: BackgroundRepeat?, + hasIntrinsicRatio: Boolean = false, ): Pair { var finalWidth = imageWidth var finalHeight = imageHeight + // An `auto` dimension keeps the image's aspect ratio. Without a ratio (gradients), it stays at + // its intrinsic size. + val keepsRatio = hasIntrinsicRatio && imageWidth > 0 && imageHeight > 0 + val ratio = if (keepsRatio) imageWidth / imageHeight else 0f + var xAuto = true + var yAuto = true if (backgroundSize is BackgroundSize.LengthPercentageAuto) { val w = backgroundSize.lengthPercentage.x val h = backgroundSize.lengthPercentage.y + xAuto = backgroundSize.lengthPercentage.isXAuto() + yAuto = backgroundSize.lengthPercentage.isYAuto() if (w != null) { finalWidth = positionToPixels(w, containerWidth) } if (h != null) { finalHeight = positionToPixels(h, containerHeight) } + if (keepsRatio) { + if (!xAuto && yAuto) { + finalHeight = finalWidth / ratio + } else if (xAuto && !yAuto) { + finalWidth = finalHeight * ratio + } + } } if (repeat?.x == BackgroundRepeatKeyword.Round && finalWidth > 0) { if (!FloatUtil.floatsEqual(containerWidth.rem(finalWidth), 0f)) { - val numRepeats = round(containerWidth / finalWidth) - if (numRepeats > 0) { - finalWidth = containerWidth / numRepeats - } + // CSS rounds to the nearest whole number of tiles, but at least one. + val numRepeats = maxOf(1f, round(containerWidth / finalWidth)) + finalWidth = containerWidth / numRepeats } } if (repeat?.y == BackgroundRepeatKeyword.Round && finalHeight > 0) { if (!FloatUtil.floatsEqual(containerHeight.rem(finalHeight), 0f)) { - val numRepeats = round(containerHeight / finalHeight) - if (numRepeats > 0) { - finalHeight = containerHeight / numRepeats - } + // CSS rounds to the nearest whole number of tiles, but at least one. + val numRepeats = maxOf(1f, round(containerHeight / finalHeight)) + finalHeight = containerHeight / numRepeats } } + // With `round` on one axis only, an `auto` other axis is scaled again to restore the ratio. + val roundX = repeat?.x == BackgroundRepeatKeyword.Round + val roundY = repeat?.y == BackgroundRepeatKeyword.Round + if (keepsRatio && roundX && !roundY && yAuto) { + finalHeight = finalWidth / ratio + } else if (keepsRatio && roundY && !roundX && xAuto) { + finalWidth = finalHeight * ratio + } + return finalWidth to finalHeight } @@ -95,11 +120,13 @@ internal class BackgroundImageDrawable( private var backgroundImageClipPath: Path? = null private var backgroundPositioningArea: RectF? = null private var backgroundPaintingArea: RectF? = null + private val backgroundImageURLLoader = BackgroundImageURLLoader(context) { invalidateSelf() } var backgroundImageLayers: List? = null set(value) { if (field != value) { field = value + backgroundImageURLLoader.loadBackgroundImages(value.orEmpty()) invalidateSelf() } } @@ -129,7 +156,12 @@ internal class BackgroundImageDrawable( } private val backgroundPaint: Paint = - Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } + Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { style = Paint.Style.FILL } + + /** Called when the view is dropped. */ + fun cancelBackgroundImageURLRequests() { + backgroundImageURLLoader.cancelRequests() + } override fun invalidateSelf() { needUpdatePath = true @@ -166,7 +198,7 @@ internal class BackgroundImageDrawable( } override fun draw(canvas: Canvas) { - if (backgroundImageLayers == null || backgroundImageLayers?.isEmpty() == true) { + if (backgroundImageLayers.isNullOrEmpty()) { return } @@ -195,23 +227,53 @@ internal class BackgroundImageDrawable( val position = backgroundPosition?.takeIf { it.isNotEmpty() }?.let { it.getOrNull(index % it.size) } + val uri = backgroundImageLayer.uri + val urlImage: BackgroundImageURLLoader.LoadedImage? + val (intrinsicWidth, intrinsicHeight) = + if (uri == null) { + urlImage = null + backgroundPositioningArea.width() to backgroundPositioningArea.height() + } else { + val image = backgroundImageURLLoader.imageForUri(uri) + if (image == null) { + continue + } + urlImage = image + // Asset (local require() assets) pass intrinsicWidth/Height in DIPs + // So use those dimensions and convert from dp to physical pixels. + val assetWidth = backgroundImageLayer.intrinsicWidth + val assetHeight = backgroundImageLayer.intrinsicHeight + if (assetWidth != null && assetHeight != null) { + assetWidth.dpToPx() to assetHeight.dpToPx() + } else { + // Plain url() images don't pass intrinsic width/height + // so take the image's natural pixels as DIPs and convert + image.width.dpToPx() to image.height.dpToPx() + } + } + // 2. Calculate the size of a single tile. val (tileWidth, tileHeight) = calculateBackgroundImageSize( backgroundPositioningArea.width(), backgroundPositioningArea.height(), - backgroundPositioningArea.width(), - backgroundPositioningArea.height(), + intrinsicWidth, + intrinsicHeight, size, repeat, + hasIntrinsicRatio = uri != null, ) if (tileWidth <= 0 || tileHeight <= 0) { continue } - // 3. Set paint shader - backgroundPaint.setShader(backgroundImageLayer.getShader(tileWidth, tileHeight)) + // 3. Set paint shader for gradients (URL images don't use shaders) + if (uri == null) { + backgroundPaint.setShader(backgroundImageLayer.getShader(tileWidth, tileHeight)) + } else { + backgroundPaint.setShader(null) + } // 4. Calculate spacing, x and y tiles count and position for tiles var (initialX, initialY) = calculateBackgroundPosition(tileWidth, tileHeight, position) @@ -303,18 +365,30 @@ internal class BackgroundImageDrawable( } // 5. draw the repeating tiles using translate + val urlImageMatrix = urlImage?.drawMatrix(tileWidth, tileHeight) var translateX = initialX var translateY: Float - repeat(xTilesCount) { - translateY = initialY - repeat(yTilesCount) { - canvas.save() - canvas.translate(translateX, translateY) - canvas.drawRect(0f, 0f, tileWidth, tileHeight, backgroundPaint) - canvas.restore() - translateY += tileHeight + ySpacing + val saveCount = canvas.saveCount + try { + repeat(xTilesCount) { + translateY = initialY + repeat(yTilesCount) { + canvas.save() + canvas.translate(translateX, translateY) + if (urlImage != null && urlImageMatrix != null) { + canvas.drawBitmap(urlImage.bitmap, urlImageMatrix, backgroundPaint) + } else { + canvas.drawRect(0f, 0f, tileWidth, tileHeight, backgroundPaint) + } + canvas.restore() + translateY += tileHeight + ySpacing + } + translateX += tileWidth + xSpacing } - translateX += tileWidth + xSpacing + } catch (e: RuntimeException) { + // Like `ReactImageView`: the canvas throws for a bitmap that is too large to draw. + canvas.restoreToCount(saveCount) + FLog.w(ReactConstants.TAG, e, "Could not draw background image: %s", uri) } } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/drawable/BackgroundImageURLLoader.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/drawable/BackgroundImageURLLoader.kt new file mode 100644 index 000000000000..fb10b912c100 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/drawable/BackgroundImageURLLoader.kt @@ -0,0 +1,197 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.uimanager.drawable + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Matrix +import com.facebook.common.executors.UiThreadImmediateExecutorService +import com.facebook.common.logging.FLog +import com.facebook.common.references.CloseableReference +import com.facebook.datasource.BaseDataSubscriber +import com.facebook.datasource.DataSource +import com.facebook.fresco.middleware.HasExtraData +import com.facebook.imagepipeline.common.ImageDecodeOptions +import com.facebook.imagepipeline.core.ImagePipelineFactory +import com.facebook.imagepipeline.image.CloseableImage +import com.facebook.imagepipeline.image.CloseableStaticBitmap +import com.facebook.imagepipeline.request.ImageRequestBuilder +import com.facebook.react.bridge.UiThreadUtil +import com.facebook.react.common.ReactConstants +import com.facebook.react.uimanager.style.BackgroundImageLayer +import com.facebook.react.views.imagehelper.ImageSource + +/** + * Loads the `url()` layers of a view's background image. Keeps one request for each unique uri and + * calls [onLoad] on the UI thread each time an image finishes loading. Use it only on the UI + * thread. + */ +internal class BackgroundImageURLLoader( + private val context: Context, + private val onLoad: () -> Unit, +) { + + private companion object { + // Identifies these requests in Fresco's pipeline + const val CALLER_CONTEXT = "BackgroundImage" + } + + private var entries: List = emptyList() + + /** + * Requests every `url()` layer in [backgroundImageLayers]. Does nothing if the uris did not + * change since the last call. Cancels all requests when there are no `url()` layers. + */ + fun loadBackgroundImages(backgroundImageLayers: List) { + val distinctUris = + backgroundImageLayers.mapNotNull { it.uri }.filter { it.isNotEmpty() }.distinct() + if (distinctUris == entries.map { it.uri }) { + return + } + + // Keep the entries for uris that are still used, so their images do not disappear while the + // new ones load. + val newEntries = mutableListOf() + val nextEntries = + distinctUris.map { uri -> + entries.find { it.uri == uri } ?: Entry(uri).also { newEntries.add(it) } + } + entries.filter { it !in nextEntries }.forEach { it.cancel() } + entries = nextEntries + newEntries.forEach { it.start() } + } + + fun cancelRequests() { + entries.forEach { it.cancel() } + entries = emptyList() + } + + /** Returns null until the image for [uri] has loaded. */ + fun imageForUri(uri: String): LoadedImage? = entries.find { it.uri == uri }?.image + + /** + * A decoded image from the pipeline's cache. The pipeline already applied the EXIF orientation. + * + * [encodedWidth] and [encodedHeight] are the image size before downsampling, or zero if unknown. + */ + class LoadedImage(val bitmap: Bitmap, encodedWidth: Int = 0, encodedHeight: Int = 0) { + private val hasEncodedSize = encodedWidth >= bitmap.width && encodedHeight >= bitmap.height + + /** Natural width of the image in pixels. */ + val width: Float = (if (hasEncodedSize) encodedWidth else bitmap.width).toFloat() + + /** Natural height of the image in pixels. */ + val height: Float = (if (hasEncodedSize) encodedHeight else bitmap.height).toFloat() + + /** Returns a matrix that draws [bitmap] scaled to [width] x [height]. */ + fun drawMatrix(width: Float, height: Float): Matrix = + Matrix().apply { setScale(width / bitmap.width, height / bitmap.height) } + } + + private inner class Entry(val uri: String) { + var image: LoadedImage? = null + private set + + private var dataSource: DataSource>? = null + // Keeps the bitmap in the pipeline's cache while this entry draws it. + private var imageReference: CloseableReference? = null + private var cancelled = false + + fun start() { + // The default decode options, like `Image`, so that an `Image` without resize options and a + // background image with the same uri can share one decoded bitmap in the cache. + fetch(forceStaticImage = false) + } + + private fun fetch(forceStaticImage: Boolean) { + val requestBuilder = ImageRequestBuilder.newBuilderWithSource(ImageSource(context, uri).uri) + if (forceStaticImage) { + requestBuilder.setImageDecodeOptions( + ImageDecodeOptions.newBuilder().setForceStaticImage(true).build() + ) + } + val imageRequest = + try { + requestBuilder.build() + } catch (e: RuntimeException) { + // `build()` validates the uri, e.g. a `res:` uri must name a resource id. + FLog.w(ReactConstants.TAG, e, "Invalid background image uri: %s", uri) + return + } + val dataSource = + ImagePipelineFactory.getInstance() + .imagePipeline + .fetchDecodedImage(imageRequest, CALLER_CONTEXT) + this.dataSource = dataSource + dataSource.subscribe( + object : BaseDataSubscriber>() { + override fun onNewResultImpl( + dataSource: DataSource> + ) { + if (!dataSource.isFinished) { + return + } + val imageReference = dataSource.result ?: return + // This is the final image. Closing the data source makes any later callback get + // no result, so only this reference is kept. + dataSource.close() + val closeableImage = imageReference.get() + val staticBitmap = closeableImage as? CloseableStaticBitmap + val bitmap = staticBitmap?.underlyingBitmap + if (cancelled || staticBitmap == null || bitmap == null) { + CloseableReference.closeSafely(imageReference) + if (!cancelled && staticBitmap == null) { + if (!forceStaticImage) { + // An animated image. Like iOS, show its first frame. + fetch(forceStaticImage = true) + } else { + FLog.w( + ReactConstants.TAG, + "Background image is not a static bitmap: %s", + uri, + ) + } + } + return + } + this@Entry.imageReference = imageReference + image = + LoadedImage( + bitmap, + closeableImage.getExtra(HasExtraData.KEY_ENCODED_WIDTH) ?: 0, + closeableImage.getExtra(HasExtraData.KEY_ENCODED_HEIGHT) ?: 0, + ) + onLoad() + } + + override fun onFailureImpl(dataSource: DataSource>) { + FLog.w( + ReactConstants.TAG, + dataSource.failureCause, + "Failed to load background image: %s", + uri, + ) + } + }, + // Like Fresco's drawee. A cached image calls back at once. + UiThreadImmediateExecutorService.getInstance(), + ) + } + + fun cancel() { + cancelled = true + dataSource?.close() + image = null + val imageReference = imageReference ?: return + this.imageReference = null + // The last frame drawn can still use the bitmap, so release it after that frame, like + // Fresco's drawee. + UiThreadUtil.runOnUiThread { CloseableReference.closeSafely(imageReference) } + } + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/style/BackgroundImageLayer.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/style/BackgroundImageLayer.kt index bbe43c54c493..e36c25e858ca 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/style/BackgroundImageLayer.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/style/BackgroundImageLayer.kt @@ -13,11 +13,11 @@ import com.facebook.react.bridge.ReadableMap import com.facebook.react.bridge.ReadableType /** - * Represents a single layer of a background image, typically containing a gradient. + * Represents a single layer of a background image: a gradient, or an image loaded from a `url()`. * - * This class encapsulates gradient definitions that can be applied as background layers to React - * Native views. It provides parsing from React Native bridge data and shader generation for - * rendering. + * This class encapsulates gradient definitions (conic, linear or radial) and `url()` images that + * can be applied as background layers to React Native views. It provides parsing from React Native + * bridge data and shader generation for rendering gradients. * * @see ConicGradient * @see LinearGradient @@ -26,6 +26,14 @@ import com.facebook.react.bridge.ReadableType public class BackgroundImageLayer() { private lateinit var gradient: Gradient + /** The source uri of a `url()` layer, or null for a gradient layer. */ + internal var uri: String? = null + + /** Natural size in DIPs, supplied for bundled assets. Null for a plain url. */ + internal var intrinsicWidth: Float? = null + + internal var intrinsicHeight: Float? = null + private constructor(gradient: Gradient) : this() { this.gradient = gradient } @@ -34,33 +42,61 @@ public class BackgroundImageLayer() { /** * Parses a ReadableMap into a BackgroundImageLayer. * - * The map should contain gradient configuration including a "type" key specifying a supported - * gradient type. + * The map should contain a "type" key specifying a supported gradient type, or "url". * - * @param gradientMap The map containing gradient configuration + * @param backgroundImageMap The map containing the background image configuration * @param context Android context for resource resolution * @return A BackgroundImageLayer instance, or null if parsing fails */ - public fun parse(gradientMap: ReadableMap?, context: Context): BackgroundImageLayer? { - if (gradientMap == null) { + public fun parse(backgroundImageMap: ReadableMap?, context: Context): BackgroundImageLayer? { + if (backgroundImageMap == null) { return null } - val gradient = parseGradient(gradientMap, context) ?: return null + if ( + backgroundImageMap.hasKey("type") && + backgroundImageMap.getType("type") == ReadableType.String && + backgroundImageMap.getString("type") == "url" + ) { + return parseURLImage(backgroundImageMap) + } + val gradient = parseGradient(backgroundImageMap, context) ?: return null return BackgroundImageLayer(gradient) } - private fun parseGradient(gradientMap: ReadableMap, context: Context): Gradient? { - if (!gradientMap.hasKey("type") || gradientMap.getType("type") != ReadableType.String) { + private fun parseGradient(backgroundImageMap: ReadableMap, context: Context): Gradient? { + if ( + !backgroundImageMap.hasKey("type") || + backgroundImageMap.getType("type") != ReadableType.String + ) { return null } - return when (gradientMap.getString("type")) { - "conic-gradient" -> ConicGradient.parse(gradientMap, context) - "linear-gradient" -> LinearGradient.parse(gradientMap, context) - "radial-gradient" -> RadialGradient.parse(gradientMap, context) + return when (backgroundImageMap.getString("type")) { + "conic-gradient" -> ConicGradient.parse(backgroundImageMap, context) + "linear-gradient" -> LinearGradient.parse(backgroundImageMap, context) + "radial-gradient" -> RadialGradient.parse(backgroundImageMap, context) else -> null } } + + private fun parseURLImage(urlMap: ReadableMap): BackgroundImageLayer? { + if (!urlMap.hasKey("uri") || urlMap.getType("uri") != ReadableType.String) { + return null + } + val uri = urlMap.getString("uri") ?: return null + return BackgroundImageLayer().apply { + this.uri = uri + intrinsicWidth = readDimension(urlMap, "intrinsicWidth") + intrinsicHeight = readDimension(urlMap, "intrinsicHeight") + } + } + + private fun readDimension(map: ReadableMap, key: String): Float? = + if (map.hasKey(key) && map.getType(key) == ReadableType.Number) { + map.getDouble(key).toFloat() + } else { + null + } } /** diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt index 1fbbed7edc32..ef98c912d70b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt @@ -91,6 +91,8 @@ public open class ReactViewManager : ReactClippingViewManager() } override fun onDropViewInstance(view: ReactViewGroup) { + // Before `super`, which may recycle the view and drop its background. + BackgroundStyleApplicator.cancelBackgroundImageURLRequests(view) super.onDropViewInstance(view) view.cleanUpAxOrderListener() } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/drawable/BackgroundImageURLLoaderTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/drawable/BackgroundImageURLLoaderTest.kt new file mode 100644 index 000000000000..75889288aaab --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/drawable/BackgroundImageURLLoaderTest.kt @@ -0,0 +1,75 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.uimanager.drawable + +import android.graphics.Bitmap +import com.facebook.imagepipeline.core.ImagePipelineFactory +import com.facebook.react.bridge.JavaOnlyMap +import com.facebook.react.uimanager.style.BackgroundImageLayer +import org.assertj.core.api.Assertions.* +import org.junit.After +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.GraphicsMode + +/** Tests for [BackgroundImageURLLoader] */ +@RunWith(RobolectricTestRunner::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class BackgroundImageURLLoaderTest { + private val bitmap = Bitmap.createBitmap(60, 40, Bitmap.Config.ARGB_8888) + + private fun mappedCorners(image: BackgroundImageURLLoader.LoadedImage, w: Float, h: Float) = + floatArrayOf(0f, 0f, bitmap.width.toFloat(), bitmap.height.toFloat()) + .also { image.drawMatrix(w, h).mapPoints(it) } + .toList() + + @Test + fun testUsesBitmapSizeWithoutEncodedSize() { + val image = BackgroundImageURLLoader.LoadedImage(bitmap) + assertThat(image.width).isEqualTo(60f) + assertThat(image.height).isEqualTo(40f) + assertThat(mappedCorners(image, 30f, 80f)).containsExactly(0f, 0f, 30f, 80f) + } + + @Test + fun testUsesEncodedSizeForDownsampledBitmap() { + val image = BackgroundImageURLLoader.LoadedImage(bitmap, 120, 80) + assertThat(image.width).isEqualTo(120f) + assertThat(image.height).isEqualTo(80f) + // The smaller bitmap still fills the tile. + assertThat(mappedCorners(image, 120f, 80f)).containsExactly(0f, 0f, 120f, 80f) + } + + @Test + fun testIgnoresSmallerEncodedSize() { + for ((encodedWidth, encodedHeight) in listOf(30 to 20, 120 to 20)) { + val image = BackgroundImageURLLoader.LoadedImage(bitmap, encodedWidth, encodedHeight) + assertThat(image.width).isEqualTo(60f) + assertThat(image.height).isEqualTo(40f) + } + } + + @After + fun tearDown() { + ImagePipelineFactory.shutDown() + } + + @Test + fun testTreatsInvalidResourceUriAsFailedLoad() { + val context = RuntimeEnvironment.getApplication() + ImagePipelineFactory.initialize(context) + val loader = BackgroundImageURLLoader(context) {} + for (uri in listOf("res:///icon", "res:icon")) { + val layer = BackgroundImageLayer.parse(JavaOnlyMap.of("type", "url", "uri", uri), context) + loader.loadBackgroundImages(listOfNotNull(layer)) + assertThat(loader.imageForUri(uri)).isNull() + } + } +} diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/style/BackgroundImageLayerTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/style/BackgroundImageLayerTest.kt new file mode 100644 index 000000000000..18301264ca09 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/style/BackgroundImageLayerTest.kt @@ -0,0 +1,110 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.uimanager.style + +import android.content.Context +import android.graphics.Color +import android.graphics.LinearGradient as AndroidLinearGradient +import android.util.DisplayMetrics +import com.facebook.react.bridge.JavaOnlyArray +import com.facebook.react.bridge.JavaOnlyMap +import com.facebook.react.uimanager.DisplayMetricsHolder +import org.assertj.core.api.Assertions.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment + +/** Tests for [BackgroundImageLayer] */ +@RunWith(RobolectricTestRunner::class) +class BackgroundImageLayerTest { + private lateinit var context: Context + + @Before + fun setUp() { + val metrics = DisplayMetrics() + metrics.density = 1f + DisplayMetricsHolder.setScreenDisplayMetrics(metrics) + context = RuntimeEnvironment.getApplication() + } + + @Test + fun testParsesURL() { + val layer = + BackgroundImageLayer.parse( + JavaOnlyMap.of("type", "url", "uri", "https://example.com/a.png"), + context, + ) + + assertThat(layer).isNotNull + assertThat(layer?.uri).isEqualTo("https://example.com/a.png") + assertThat(layer?.intrinsicWidth).isNull() + assertThat(layer?.intrinsicHeight).isNull() + } + + @Test + fun testParsesURLIntrinsicSize() { + val layer = + BackgroundImageLayer.parse( + JavaOnlyMap.of( + "type", + "url", + "uri", + "asset.png", + "intrinsicWidth", + 100.0, + "intrinsicHeight", + 50.0, + ), + context, + ) + + assertThat(layer).isNotNull + assertThat(layer?.uri).isEqualTo("asset.png") + assertThat(layer?.intrinsicWidth).isEqualTo(100f) + assertThat(layer?.intrinsicHeight).isEqualTo(50f) + } + + @Test + fun testRejectsURLWithoutStringURI() { + assertThat(BackgroundImageLayer.parse(JavaOnlyMap.of("type", "url"), context)).isNull() + assertThat(BackgroundImageLayer.parse(JavaOnlyMap.of("type", "url", "uri", 1.0), context)) + .isNull() + } + + @Test + fun testParsesGradient() { + val layer = + BackgroundImageLayer.parse( + JavaOnlyMap.of( + "type", + "linear-gradient", + "direction", + JavaOnlyMap.of("type", "angle", "value", 180.0), + "colorStops", + JavaOnlyArray.of( + JavaOnlyMap.of("color", Color.RED), + JavaOnlyMap.of("color", Color.BLUE), + ), + ), + context, + ) + + assertThat(layer).isNotNull + assertThat(layer?.uri).isNull() + assertThat(layer?.getShader(100f, 100f)).isInstanceOf(AndroidLinearGradient::class.java) + } + + @Test + fun testRejectsUnknownType() { + assertThat(BackgroundImageLayer.parse(JavaOnlyMap.of("type", "unknown-gradient"), context)) + .isNull() + assertThat(BackgroundImageLayer.parse(null, context)).isNull() + } +}