fabricethilaw/notable-ui-compose

Text measure during composition phase

halilozercan opened this issue · 1 comments

First of all thanks for such a cool library and extensive documentation.

One thing I noticed is that the library uses BoxWithConstraints(Subcomposition) to obtain constraints during composition and measure the text in the same phase.

https://github.com/fabricethilaw/notable-ui-compose/blob/master/components/notable-ui/src/main/java/com/notable/ui/text/ResponsiveText.kt#L326

Text measure, or referred to as text layout from here on, should be part of layout phase in Compose. To learn more about what these phases mean please check out https://developer.android.com/jetpack/compose/phases

You can see an example of this in BasicText composable.

https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/BasicText.kt%3Bl=142?q=basictext.kt

https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/CoreText.kt;l=306

As it's highlighted in the linked source code, BasicText obtains the constraints during layout phase using Layout composable. After, text layout is cached in TextController to be drawn in the next phase which is Draw.

I suggest that this library follow the same path for better performance. Subcomposition already introduces some overhead, additionally doing text measure multiple times in composition is definitely not ideal. So instead of using BoxWithConstraints, please consider using @Composable Box + Modifier.layout or just @Composable Layout to

  1. receive Constraints
  2. do the text size computation in layout
  3. cache the final TextLayoutResult in e.g. DynamicTextScalingHelper
  4. Draw the cached result in draw phase using Modifier.drawBehind