PlatformColor caching & invalidation (#54076)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/54076

Changelog: [Internal]
Add PlatformColor caching so we do not need to make as many JNI calls which helps with perf.

Reviewed By: javache

Differential Revision: D83050864

fbshipit-source-id: 56a53a5facccdbbb3ff18a66df9e07d794bb074c
This commit is contained in:
Andrew Datsenko
2025-10-08 07:41:37 -07:00
committed by meta-codesync[bot]
parent b31a2fb4b8
commit 5b9873ff35
5 changed files with 111 additions and 23 deletions
@@ -2478,6 +2478,7 @@ public final class com/facebook/react/modules/appearance/AppearanceModule : com/
public fun addListener (Ljava/lang/String;)V
public final fun emitAppearanceChanged (Ljava/lang/String;)V
public fun getColorScheme ()Ljava/lang/String;
public final fun invalidatePlatformColorCache ()V
public final fun onConfigurationChanged (Landroid/content/Context;)V
public fun removeListeners (D)V
public fun setColorScheme (Ljava/lang/String;)V
@@ -10,6 +10,7 @@ package com.facebook.react.modules.appearance
import android.content.Context
import androidx.appcompat.app.AppCompatDelegate
import com.facebook.fbreact.specs.NativeAppearanceSpec
import com.facebook.jni.annotations.DoNotStrip
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.react.bridge.buildReadableMap
@@ -84,12 +85,23 @@ constructor(
/** Sends an event to the JS instance that the preferred color scheme has changed. */
public fun emitAppearanceChanged(colorScheme: String) {
val appearancePreferences = buildReadableMap { put("colorScheme", colorScheme) }
val reactApplicationContext = getReactApplicationContextIfActiveOrWarn()
reactApplicationContext?.emitDeviceEvent(APPEARANCE_CHANGED_EVENT_NAME, appearancePreferences)
// Invalidate platform color cache on native side
invalidatePlatformColorCache()
}
public fun invalidatePlatformColorCache() {
// call into static invalidatePlatformColorCache?.run() method
Companion.invalidatePlatformColorCache?.run()
}
public companion object {
public const val NAME: String = NativeAppearanceSpec.NAME
private const val APPEARANCE_CHANGED_EVENT_NAME = "appearanceChanged"
@DoNotStrip private var invalidatePlatformColorCache: Runnable? = null
}
}
@@ -7,50 +7,86 @@
#pragma once
#include "configurePlatformColorCacheInvalidationHook.h"
#include <fbjni/fbjni.h>
#include <react/debug/react_native_expect.h>
#include <folly/container/EvictingCacheMap.h>
#include <react/renderer/core/RawValue.h>
#include <react/renderer/graphics/Color.h>
#include <react/renderer/graphics/fromRawValueShared.h>
#include <react/utils/ContextContainer.h>
#include <functional>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
namespace facebook::react {
inline size_t hashGetColourArguments(
int32_t surfaceId,
const std::vector<std::string>& resourcePaths) {
size_t seed = std::hash<int32_t>{}(surfaceId);
for (const auto& path : resourcePaths) {
seed ^=
std::hash<std::string>{}(path) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
inline SharedColor parsePlatformColor(
const ContextContainer& contextContainer,
int32_t surfaceId,
const RawValue& value) {
ColorComponents colorComponents = {0, 0, 0, 0};
Color color = 0;
if (value.hasType<
std::unordered_map<std::string, std::vector<std::string>>>()) {
const auto& fabricUIManager =
contextContainer.at<jni::global_ref<jobject>>("FabricUIManager");
static auto getColorFromJava =
fabricUIManager->getClass()
->getMethod<jint(jint, jni::JArrayClass<jni::JString>)>("getColor");
auto map = (std::unordered_map<std::string, std::vector<std::string>>)value;
auto& resourcePaths = map["resource_paths"];
auto javaResourcePaths =
jni::JArrayClass<jni::JString>::newArray(resourcePaths.size());
for (int i = 0; i < resourcePaths.size(); i++) {
javaResourcePaths->setElement(i, *jni::make_jstring(resourcePaths[i]));
}
auto color =
getColorFromJava(fabricUIManager, surfaceId, *javaResourcePaths);
// JNI calls are time consuming. Let's cache results here to avoid
// unnecessary calls.
static std::mutex getColorCacheMutex;
static folly::EvictingCacheMap<size_t, Color> getColorCache(64);
auto argb = (int64_t)color;
auto ratio = 255.f;
colorComponents.alpha = ((argb >> 24) & 0xFF) / ratio;
colorComponents.red = ((argb >> 16) & 0xFF) / ratio;
colorComponents.green = ((argb >> 8) & 0xFF) / ratio;
colorComponents.blue = (argb & 0xFF) / ratio;
// Listen for appearance changes, which should invalidate the cache
static std::once_flag setupCacheInvalidation;
std::call_once(
setupCacheInvalidation,
configurePlatformColorCacheInvalidationHook,
[&] {
std::scoped_lock lock(getColorCacheMutex);
getColorCache.clear();
});
auto hash = hashGetColourArguments(surfaceId, resourcePaths);
{
std::scoped_lock lock(getColorCacheMutex);
auto iterator = getColorCache.find(hash);
if (iterator != getColorCache.end()) {
color = iterator->second;
} else {
const auto& fabricUIManager =
contextContainer.at<jni::global_ref<jobject>>("FabricUIManager");
static auto getColorFromJava =
fabricUIManager->getClass()
->getMethod<jint(jint, jni::JArrayClass<jni::JString>)>(
"getColor");
auto javaResourcePaths =
jni::JArrayClass<jni::JString>::newArray(resourcePaths.size());
for (int i = 0; i < resourcePaths.size(); i++) {
javaResourcePaths->setElement(
i, *jni::make_jstring(resourcePaths[i]));
}
color =
getColorFromJava(fabricUIManager, surfaceId, *javaResourcePaths);
getColorCache.set(hash, color);
}
}
}
return {colorFromComponents(colorComponents)};
return color;
}
inline void fromRawValue(
@@ -0,0 +1,27 @@
/*
* 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.
*/
#include "configurePlatformColorCacheInvalidationHook.h"
#include <fbjni/NativeRunnable.h>
#include <fbjni/fbjni.h>
namespace facebook::react {
void configurePlatformColorCacheInvalidationHook(std::function<void()>&& hook) {
auto appearanceModuleClass = jni::findClassLocal(
"com/facebook/react/modules/appearance/AppearanceModule");
if (appearanceModuleClass) {
auto callbackField =
appearanceModuleClass->getStaticField<jni::JRunnable::javaobject>(
"invalidatePlatformColorCache");
jni::local_ref<jni::JRunnable> invalidationCallback =
jni::JNativeRunnable::newObjectCxxArgs(std::move(hook));
appearanceModuleClass->setStaticFieldValue(
callbackField, invalidationCallback.get());
}
}
} // namespace facebook::react
@@ -0,0 +1,12 @@
/*
* 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.
*/
#include <functional>
namespace facebook::react {
void configurePlatformColorCacheInvalidationHook(std::function<void()>&& hook);
} // namespace facebook::react