[Android][Fabric] Text keeps its pre-change width after Bold text is turned on at runtime: TextMeasureCache key has no font weight adjustment

Aberta
#59,332 1 comentário 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 2 dias

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
45/100
Tipo de issue
Bug
Clareza
Razoavelmente clara
Status de atividade
Ativa
Stack de tecnologia
android, cpp, java, react-native
Domínio
frontend, mobile

Direção de pesquisa

Read ReactCommon's TextMeasureCache.h and the Android TextLayoutManager cache path, then trace how FabricUIManager.measureText passes the font weight adjustment into measurement. Reproduce with the provided RNTester Playground example and Rubik family, toggling Bold text while the app is open. Done when text measured before the change uses widths appropriate to the adjusted face after returning to the app, while the described cache behavior is covered.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

Needs: Author Feedback Needs: Repro
Description

On Android with the New Architecture, when a custom font family has more than one weight registered (each weight its own face) and the user turns on the system Bold text setting while the app is running, Text that was measured before the change keeps its old measured width but draws with the heavier face. Single-line labels are cut: "Create account" renders as "Create", "Sign in" as "Sign", "Forgot password?" as "Forgot".

  • It persists through a second activity recreate minutes later, and clears only after a cold start (process death).
  • Strings first measured after the change (a screen opened afterwards) are whole.
  • With only one face per family name the labels are not cut: the adjusted weight then resolves to a synthetic bold of the same face, which keeps the advance widths, so the stale width still fits.

This looks like a follow-up to #57118, the change for #54931. Since that change, Fabric measurement applies the adjustment, read live at measure time: FabricUIManager.measureText passes ReactTypefaceUtils.getFontWeightAdjustment(mReactApplicationContext) (Configuration.fontWeightAdjustment, 300 with Bold text on) to TextLayoutManager.measureText, and ReactTypefaceUtils.applyFontWeightAdjustment turns weight 400 into Typeface.create(base, 700, italic). With a multi-face family that selects the real 700 face, which is wider.

What the cache key includes (read from the 0.88.0 source; TextMeasureCache.h on main today differs only in its includes):

  • TextMeasureCacheKey is {attributedString, paragraphAttributes, layoutConstraints, pointScaleFactor}. LineMeasureCacheKey is {attributedString, paragraphAttributes, size}.
  • Fragment equivalence (areAttributedStringFragmentsEquivalentLayoutWise → areTextAttributesEquivalentLayoutWise, hashed by textAttributesHashLayoutWise) compares the fragment string plus fontFamily, fontWeight, fontStyle, fontVariant, fontVariationSettings, allowFontScaling, dynamicTypeRamp, alignment, fontSize, fontSizeMultiplier, letterSpacing, lineHeight and maxFontSizeMultiplier.
  • Nothing in the key reflects the font weight adjustment: no file under ReactCommon/ mentions it, and TextLayoutContext carries only pointScaleFactor and surfaceId. fontWeight in the key is the style's own weight (unset here, which Android resolves as 400), before the adjustment is added on the Java side.
  • Nothing invalidates the cache on a configuration change: SimpleThreadSafeCache has no clear, and the Android TextLayoutManager owns textMeasureCache_ and lineMeasureCache_ for its lifetime.
  • The cache path is on by default: disableTextLayoutManagerCacheAndroid() and enablePreparedTextLayout() both default to false in ReactNativeFeatureFlagsDefaults.h, so TextLayoutManager::measure goes through textMeasureCache_.get(...). (When enablePreparedTextLayout is on, PreparedTextCacheKey has no adjustment either.)

That matches the observed pattern: a process-lifetime cache keyed without the adjustment returns the pre-change size for any string measured before the change, and misses for new strings. We have not confirmed it by running with disableTextLayoutManagerCacheAndroid set to true.

A possible direction: make the adjustment (or a configuration generation) part of the key, for example through TextLayoutContext, or drop the text caches when the configuration's font weight adjustment changes. The iOS counterpart for a runtime Dynamic Type change is #57512.

Steps to reproduce

RNTester already registers a multi-weight family, Rubik (res/font/rubik.xml has faces at 300, 400, 500 and 700; RNTesterApplication calls ReactFontManager.getInstance().addCustomFont(this, "Rubik", R.font.rubik)), so the reproducer is an edit to packages/rn-tester/js/examples/Playground/RNTesterPlayground.js:

import type {RNTesterModuleExample} from '../../types/RNTesterTypes';

import * as React from 'react';
import {StyleSheet, Text, View} from 'react-native';

function Playground() {
  return (
    <View style={styles.container}>
      {/* Row children are sized by their measured text width. */}
      <View style={styles.row}>
        <Text style={styles.label}>Create account</Text>
      </View>
      <View style={styles.row}>
        <Text style={styles.label}>Forgot password?</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {padding: 10, gap: 12},
  row: {flexDirection: 'row'},
  label: {fontFamily: 'Rubik', fontSize: 17, backgroundColor: '#eee'},
});

export default {
  title: 'Playground',
  name: 'playground',
  description: 'Test out new features and ideas.',
  render: (): React.Node => <Playground />,
} as RNTesterModuleExample;
  1. With Bold text off (adb shell settings put secure font_weight_adjustment 0), launch RNTester on an Android 12+ device or emulator and open Playground. Both labels are whole.
  2. Leave the app open and turn Bold text on: Settings → Accessibility → Display size and text → Bold text, or adb shell settings put secure font_weight_adjustment 300.
  3. Return to the app (the activity is recreated; RNTester's configChanges does not include fontWeightAdjustment). Expected: both labels whole, in the bold face. Actual: the labels draw in the bold face inside their old width and are cut.
  4. Kill the app and start it again with Bold text still on: the labels are whole.

Without RNTester, the same family can be registered in any app with an XML font family under res/font/ (two <font> entries, app:fontWeight="400" and "700") and ReactFontManager.getInstance().addCustomFont(context, "Family", R.font.family) in Application.onCreate, or in an Expo app with expo-font's FontFamilyDefinition (useFonts([{fontFamily: 'Family', fontDefinitions: [{path: regular, weight: 400}, {path: bold, weight: 700}]}])), which builds a multi-face Typeface and registers it through ReactFontManager.addCustomFont(fontFamily, typeface).

We observed this in an app through the expo-font path (Expo SDK 58), with several families each registered as a 400 face and a 700 face. The RNTester form above is that setup reduced to one label; we have not run it separately.

React Native Version

0.88.0

Affected Platforms

Runtime - Android

Areas

Fabric - The New Renderer

Output of npx @react-native-community/cli info
Collected by hand (Expo-managed app; the community CLI is not installed in it):

System:
  OS: macOS 27.0.1
Binaries:
  Node: 22.23.2
  Java: OpenJDK 17.0.19
npmPackages:
  react: 19.3.0
  react-native: 0.88.0
  expo: 58.0.16
  expo-font: 58.0.9
Android:
  newArchEnabled: true
  hermesEnabled: true
  compileSdk 37, targetSdk 36 (React Native 0.88.0 defaults)
Device:
  Android emulator, Pixel 8, API 35 (Android 15)
Stacktrace or Logs
No crash or log output: a layout-only defect.
MANDATORY Reproducer

Inline above, as an edit to RNTesterPlayground.js (RNTester's bundled Rubik family needs no font files). We can't publish a separate repository for this.

Screenshots and Videos

No screenshots attached. Observed in the app: with Bold text switched on while the app was open, "Create account" showed "Create", "Sign in" showed "Sign" and "Forgot password?" showed "Forgot"; after a cold start with Bold text still on, all three were whole.

Linguagem predominante
C++
Estrelas
127k
Forks
25.4k
Merge médio
3d 1h
PRs com merge (30d)
108

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de react/react-native

Todas as issues de react/react-native

Issues semelhantes

Mais issues de C++

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.