[iOS] Consider caching `accessibilityLabel` for RNGestureHandlerButton

Abierto
#4,701 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 2 días

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
53/100
Tipo de issue
Nueva funcionalidad
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
ios, objective-c, react-native

Línea de trabajo

Start in the iOS implementation of RNGestureHandlerButton and inspect its accessibilityLabel getter and RNGHRecursiveAccessibilityLabel. The issue proposes caching the inferred label for the current main-queue turn; review how the button's view tree can change during that interval. Done means repeated accessibility queries reuse the label within a turn and still reflect the current tree on the next turn.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Missing info Platform: iOS
Description

While testing performance with iOS accessibility settings turned on (Voice Control), we found that the app becomes extremely laggy: scrolling and opening screens freeze for several seconds.

This comes from how Voice Control queries the accessibility tree.

  1. After new content mounts, it asks the app many times per second which element is focused. UIKit answers each request synchronously on the main thread by walking the whole view hierarchy. During that walk, React Native's Text (RCTParagraphComponentView) runs isAccessibilityCoopted, which walks up through every ancestor of every Text and reads accessibilityLabel on any non-RN view, only to check that a label exists.
  2. When the ancestor is an RNGH button with no explicit label, its getter (RNGHRecursiveAccessibilityLabel) rebuilds the label from the button's whole subtree, creating a new NSAttributedString for every Text inside it. A button with N texts therefore rebuilds its label N + 1 times per query, and this repeats for every mounted button on every query.

In our profiles (Time Profiler, iPhone 17 Pro, iOS 26.6.1), this accounted for ~3.3s of main-thread time plus ~2.3s spent building attributed strings on a busy screen.

React Native already knows this lookup is expensive and avoids it for its own views (facebook/react-native#50265):

} else if (![ancestor isKindOfClass:[RCTViewComponentView class]] && ancestor.accessibilityLabel) {
  // Same as above, for UIView case. Cannot call this on RCTViewComponentView
  // as it is recursive and quite expensive.
  return NO;
}

RNGH can't benefit from this. RNGestureHandlerButtonComponentView is an RCTViewComponentView, but children are mounted inside the inner RNGestureHandlerButton, which is a UIControl. React Native reaches that control first and calls its expensive getter.

Therefore, we propose caching the inferred label for the current main-queue turn. An accessibility query runs synchronously on the main thread and the view tree can't change during it, so the label is built once per query instead of once per Text, and it is never stale. With this change, the time spent in the getter dropped by 82% (3,285ms → 593ms) and attributed-string building by 80% (2,259ms → 457ms):

 @implementation RNGestureHandlerButton {
   ...
+  BOOL _isRecursiveAccessibilityLabelCached;
+  NSString *_cachedRecursiveAccessibilityLabel;
 }

 - (NSString *)accessibilityLabel
 {
   NSString *label = super.accessibilityLabel;
   if (label) {
     return label;
   }
-  return RNGHRecursiveAccessibilityLabel(self);
+  if (!_isRecursiveAccessibilityLabelCached) {
+    _cachedRecursiveAccessibilityLabel = RNGHRecursiveAccessibilityLabel(self);
+    _isRecursiveAccessibilityLabelCached = YES;
+    __weak RNGestureHandlerButton *weakSelf = self;
+    dispatch_async(dispatch_get_main_queue(), ^{
+      RNGestureHandlerButton *strongSelf = weakSelf;
+      if (strongSelf != nil) {
+        strongSelf->_isRecursiveAccessibilityLabelCached = NO;
+        strongSelf->_cachedRecursiveAccessibilityLabel = nil;
+      }
+    });
+  }
+  return _cachedRecursiveAccessibilityLabel;
 }
Steps to reproduce
  1. On a physical iPhone, enable Voice Control (Settings → Accessibility → Voice Control). Simulators don't have this setting.
  2. Run the snippet below and scroll up and down.
  3. Scrolling stutters while new rows mount.
  4. For comparison, disable Voice Control and repeat: scrolling is smooth.
import { FlatList, Text, View } from 'react-native';
import { GestureHandlerRootView, Touchable } from 'react-native-gesture-handler';

const data = Array.from({ length: 80 }, (_, i) => i);

export default function App() {
  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <FlatList
        data={data}
        keyExtractor={String}
        renderItem={({ item }) => (
          <Touchable onPress={() => {}} style={{ padding: 12 }}>
            <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
              <View>
                <Text>Item {item}</Text>
                <Text>Subtitle {item}</Text>
              </View>
              <View>
                <Text>123.45</Text>
                <Text>+1.23%</Text>
              </View>
            </View>
          </Touchable>
        )}
      />
    </GestureHandlerRootView>
  );
}
A link to a Gist, an Expo Snack or a link to a repository based on this template that reproduces the bug.
Gesture Handler version

3.5.0

React Native version

0.86.3

Platforms

iOS

JavaScript runtime

None

Workflow

None

Build type

None

Device

Real device

Device model

No response

Acknowledgements

Yes

Lenguaje dominante
TypeScript
Estrellas
6.8k
Forks
1.1k
Merge medio
2 d 17 h
PR fusionados (30 d)
28

Preparar el entorno

  • Sin Dockerfile ni archivo de Docker Compose
  • Tiene una plantilla de pull request
  • Sin guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de software-mansion/react-native-gesture-handler

Todos los issues de software-mansion/react-native-gesture-handler

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.