diff --git a/benchmark/Benchmark.cpp b/benchmark/Benchmark.cpp index a1034f747a..6c4d6a34cc 100644 --- a/benchmark/Benchmark.cpp +++ b/benchmark/Benchmark.cpp @@ -265,6 +265,8 @@ std::shared_ptr buildNodeFromJson( for (json::iterator it = nodeState.begin(); it != nodeState.end(); it++) { if (it.key() == "always-forms-containing-block") { YGNodeSetAlwaysFormsContainingBlock(node.get(), it.value()); + } else if (it.key() == "measure-func-follows-measure-modes") { + YGNodeSetMeasureFuncFollowsMeasureModes(node.get(), it.value()); } else if (it.key() == "measure-funcs") { std::vector vec{}; for (auto measureFuncJson : it.value()) { diff --git a/capture/NodeToString.cpp b/capture/NodeToString.cpp index 2f4cd32762..f13459e812 100644 --- a/capture/NodeToString.cpp +++ b/capture/NodeToString.cpp @@ -312,6 +312,11 @@ static void serializeTreeImpl( "always-forms-containing-block", YGNodeGetAlwaysFormsContainingBlock(node), YGNodeGetAlwaysFormsContainingBlock(defaultNode.get())); + appendBoolIfNotDefault( + j["node"], + "measure-func-follows-measure-modes", + YGNodeGetMeasureFuncFollowsMeasureModes(node), + YGNodeGetMeasureFuncFollowsMeasureModes(defaultNode.get())); if (YGNodeHasMeasureFunc(node)) { auto measureFuncIt = nodesToMeasureFuncs.find(node); if (measureFuncIt == nodesToMeasureFuncs.end()) { diff --git a/java/com/facebook/yoga/YogaNative.kt b/java/com/facebook/yoga/YogaNative.kt index 9f09f26b09..12fcd84d60 100644 --- a/java/com/facebook/yoga/YogaNative.kt +++ b/java/com/facebook/yoga/YogaNative.kt @@ -64,6 +64,15 @@ public object YogaNative { @JvmStatic public external fun jni_YGNodeIsReferenceBaselineJNI(nativePointer: Long): Boolean + @JvmStatic + public external fun jni_YGNodeSetMeasureFuncFollowsMeasureModesJNI( + nativePointer: Long, + followsMeasureModes: Boolean, + ) + + @JvmStatic + public external fun jni_YGNodeGetMeasureFuncFollowsMeasureModesJNI(nativePointer: Long): Boolean + @JvmStatic public external fun jni_YGNodeRemoveAllChildrenJNI(nativePointer: Long) @JvmStatic public external fun jni_YGNodeRemoveChildJNI(nativePointer: Long, childPointer: Long) diff --git a/java/com/facebook/yoga/YogaNode.kt b/java/com/facebook/yoga/YogaNode.kt index 754ed7a279..0e62437c09 100644 --- a/java/com/facebook/yoga/YogaNode.kt +++ b/java/com/facebook/yoga/YogaNode.kt @@ -239,6 +239,31 @@ public abstract class YogaNode : YogaProps { */ public open fun setNodeType(nodeType: YogaNodeType) {} + /** + * Sets whether this node's measure function sizes as [YogaMeasureFunction] describes for each + * [YogaMeasureMode]: [YogaMeasureMode.UNDEFINED] as max-content, [YogaMeasureMode.AT_MOST] as + * fit-content and [YogaMeasureMode.EXACTLY] as stretch-fit. True by default. + * + * When false, Yoga infers nothing about the node from a measurement under other constraints: + * - It reuses a measurement only under the same constraints. + * - For automatic minimum sizing (enabled by clearing + * [YogaErrata.MIN_SIZE_UNDEFINED_INSTEAD_OF_AUTO]), the measure function isn't called with + * [YogaMeasureMode.AT_MOST] 0. The node's min-content size is the one set by + * [setMinContentWidth] / [setMinContentHeight], if any; else its padding and border plus what + * its [setMinContentMeasureFunction] function returns, or plus 0 without one. + * + * Set it false for a measure function that sizes itself otherwise, for example one that fills the + * space it is given or picks a layout by it. Has no effect on the layout of a node without a + * measure function. Marks the node dirty when the value changes. + * + * Does nothing by default, so a subclass built against an earlier [YogaNode] keeps working. + */ + public open fun setMeasureFunctionFollowsMeasureModes(followsMeasureModes: Boolean) {} + + /** Whether this node's measure function sizes as the measure modes describe. True by default. */ + public open val measureFunctionFollowsMeasureModes: Boolean + get() = true + abstract override fun setMinContentMeasureFunction(measureFunction: YogaMeasureFunction?) abstract override fun setMinContentWidth(minContentWidth: Float) diff --git a/java/com/facebook/yoga/YogaNodeJNIBase.kt b/java/com/facebook/yoga/YogaNodeJNIBase.kt index 9e2b1fe14e..76a9239ef1 100644 --- a/java/com/facebook/yoga/YogaNodeJNIBase.kt +++ b/java/com/facebook/yoga/YogaNodeJNIBase.kt @@ -530,6 +530,13 @@ public abstract class YogaNodeJNIBase : YogaNode, Cloneable { YogaNative.jni_YGNodeSetNodeTypeJNI(nativePointer, nodeType.intValue()) } + override fun setMeasureFunctionFollowsMeasureModes(followsMeasureModes: Boolean) { + YogaNative.jni_YGNodeSetMeasureFuncFollowsMeasureModesJNI(nativePointer, followsMeasureModes) + } + + override val measureFunctionFollowsMeasureModes: Boolean + get() = YogaNative.jni_YGNodeGetMeasureFuncFollowsMeasureModesJNI(nativePointer) + override fun setMinContentMeasureFunction(measureFunction: YogaMeasureFunction?) { this.minContentMeasureFunction = measureFunction YogaNative.jni_YGNodeSetHasMinContentMeasureFuncJNI(nativePointer, measureFunction != null) diff --git a/java/jni/YGJNIVanilla.cpp b/java/jni/YGJNIVanilla.cpp index d3d39a704c..b97a1bff0d 100644 --- a/java/jni/YGJNIVanilla.cpp +++ b/java/jni/YGJNIVanilla.cpp @@ -239,6 +239,23 @@ static jboolean jni_YGNodeIsReferenceBaselineJNI( YGNodeIsReferenceBaseline(_jlong2YGNodeRef(nativePointer))); } +static void jni_YGNodeSetMeasureFuncFollowsMeasureModesJNI( + JNIEnv* /*env*/, + jobject /*obj*/, + jlong nativePointer, + jboolean followsMeasureModes) { + YGNodeSetMeasureFuncFollowsMeasureModes( + _jlong2YGNodeRef(nativePointer), static_cast(followsMeasureModes)); +} + +static jboolean jni_YGNodeGetMeasureFuncFollowsMeasureModesJNI( + JNIEnv* /*env*/, + jobject /*obj*/, + jlong nativePointer) { + return static_cast( + YGNodeGetMeasureFuncFollowsMeasureModes(_jlong2YGNodeRef(nativePointer))); +} + static void jni_YGNodeRemoveAllChildrenJNI( JNIEnv* /*env*/, jobject /*obj*/, @@ -880,6 +897,12 @@ static JNINativeMethod methods[] = { {"jni_YGNodeIsReferenceBaselineJNI", "(J)Z", (void*)jni_YGNodeIsReferenceBaselineJNI}, + {"jni_YGNodeSetMeasureFuncFollowsMeasureModesJNI", + "(JZ)V", + (void*)jni_YGNodeSetMeasureFuncFollowsMeasureModesJNI}, + {"jni_YGNodeGetMeasureFuncFollowsMeasureModesJNI", + "(J)Z", + (void*)jni_YGNodeGetMeasureFuncFollowsMeasureModesJNI}, {"jni_YGNodeRemoveAllChildrenJNI", "(J)V", (void*)jni_YGNodeRemoveAllChildrenJNI}, diff --git a/java/tests/com/facebook/yoga/YogaNodeTest.kt b/java/tests/com/facebook/yoga/YogaNodeTest.kt index bd1ace12ca..f74a9e36f0 100644 --- a/java/tests/com/facebook/yoga/YogaNodeTest.kt +++ b/java/tests/com/facebook/yoga/YogaNodeTest.kt @@ -341,6 +341,199 @@ class YogaNodeTest { ) } + @Test + fun testMeasureFunctionFollowsMeasureModesByDefault() { + assertTrue(createNode().measureFunctionFollowsMeasureModes) + } + + @Test + fun testClonesKeepMeasureFunctionFollowsMeasureModes() { + val node = createNode() + node.setMeasureFunctionFollowsMeasureModes(false) + assertFalse(node.measureFunctionFollowsMeasureModes) + assertFalse(node.cloneWithoutChildren().measureFunctionFollowsMeasureModes) + assertFalse(node.cloneWithChildren().measureFunctionFollowsMeasureModes) + } + + @Test + fun testResetRestoresMeasureFunctionFollowsMeasureModes() { + val node = createNode() + node.setMeasureFunctionFollowsMeasureModes(false) + node.reset() + assertTrue(node.measureFunctionFollowsMeasureModes) + } + + @Test + fun testSettingMeasureFunctionFollowsMeasureModesDirtiesOnChange() { + val root = createNode() + val child = createNode() + child.setMeasureFunction( + YogaMeasureFunction { _, _, _, _, _ -> YogaMeasureOutput.make(10f, 10f) }, + ) + root.addChildAt(child, 0) + root.calculateLayout(100f, 100f) + assertFalse(root.isDirty()) + + child.setMeasureFunctionFollowsMeasureModes(true) + assertFalse(child.isDirty()) + assertFalse(root.isDirty()) + + child.setMeasureFunctionFollowsMeasureModes(false) + assertTrue(child.isDirty()) + assertTrue(root.isDirty()) + } + + @Test + fun testMeasureFunctionIsNotAskedAgainUnderTighterBoundItFitsByDefault() { + assertEquals(0, measuresAt80WideAfterAtMost100(followsMeasureModes = true)) + } + + @Test + fun testMeasureFunctionIsAskedAgainUnderTighterBoundWhenNotFollowingMeasureModes() { + assertEquals(2, measuresAt80WideAfterAtMost100(followsMeasureModes = false)) + } + + @Test + fun testMeasureFunctionIsNotAskedAgainAtExactlyItsMeasuredWidthByDefault() { + assertEquals(0, measuresStretchedTo10AfterAtMost100(followsMeasureModes = true)) + } + + @Test + fun testMeasureFunctionIsAskedAgainAtExactlyItsMeasuredWidthWhenNotFollowingMeasureModes() { + assertEquals(1, measuresStretchedTo10AfterAtMost100(followsMeasureModes = false)) + } + + @Test + fun testMeasurementsAreKeptUnderTheSameSpecsWhenNotFollowingMeasureModes() { + var measureCount = 0 + val root = createNode() + root.alignItems = YogaAlign.FLEX_START + val child = createNode() + child.setMeasureFunction( + YogaMeasureFunction { _, _, _, _, _ -> + measureCount++ + YogaMeasureOutput.make(10f, 10f) + }, + ) + child.setMeasureFunctionFollowsMeasureModes(false) + root.addChildAt(child, 0) + val sibling = createNode() + sibling.setWidth(10f) + sibling.setHeight(10f) + root.addChildAt(sibling, 1) + root.calculateLayout(100f, YogaConstants.UNDEFINED) + val firstLayoutCount = measureCount + + sibling.setHeight(20f) + root.calculateLayout(100f, YogaConstants.UNDEFINED) + + assertEquals(firstLayoutCount, measureCount) + assertEquals(30f, root.layoutHeight, 0f) + } + + @Test + fun testMinContentProbeAsksMeasureFunctionAtMostZeroByDefault() { + val (probeCount, textWidth) = probesAtMostZeroWhenShrunk(followsMeasureModes = true) + assertTrue(probeCount > 0) + assertEquals(30f, textWidth, 0f) + } + + @Test + fun testMinContentProbeSkipsMeasureFunctionWhenNotFollowingMeasureModes() { + val (probeCount, textWidth) = probesAtMostZeroWhenShrunk(followsMeasureModes = false) + assertEquals(0, probeCount) + assertEquals(10f, textWidth, 0f) + } + + /** + * How many times a node is measured stretched to exactly 10 wide, after it measured 10 wide at + * most 100 wide, under the same height. + */ + private fun measuresStretchedTo10AfterAtMost100(followsMeasureModes: Boolean): Int { + var measureCount = 0 + val root = createNode() + root.alignItems = YogaAlign.FLEX_START + val child = createNode() + child.setMeasureFunction( + YogaMeasureFunction { _, width, widthMode, _, _ -> + measureCount++ + val measuredWidth = if (widthMode == YogaMeasureMode.EXACTLY) width else 10f + YogaMeasureOutput.make(measuredWidth, 10f) + }, + ) + child.setMeasureFunctionFollowsMeasureModes(followsMeasureModes) + root.addChildAt(child, 0) + root.calculateLayout(100f, 100f) + val firstLayoutCount = measureCount + root.alignItems = YogaAlign.STRETCH + root.calculateLayout(10f, 100f) + return measureCount - firstLayoutCount + } + + /** + * How many times a node 10 wide is measured laid out at most 80 wide, after it was laid out at + * most 100 wide. + */ + private fun measuresAt80WideAfterAtMost100(followsMeasureModes: Boolean): Int { + var measureCount = 0 + val root = createNode() + root.alignItems = YogaAlign.FLEX_START + val child = createNode() + child.setMeasureFunction( + YogaMeasureFunction { _, width, widthMode, _, _ -> + measureCount++ + val measuredWidth = if (widthMode == YogaMeasureMode.UNDEFINED) 10f else minOf(10f, width) + YogaMeasureOutput.make(measuredWidth, 10f) + }, + ) + child.setMeasureFunctionFollowsMeasureModes(followsMeasureModes) + root.addChildAt(child, 0) + root.calculateLayout(100f, YogaConstants.UNDEFINED) + val firstLayoutCount = measureCount + root.calculateLayout(80f, YogaConstants.UNDEFINED) + return measureCount - firstLayoutCount + } + + /** + * Shrinks a text 90 wide whose longest word is 30 wide into 10, beside a spacer 10 wide, with + * automatic minimum sizing on. Returns how many times its measure function is asked at most 0 + * wide, and the width it's laid out at. + */ + private fun probesAtMostZeroWhenShrunk(followsMeasureModes: Boolean): Pair { + var probeCount = 0 + val config = YogaConfigFactory.create() + config.setErrata(YogaErrata.NONE) + val root = createNode(config) + root.flexDirection = YogaFlexDirection.ROW + root.setWidth(20f) + root.setHeight(50f) + val text = createNode(config) + text.setMeasureFunction( + YogaMeasureFunction { _, width, widthMode, _, _ -> + if (widthMode == YogaMeasureMode.AT_MOST && width == 0f) { + probeCount++ + } + val measuredWidth = + when (widthMode) { + YogaMeasureMode.EXACTLY -> width + YogaMeasureMode.AT_MOST -> minOf(90f, maxOf(30f, width)) + else -> 90f + } + YogaMeasureOutput.make(measuredWidth, 16f) + }, + ) + text.setMeasureFunctionFollowsMeasureModes(followsMeasureModes) + text.setFlexBasis(90f) + text.flexShrink = 1f + root.addChildAt(text, 0) + val spacer = createNode(config) + spacer.setWidth(10f) + spacer.flexShrink = 0f + root.addChildAt(spacer, 1) + root.calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED) + return Pair(probeCount, text.layoutWidth) + } + /** No width of its own, so flexing gives it its third. */ private val fillsWidth = YogaMeasureFunction { _, _, _, _, _ -> YogaMeasureOutput.make(0f, 10f) } diff --git a/javascript/src/wrapAssembly.ts b/javascript/src/wrapAssembly.ts index f6689a2ca9..2b0f256378 100644 --- a/javascript/src/wrapAssembly.ts +++ b/javascript/src/wrapAssembly.ts @@ -106,6 +106,7 @@ export type Node = { getJustifyContent(): Justify; getGap(gutter: Gutter): Value; getMargin(edge: Edge): Value; + getMeasureFuncFollowsMeasureModes(): boolean; getMaxHeight(): Value; getMaxWidth(): Value; getMinHeight(): Value; @@ -205,6 +206,9 @@ export type Node = { setMaxWidthStretch(): void; setDirtiedFunc(dirtiedFunc: DirtiedFunction | null): void; setMeasureFunc(measureFunc: MeasureFunction | null): void; + setMeasureFuncFollowsMeasureModes( + measureFuncFollowsMeasureModes: boolean, + ): void; setMinHeight( minHeight: | number @@ -884,6 +888,10 @@ export default function wrapAssembly(lib: any): Yoga { return !!lib._YGNodeIsReferenceBaseline(this._ptr); } + getMeasureFuncFollowsMeasureModes(): boolean { + return !!lib._YGNodeGetMeasureFuncFollowsMeasureModes(this._ptr); + } + // --- Measure / Dirtied --- setMeasureFunc(measureFunc: MeasureFunction | null): void { if (measureFunc) { @@ -899,6 +907,15 @@ export default function wrapAssembly(lib: any): Yoga { lib._jswrap_YGNodeUnsetMeasureFunc(this._ptr); } + setMeasureFuncFollowsMeasureModes( + measureFuncFollowsMeasureModes: boolean, + ): void { + lib._YGNodeSetMeasureFuncFollowsMeasureModes( + this._ptr, + measureFuncFollowsMeasureModes ? 1 : 0, + ); + } + setDirtiedFunc(dirtiedFunc: DirtiedFunction | null): void { if (dirtiedFunc) { const nodeWeakRef = new WeakRef(this); diff --git a/javascript/tests/YGMeasureCacheTest.test.ts b/javascript/tests/YGMeasureCacheTest.test.ts index f570caf53a..01037481f7 100644 --- a/javascript/tests/YGMeasureCacheTest.test.ts +++ b/javascript/tests/YGMeasureCacheTest.test.ts @@ -7,7 +7,10 @@ import Yoga from 'yoga-layout'; -import {getMeasureCounterMax} from './tools/MeasureCounter.ts'; +import { + getMeasureCounterMax, + getMeasureCounterMin, +} from './tools/MeasureCounter.ts'; test('measure_once_single_flexible_child', () => { const root = Yoga.Node.create(); @@ -27,3 +30,97 @@ test('measure_once_single_flexible_child', () => { expect(measureCounter.get()).toBe(1); }); + +test('measure_func_follows_measure_modes_by_default', () => { + const node = Yoga.Node.create(); + + expect(node.getMeasureFuncFollowsMeasureModes()).toBe(true); +}); + +test('keep_tighter_atmost_width_measurement_by_default', () => { + const root = Yoga.Node.create(); + root.setAlignItems(Yoga.ALIGN_FLEX_START); + + const measureCounter = getMeasureCounterMin(); + + const root_child0 = Yoga.Node.create(); + root_child0.setMeasureFunc(measureCounter.inc); + root.insertChild(root_child0, 0); + + root.calculateLayout(100, undefined, Yoga.DIRECTION_LTR); + root.calculateLayout(80, undefined, Yoga.DIRECTION_LTR); + + expect(measureCounter.get()).toBe(1); +}); + +test('remeasure_tighter_atmost_width_when_not_following_measure_modes', () => { + const root = Yoga.Node.create(); + root.setAlignItems(Yoga.ALIGN_FLEX_START); + + const measureCounter = getMeasureCounterMin(); + + const root_child0 = Yoga.Node.create(); + root_child0.setMeasureFunc(measureCounter.inc); + root_child0.setMeasureFuncFollowsMeasureModes(false); + root.insertChild(root_child0, 0); + + root.calculateLayout(100, undefined, Yoga.DIRECTION_LTR); + expect(measureCounter.get()).toBe(2); + root.calculateLayout(80, undefined, Yoga.DIRECTION_LTR); + + expect(measureCounter.get()).toBe(4); +}); + +test('keep_measurement_for_same_spec_when_not_following_measure_modes', () => { + const root = Yoga.Node.create(); + root.setAlignItems(Yoga.ALIGN_FLEX_START); + + const measureCounter = getMeasureCounterMin(); + + const root_child0 = Yoga.Node.create(); + root_child0.setMeasureFunc(measureCounter.inc); + root_child0.setMeasureFuncFollowsMeasureModes(false); + root.insertChild(root_child0, 0); + + const root_child1 = Yoga.Node.create(); + root_child1.setWidth(10); + root_child1.setHeight(10); + root.insertChild(root_child1, 1); + + root.calculateLayout(100, undefined, Yoga.DIRECTION_LTR); + const firstLayoutCount = measureCounter.get(); + root_child1.setHeight(20); + root.calculateLayout(100, undefined, Yoga.DIRECTION_LTR); + + expect(measureCounter.get()).toBe(firstLayoutCount); + expect(root.getComputedHeight()).toBe(30); +}); + +test('setting_measure_func_follows_measure_modes_dirties_on_change', () => { + const root = Yoga.Node.create(); + + const root_child0 = Yoga.Node.create(); + root_child0.setMeasureFunc(getMeasureCounterMin().inc); + root.insertChild(root_child0, 0); + + root.calculateLayout(100, 100, Yoga.DIRECTION_LTR); + expect(root.isDirty()).toBe(false); + + root_child0.setMeasureFuncFollowsMeasureModes(true); + expect(root_child0.isDirty()).toBe(false); + expect(root.isDirty()).toBe(false); + + root_child0.setMeasureFuncFollowsMeasureModes(false); + expect(root_child0.isDirty()).toBe(true); + expect(root.isDirty()).toBe(true); + expect(root_child0.getMeasureFuncFollowsMeasureModes()).toBe(false); +}); + +test('reset_restores_measure_func_follows_measure_modes', () => { + const node = Yoga.Node.create(); + node.setMeasureFuncFollowsMeasureModes(false); + + node.reset(); + + expect(node.getMeasureFuncFollowsMeasureModes()).toBe(true); +}); diff --git a/tests/CacheTest.cpp b/tests/CacheTest.cpp index 4649797e6a..f2f01ee5dd 100644 --- a/tests/CacheTest.cpp +++ b/tests/CacheTest.cpp @@ -43,7 +43,8 @@ TEST_F(CacheTest, negativeCachedMeasurementDisablesCache) { /*lastComputedHeight=*/50.0f, 0.0f, 0.0f, - config_); + config_, + /*measureFuncFollowsMeasureModes=*/true); EXPECT_FALSE(negativeWidth); const bool negativeHeight = canUseCachedMeasurement( @@ -59,7 +60,8 @@ TEST_F(CacheTest, negativeCachedMeasurementDisablesCache) { /*lastComputedHeight=*/-0.5f, 0.0f, 0.0f, - config_); + config_, + /*measureFuncFollowsMeasureModes=*/true); EXPECT_FALSE(negativeHeight); } @@ -79,7 +81,8 @@ TEST_F(CacheTest, identicalSpecsAllowCacheReuse) { /*lastComputedHeight=*/45.0f, 0.0f, 0.0f, - config_); + config_, + /*measureFuncFollowsMeasureModes=*/true); EXPECT_TRUE(canUse); } @@ -102,7 +105,8 @@ TEST_F(CacheTest, incompatibleSpecsDisableCache) { /*lastComputedHeight=*/95.0f, 0.0f, 0.0f, - config_); + config_, + /*measureFuncFollowsMeasureModes=*/true); EXPECT_FALSE(canUse); } @@ -128,7 +132,8 @@ TEST_F( /*lastComputedHeight=*/60.0f, /*marginRow=*/10.0f, /*marginColumn=*/0.0f, - config_); + config_, + /*measureFuncFollowsMeasureModes=*/true); EXPECT_TRUE(canUse); } @@ -150,7 +155,8 @@ TEST_F(CacheTest, maxContentResultStillFitsFitContentRequest) { /*lastComputedHeight=*/50.0f, 0.0f, 0.0f, - config_); + config_, + /*measureFuncFollowsMeasureModes=*/true); EXPECT_TRUE(canUse); } @@ -172,7 +178,8 @@ TEST_F(CacheTest, tighterFitContentReusesCacheWhenPreviousResultStillFits) { /*lastComputedHeight=*/50.0f, 0.0f, 0.0f, - config_); + config_, + /*measureFuncFollowsMeasureModes=*/true); EXPECT_TRUE(canUse); } @@ -196,7 +203,8 @@ TEST_F( /*lastComputedHeight=*/50.0f, 0.0f, 0.0f, - config_); + config_, + /*measureFuncFollowsMeasureModes=*/true); EXPECT_FALSE(canUse); } @@ -221,9 +229,113 @@ TEST_F(CacheTest, pixelGridRoundingMakesSubPixelSpecsEquivalent) { /*lastComputedHeight=*/20.0f, 0.0f, 0.0f, - config_); + config_, + /*measureFuncFollowsMeasureModes=*/true); EXPECT_TRUE(canUse); } +TEST_F(CacheTest, notFollowingMeasureModesKeepsIdenticalSpecs) { + // The same spec still reuses its measurement. + EXPECT_TRUE(canUseCachedMeasurement( + SizingMode::StretchFit, + 100.0f, + SizingMode::FitContent, + 50.0f, + SizingMode::StretchFit, + 100.0f, + SizingMode::FitContent, + 50.0f, + /*lastComputedWidth=*/95.0f, + /*lastComputedHeight=*/45.0f, + 0.0f, + 0.0f, + config_, + /*measureFuncFollowsMeasureModes=*/false)); +} + +TEST_F(CacheTest, notFollowingMeasureModesDropsResultForExactSizeEqualToIt) { + // Exactly the size it measured (here after the margin), where only a measure + // function that follows the measure modes reuses its measurement. + const auto exactAtMeasuredWidth = + [this](bool measureFuncFollowsMeasureModes) { + return canUseCachedMeasurement( + SizingMode::StretchFit, + /*availableWidth=*/100.0f, + SizingMode::StretchFit, + /*availableHeight=*/60.0f, + SizingMode::FitContent, + /*lastAvailableWidth=*/90.0f, + SizingMode::StretchFit, + /*lastAvailableHeight=*/60.0f, + /*lastComputedWidth=*/90.0f, + /*lastComputedHeight=*/60.0f, + /*marginRow=*/10.0f, + /*marginColumn=*/0.0f, + config_, + measureFuncFollowsMeasureModes); + }; + EXPECT_TRUE(exactAtMeasuredWidth(/*measureFuncFollowsMeasureModes=*/true)); + EXPECT_FALSE(exactAtMeasuredWidth(/*measureFuncFollowsMeasureModes=*/false)); +} + +TEST_F(CacheTest, notFollowingMeasureModesDropsZeroResultForExactZero) { + // Unbounded it measured 0; exactly 0 is asked again. + EXPECT_FALSE(canUseCachedMeasurement( + SizingMode::StretchFit, + /*availableWidth=*/0.0f, + SizingMode::MaxContent, + /*availableHeight=*/YGUndefined, + SizingMode::MaxContent, + /*lastAvailableWidth=*/YGUndefined, + SizingMode::MaxContent, + /*lastAvailableHeight=*/YGUndefined, + /*lastComputedWidth=*/0.0f, + /*lastComputedHeight=*/0.0f, + 0.0f, + 0.0f, + config_, + /*measureFuncFollowsMeasureModes=*/false)); +} + +TEST_F( + CacheTest, + notFollowingMeasureModesDropsMaxContentResultForFitContentRequest) { + // Same inputs as maxContentResultStillFitsFitContentRequest. + EXPECT_FALSE(canUseCachedMeasurement( + SizingMode::FitContent, + /*availableWidth=*/120.0f, + SizingMode::StretchFit, + /*availableHeight=*/50.0f, + SizingMode::MaxContent, + /*lastAvailableWidth=*/YGUndefined, + SizingMode::StretchFit, + /*lastAvailableHeight=*/50.0f, + /*lastComputedWidth=*/80.0f, + /*lastComputedHeight=*/50.0f, + 0.0f, + 0.0f, + config_, + /*measureFuncFollowsMeasureModes=*/false)); +} + +TEST_F(CacheTest, notFollowingMeasureModesDropsResultForTighterFitContent) { + // Same inputs as tighterFitContentReusesCacheWhenPreviousResultStillFits. + EXPECT_FALSE(canUseCachedMeasurement( + SizingMode::FitContent, + /*availableWidth=*/100.0f, + SizingMode::StretchFit, + /*availableHeight=*/50.0f, + SizingMode::FitContent, + /*lastAvailableWidth=*/150.0f, + SizingMode::StretchFit, + /*lastAvailableHeight=*/50.0f, + /*lastComputedWidth=*/80.0f, + /*lastComputedHeight=*/50.0f, + 0.0f, + 0.0f, + config_, + /*measureFuncFollowsMeasureModes=*/false)); +} + } // namespace facebook::yoga diff --git a/tests/YGAutoMinSizeTest.cpp b/tests/YGAutoMinSizeTest.cpp index 4a6f68fc80..8b54e08c43 100644 --- a/tests/YGAutoMinSizeTest.cpp +++ b/tests/YGAutoMinSizeTest.cpp @@ -781,3 +781,101 @@ TEST(YogaAutoMinSize, errata_bit_round_trips) { YGConfigFree(config); } + +// Counts the regular measure function's calls at most 0 wide: the min-content +// probe. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +static int gAtMostZeroWidthCalls = 0; + +static YGSize measureWordWrappingTextCountingProbes( + YGNodeConstRef node, + float width, + YGMeasureMode widthMode, + float height, + YGMeasureMode heightMode) { + if (widthMode == YGMeasureModeAtMost && width == 0.0f) { + ++gAtMostZeroWidthCalls; + } + return measureWordWrappingText(node, width, widthMode, height, heightMode); +} + +// By default the regular measure function answers the probe at most 0 wide, +// and its answer is the min-content width. +TEST(YogaAutoMinSize, measure_func_probed_at_most_zero_by_default) { + ShrinkRow row(/*useAutoMinSize=*/true, /*containerWidth=*/20); + YGNodeSetMeasureFunc(row.text, measureWordWrappingTextCountingProbes); + gAtMostZeroWidthCalls = 0; + row.layout(); + + EXPECT_GT(gAtMostZeroWidthCalls, 0); + EXPECT_FLOAT_EQ(kWordWidth, YGNodeLayoutGetWidth(row.text)); +} + +// A measure function that doesn't follow the measure modes isn't probed: what +// it answers at most 0 wide says nothing about its min-content, which is 0. +TEST( + YogaAutoMinSize, + measure_func_not_probed_when_not_following_measure_modes) { + ShrinkRow row(/*useAutoMinSize=*/true, /*containerWidth=*/20); + YGNodeSetMeasureFunc(row.text, measureWordWrappingTextCountingProbes); + YGNodeSetMeasureFuncFollowsMeasureModes(row.text, false); + gAtMostZeroWidthCalls = 0; + row.layout(); + + EXPECT_EQ(gAtMostZeroWidthCalls, 0); + // Floor 0: the text shrinks to 10 (container 20 - spacer 10). + EXPECT_FLOAT_EQ(10.0f, YGNodeLayoutGetWidth(row.text)); +} + +// A static min-content is still honoured when the measure function doesn't +// follow the measure modes. +TEST( + YogaAutoMinSize, + static_min_content_honoured_when_not_following_measure_modes) { + ShrinkRow row(/*useAutoMinSize=*/true, /*containerWidth=*/20); + YGNodeSetMeasureFunc(row.text, measureWordWrappingTextCountingProbes); + YGNodeSetMeasureFuncFollowsMeasureModes(row.text, false); + YGNodeSetMinContentWidth(row.text, 25.0f); + gAtMostZeroWidthCalls = 0; + row.layout(); + + EXPECT_EQ(gAtMostZeroWidthCalls, 0); + EXPECT_FLOAT_EQ(25.0f, YGNodeLayoutGetWidth(row.text)); +} + +// So is a min-content measure function. +TEST( + YogaAutoMinSize, + min_content_measure_func_honoured_when_not_following_measure_modes) { + ShrinkRow row(/*useAutoMinSize=*/true, /*containerWidth=*/20); + YGNodeSetMeasureFunc(row.text, measureWordWrappingTextCountingProbes); + YGNodeSetMeasureFuncFollowsMeasureModes(row.text, false); + YGNodeSetMinContentMeasureFunc(row.text, measureMinContentWord); + gAtMostZeroWidthCalls = 0; + gMinContentCalls = 0; + row.layout(); + + EXPECT_EQ(gAtMostZeroWidthCalls, 0); + EXPECT_GT(gMinContentCalls, 0); + EXPECT_FLOAT_EQ(kWordWidth, YGNodeLayoutGetWidth(row.text)); +} + +// Its padding and border still count: only its content contributes 0. +TEST( + YogaAutoMinSize, + padding_and_border_count_when_not_following_measure_modes) { + ShrinkRow row(/*useAutoMinSize=*/true, /*containerWidth=*/15); + YGNodeSetMeasureFunc(row.text, measureWordWrappingTextCountingProbes); + YGNodeSetMeasureFuncFollowsMeasureModes(row.text, false); + YGNodeStyleSetPadding(row.text, YGEdgeLeft, 3); + YGNodeStyleSetPadding(row.text, YGEdgeRight, 4); + YGNodeStyleSetBorder(row.text, YGEdgeLeft, 1); + YGNodeStyleSetBorder(row.text, YGEdgeRight, 2); + gAtMostZeroWidthCalls = 0; + row.layout(); + + EXPECT_EQ(gAtMostZeroWidthCalls, 0); + // Floor 10 (3 + 4 + 1 + 2), above the 5 left for it (container 15 - spacer + // 10). + EXPECT_FLOAT_EQ(10.0f, YGNodeLayoutGetWidth(row.text)); +} diff --git a/tests/YGMeasureCacheTest.cpp b/tests/YGMeasureCacheTest.cpp index 0567265458..85c002ea85 100644 --- a/tests/YGMeasureCacheTest.cpp +++ b/tests/YGMeasureCacheTest.cpp @@ -7,6 +7,7 @@ #include #include +#include static YGSize _measureMax( YGNodeConstRef node, @@ -221,3 +222,319 @@ TEST(YogaTest, remeasure_when_owner_resizes_with_percent_padding) { YGNodeFreeRecursive(root); } + +TEST(YogaTest, measure_func_follows_measure_modes_by_default) { + YGNodeRef node = YGNodeNew(); + ASSERT_TRUE(YGNodeGetMeasureFuncFollowsMeasureModes(node)); + YGNodeFree(node); +} + +TEST( + YogaTest, + remeasure_tighter_atmost_width_when_not_following_measure_modes) { + YGNodeRef root = YGNodeNew(); + YGNodeStyleSetAlignItems(root, YGAlignFlexStart); + + YGNodeRef root_child0 = YGNodeNew(); + int measureCount = 0; + YGNodeSetContext(root_child0, &measureCount); + YGNodeSetMeasureFunc(root_child0, _measureMin); + YGNodeSetMeasureFuncFollowsMeasureModes(root_child0, false); + YGNodeInsertChild(root, root_child0, 0); + + YGNodeCalculateLayout(root, 100, YGUndefined, YGDirectionLTR); + ASSERT_EQ(2, measureCount); + YGNodeCalculateLayout(root, 80, YGUndefined, YGDirectionLTR); + ASSERT_EQ(4, measureCount); + + YGNodeFreeRecursive(root); +} + +TEST(YogaTest, keep_tighter_atmost_width_measurement_by_default) { + YGNodeRef root = YGNodeNew(); + YGNodeStyleSetAlignItems(root, YGAlignFlexStart); + + YGNodeRef root_child0 = YGNodeNew(); + int measureCount = 0; + YGNodeSetContext(root_child0, &measureCount); + YGNodeSetMeasureFunc(root_child0, _measureMin); + YGNodeInsertChild(root, root_child0, 0); + + YGNodeCalculateLayout(root, 100, YGUndefined, YGDirectionLTR); + YGNodeCalculateLayout(root, 80, YGUndefined, YGDirectionLTR); + ASSERT_EQ(1, measureCount); + + YGNodeFreeRecursive(root); +} + +TEST( + YogaTest, + remeasure_atmost_after_max_content_when_not_following_measure_modes) { + YGNodeRef root = YGNodeNew(); + YGNodeStyleSetAlignItems(root, YGAlignFlexStart); + + YGNodeRef root_child0 = YGNodeNew(); + int measureCount = 0; + YGNodeSetContext(root_child0, &measureCount); + YGNodeSetMeasureFunc(root_child0, _measureMin); + YGNodeSetMeasureFuncFollowsMeasureModes(root_child0, false); + YGNodeInsertChild(root, root_child0, 0); + + YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); + ASSERT_EQ(2, measureCount); + YGNodeCalculateLayout(root, 80, YGUndefined, YGDirectionLTR); + ASSERT_EQ(4, measureCount); + + YGNodeFreeRecursive(root); +} + +TEST(YogaTest, keep_max_content_measurement_for_atmost_by_default) { + YGNodeRef root = YGNodeNew(); + YGNodeStyleSetAlignItems(root, YGAlignFlexStart); + + YGNodeRef root_child0 = YGNodeNew(); + int measureCount = 0; + YGNodeSetContext(root_child0, &measureCount); + YGNodeSetMeasureFunc(root_child0, _measureMin); + YGNodeInsertChild(root, root_child0, 0); + + YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); + YGNodeCalculateLayout(root, 80, YGUndefined, YGDirectionLTR); + ASSERT_EQ(1, measureCount); + + YGNodeFreeRecursive(root); +} + +TEST( + YogaTest, + remeasure_exact_measured_width_when_not_following_measure_modes) { + YGNodeRef root = YGNodeNew(); + YGNodeStyleSetAlignItems(root, YGAlignFlexStart); + + YGNodeRef root_child0 = YGNodeNew(); + int measureCount = 0; + YGNodeSetContext(root_child0, &measureCount); + YGNodeSetMeasureFunc(root_child0, _measureMin); + YGNodeSetMeasureFuncFollowsMeasureModes(root_child0, false); + YGNodeInsertChild(root, root_child0, 0); + + // At most 100 wide it measures 10 wide. Stretched to exactly 10 wide, under + // the same height spec, its width is exact and equal to what it measured: + // only a measure function that follows the measure modes reuses its + // measurement there. + YGNodeCalculateLayout(root, 100, 100, YGDirectionLTR); + ASSERT_EQ(2, measureCount); + YGNodeStyleSetAlignItems(root, YGAlignStretch); + YGNodeCalculateLayout(root, 10, 100, YGDirectionLTR); + ASSERT_EQ(3, measureCount); + ASSERT_FLOAT_EQ(10, YGNodeLayoutGetWidth(root_child0)); + + YGNodeFreeRecursive(root); +} + +TEST(YogaTest, keep_measurement_for_exact_measured_width_by_default) { + YGNodeRef root = YGNodeNew(); + YGNodeStyleSetAlignItems(root, YGAlignFlexStart); + + YGNodeRef root_child0 = YGNodeNew(); + int measureCount = 0; + YGNodeSetContext(root_child0, &measureCount); + YGNodeSetMeasureFunc(root_child0, _measureMin); + YGNodeInsertChild(root, root_child0, 0); + + YGNodeCalculateLayout(root, 100, 100, YGDirectionLTR); + YGNodeStyleSetAlignItems(root, YGAlignStretch); + YGNodeCalculateLayout(root, 10, 100, YGDirectionLTR); + ASSERT_EQ(1, measureCount); + + YGNodeFreeRecursive(root); +} + +TEST(YogaTest, remeasure_exact_measured_size_when_not_following_measure_modes) { + YGNodeRef root = YGNodeNew(); + YGNodeRef root_child0 = YGNodeNew(); + int measureCount = 0; + YGNodeSetContext(root_child0, &measureCount); + YGNodeSetMeasureFunc(root_child0, _measureMin); + YGNodeSetMeasureFuncFollowsMeasureModes(root_child0, false); + YGNodeInsertChild(root, root_child0, 0); + + // Unbounded it measures 10 x 10; then exactly 10 wide and at most 100 high: + // asked again. + YGNodeStyleSetAlignItems(root, YGAlignFlexStart); + YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); + ASSERT_EQ(2, measureCount); + YGNodeStyleSetAlignItems(root, YGAlignStretch); + YGNodeCalculateLayout(root, 10, 100, YGDirectionLTR); + ASSERT_EQ(3, measureCount); + + YGNodeFreeRecursive(root); +} + +TEST( + YogaTest, + keep_measurement_for_same_spec_when_not_following_measure_modes) { + YGNodeRef root = YGNodeNew(); + YGNodeStyleSetAlignItems(root, YGAlignFlexStart); + + YGNodeRef root_child0 = YGNodeNew(); + int measureCount = 0; + YGNodeSetContext(root_child0, &measureCount); + YGNodeSetMeasureFunc(root_child0, _measureMin); + YGNodeSetMeasureFuncFollowsMeasureModes(root_child0, false); + YGNodeInsertChild(root, root_child0, 0); + + YGNodeRef root_child1 = YGNodeNew(); + YGNodeStyleSetWidth(root_child1, 10); + YGNodeStyleSetHeight(root_child1, 10); + YGNodeInsertChild(root, root_child1, 1); + + // Its sibling grows, which lays the root out again, and asks it under the + // same specs: its measurements are kept. + YGNodeCalculateLayout(root, 100, YGUndefined, YGDirectionLTR); + const int firstLayoutCount = measureCount; + YGNodeStyleSetHeight(root_child1, 20); + YGNodeCalculateLayout(root, 100, YGUndefined, YGDirectionLTR); + ASSERT_EQ(firstLayoutCount, measureCount); + ASSERT_FLOAT_EQ(30, YGNodeLayoutGetHeight(root)); + + YGNodeFreeRecursive(root); +} + +TEST( + YogaTest, + remeasure_exact_width_tighter_atmost_height_when_not_following_measure_modes) { + YGNodeRef root = YGNodeNew(); + YGNodeStyleSetAlignItems(root, YGAlignFlexStart); + + YGNodeRef root_child0 = YGNodeNew(); + int measureCount = 0; + YGNodeSetContext(root_child0, &measureCount); + YGNodeSetMeasureFunc(root_child0, _measureMin); + YGNodeSetMeasureFuncFollowsMeasureModes(root_child0, false); + YGNodeInsertChild(root, root_child0, 0); + + // As remeasure_with_computed_width_larger_than_needed_height: exactly 10 + // wide matches the width it measured, but at most 50 high is a tighter bound + // than the 100 it measured under: only a measure function that follows the + // measure modes reuses its measurement there. + YGNodeCalculateLayout(root, 100, 100, YGDirectionLTR); + ASSERT_EQ(2, measureCount); + YGNodeStyleSetAlignItems(root, YGAlignStretch); + YGNodeCalculateLayout(root, 10, 50, YGDirectionLTR); + ASSERT_EQ(3, measureCount); + + YGNodeFreeRecursive(root); +} + +TEST( + YogaTest, + measure_again_at_exactly_its_measured_height_when_not_following_measure_modes) { + // In a column, its height is measured with no bound, then laid out at + // exactly the height it measured: measured once when its measure function + // follows the measure modes, and twice when it doesn't. + for (const bool measureFuncFollowsMeasureModes : {true, false}) { + YGNodeRef root = YGNodeNew(); + YGNodeStyleSetAlignItems(root, YGAlignFlexStart); + + YGNodeRef root_child0 = YGNodeNew(); + int measureCount = 0; + YGNodeSetContext(root_child0, &measureCount); + YGNodeSetMeasureFunc(root_child0, _measureMin); + YGNodeSetMeasureFuncFollowsMeasureModes( + root_child0, measureFuncFollowsMeasureModes); + YGNodeInsertChild(root, root_child0, 0); + + YGNodeCalculateLayout(root, 100, YGUndefined, YGDirectionLTR); + ASSERT_EQ(measureFuncFollowsMeasureModes ? 1 : 2, measureCount); + + YGNodeFreeRecursive(root); + } +} + +TEST(YogaTest, setting_measure_func_follows_measure_modes_dirties_on_change) { + YGNodeRef root = YGNodeNew(); + + YGNodeRef root_child0 = YGNodeNew(); + int measureCount = 0; + YGNodeSetContext(root_child0, &measureCount); + YGNodeSetMeasureFunc(root_child0, _measureMin); + YGNodeInsertChild(root, root_child0, 0); + + YGNodeCalculateLayout(root, 100, 100, YGDirectionLTR); + ASSERT_FALSE(YGNodeIsDirty(root)); + + YGNodeSetMeasureFuncFollowsMeasureModes(root_child0, true); + ASSERT_FALSE(YGNodeIsDirty(root_child0)); + ASSERT_FALSE(YGNodeIsDirty(root)); + + YGNodeSetMeasureFuncFollowsMeasureModes(root_child0, false); + ASSERT_TRUE(YGNodeIsDirty(root_child0)); + ASSERT_TRUE(YGNodeIsDirty(root)); + + YGNodeFreeRecursive(root); +} + +TEST(YogaTest, cloned_node_keeps_measure_func_follows_measure_modes) { + YGNodeRef node = YGNodeNew(); + YGNodeSetMeasureFunc(node, _measureMin); + YGNodeSetMeasureFuncFollowsMeasureModes(node, false); + + YGNodeRef clone = YGNodeClone(node); + ASSERT_FALSE(YGNodeGetMeasureFuncFollowsMeasureModes(clone)); + + YGNodeFree(clone); + YGNodeFree(node); +} + +TEST(YogaTest, moved_node_keeps_measure_func_follows_measure_modes) { + facebook::yoga::Node node; + node.setMeasureFuncFollowsMeasureModes(false); + + facebook::yoga::Node moved{std::move(node)}; + ASSERT_FALSE(moved.measureFuncFollowsMeasureModes()); +} + +TEST(YogaTest, reset_restores_measure_func_follows_measure_modes) { + YGNodeRef node = YGNodeNew(); + YGNodeSetMeasureFuncFollowsMeasureModes(node, false); + + YGNodeReset(node); + ASSERT_TRUE(YGNodeGetMeasureFuncFollowsMeasureModes(node)); + + YGNodeFree(node); +} + +TEST(YogaTest, measure_func_follows_measure_modes_has_no_effect_on_container) { + // A container without a measure function reuses its layout only under the + // same constraints either way: its measured child is asked as often, and it + // is laid out the same. + int measureCounts[2] = {0, 0}; + float containerWidths[2] = {0, 0}; + for (const bool measureFuncFollowsMeasureModes : {true, false}) { + int& measureCount = measureCounts[measureFuncFollowsMeasureModes ? 0 : 1]; + YGNodeRef root = YGNodeNew(); + YGNodeStyleSetAlignItems(root, YGAlignFlexStart); + + YGNodeRef container = YGNodeNew(); + YGNodeSetMeasureFuncFollowsMeasureModes( + container, measureFuncFollowsMeasureModes); + YGNodeInsertChild(root, container, 0); + + YGNodeRef leaf = YGNodeNew(); + YGNodeSetContext(leaf, &measureCount); + YGNodeSetMeasureFunc(leaf, _measureMin); + YGNodeInsertChild(container, leaf, 0); + + YGNodeCalculateLayout(root, 100, YGUndefined, YGDirectionLTR); + YGNodeStyleSetAlignItems(root, YGAlignStretch); + YGNodeCalculateLayout(root, 10, YGUndefined, YGDirectionLTR); + YGNodeCalculateLayout(root, 80, YGUndefined, YGDirectionLTR); + containerWidths[measureFuncFollowsMeasureModes ? 0 : 1] = + YGNodeLayoutGetWidth(container); + + YGNodeFreeRecursive(root); + } + ASSERT_EQ(measureCounts[0], measureCounts[1]); + ASSERT_FLOAT_EQ(containerWidths[0], containerWidths[1]); +} diff --git a/website/docs/advanced/external-layout-systems.mdx b/website/docs/advanced/external-layout-systems.mdx index 1cff7e3dc9..1873f8012e 100644 --- a/website/docs/advanced/external-layout-systems.mdx +++ b/website/docs/advanced/external-layout-systems.mdx @@ -73,6 +73,46 @@ Each axis is passed a `MeasureMode` as a constraint: 2. `Undefined`: The measured length in the given axis should be the maximum natural length of the content. This corresponds to [`max-content`](https://www.w3.org/TR/css-sizing-3/#max-content) sizing. 3. `AtMost`: The measured length in the given axis should be the minimum of the available space in the axis, and the natural content size. This corresponds to [`fit-content`](https://www.w3.org/TR/css-sizing-3/#fit-content-size) sizing. +## Measure functions that size themselves otherwise + +Yoga relies on a measure function sizing as the measure modes above describe, and infers sizes from it: it reuses a measurement under a tighter `AtMost` bound the measured size still fits within, reuses an `Undefined` measurement under an `AtMost` bound it fits within, reuses a measurement under an `Exactly` size equal to the size measured, and, for [automatic minimum sizing](https://www.w3.org/TR/css-flexbox-1/#min-size-auto), takes the size measured at `AtMost` 0 as the min-content size of the node's content. Yoga applies automatic minimum sizing only when the `MinSizeUndefinedInsteadOfAuto` errata is cleared. + +A measure function may size itself otherwise, for example one that fills the space it is given, or one that picks a layout by it. Tell Yoga so by setting the node's measure function not to follow the measure modes: + + + + + +```cpp +YGNodeSetMeasureFuncFollowsMeasureModes(node, false); +``` + + + + + +```java +node.setMeasureFunctionFollowsMeasureModes(false); +``` + + + + + +```ts +node.setMeasureFuncFollowsMeasureModes(false); +``` + + + + +Yoga then infers nothing about the node from a measurement under other constraints: + +- It reuses a measurement only under the same constraints. +- For automatic minimum sizing, the measure function isn't called with `AtMost` 0. The node's min-content size is a static min-content size if one is set; otherwise its padding and border plus what its min-content measure function returns, or plus 0 without one. Static min-content sizes and min-content measure functions are available in C/C++ (`YGNodeSetMinContentWidth`, `YGNodeSetMinContentHeight` and `YGNodeSetMinContentMeasureFunc`) and Java (`setMinContentWidth`, `setMinContentHeight` and `setMinContentMeasureFunction`). + +The value is true by default. It has no effect on the layout of a node without a measure function, whose layout Yoga already reuses only under the same constraints. Changing it marks the node dirty. + ## Invalidating measurements Yoga must be notified if the content associated with a node changes in a way which may effect measurement. diff --git a/yoga/YGNode.cpp b/yoga/YGNode.cpp index 7e66845fc1..a8d8e65cd2 100644 --- a/yoga/YGNode.cpp +++ b/yoga/YGNode.cpp @@ -310,6 +310,21 @@ bool YGNodeHasMeasureFunc(YGNodeConstRef node) { return resolveRef(node)->hasMeasureFunc(); } +void YGNodeSetMeasureFuncFollowsMeasureModes( + YGNodeRef nodeRef, + bool measureFuncFollowsMeasureModes) { + const auto node = resolveRef(nodeRef); + if (node->measureFuncFollowsMeasureModes() != + measureFuncFollowsMeasureModes) { + node->setMeasureFuncFollowsMeasureModes(measureFuncFollowsMeasureModes); + node->markDirtyAndPropagate(); + } +} + +bool YGNodeGetMeasureFuncFollowsMeasureModes(YGNodeConstRef node) { + return resolveRef(node)->measureFuncFollowsMeasureModes(); +} + void YGNodeSetMinContentMeasureFunc( YGNodeRef node, YGMinContentMeasureFunc minContentMeasureFunc) { @@ -403,5 +418,6 @@ bool YGNodeCanUseCachedMeasurement( lastComputedHeight, marginRow, marginColumn, - resolveRef(config)); + resolveRef(config), + /*measureFuncFollowsMeasureModes=*/true); } diff --git a/yoga/YGNode.h b/yoga/YGNode.h index 7a9b0e1c3f..1d01996b8e 100644 --- a/yoga/YGNode.h +++ b/yoga/YGNode.h @@ -220,6 +220,36 @@ YG_EXPORT void YGNodeSetMeasureFunc(YGNodeRef node, YGMeasureFunc measureFunc); */ YG_EXPORT bool YGNodeHasMeasureFunc(YGNodeConstRef node); +/** + * Sets whether the node's measure function sizes as `YGMeasureFunc` describes + * for each `YGMeasureMode`: `YGMeasureModeUndefined` as max-content, + * `YGMeasureModeAtMost` as fit-content and `YGMeasureModeExactly` as + * stretch-fit. True by default. + * + * When false, Yoga infers nothing about the node from a measurement under other + * constraints: + * - It reuses a measurement only under the same constraints. + * - For automatic minimum sizing (enabled by clearing + * `YGErrataMinSizeUndefinedInsteadOfAuto`), the measure function isn't + * called with `AtMost 0`. The node's min-content size is the one set by + * `YGNodeSetMinContentWidth` / `YGNodeSetMinContentHeight`, if any; else + * its padding and border plus what its `YGMinContentMeasureFunc` returns, + * or plus 0 without one. + * + * Set it false for a measure function that sizes itself otherwise, for example + * one that fills the space it is given or picks a layout by it. Has no effect + * on the layout of a node without a measure function. Marks the node dirty when + * the value changes. + */ +YG_EXPORT void YGNodeSetMeasureFuncFollowsMeasureModes( + YGNodeRef node, + bool measureFuncFollowsMeasureModes); + +/** + * Whether the node's measure function sizes as the measure modes describe. + */ +YG_EXPORT bool YGNodeGetMeasureFuncFollowsMeasureModes(YGNodeConstRef node); + /** * Optional companion to `YGMeasureFunc` invoked by the CSS Flexbox §4.5 * automatic minimum sizing path when probing this node for its min-content @@ -233,7 +263,9 @@ YG_EXPORT bool YGNodeHasMeasureFunc(YGNodeConstRef node); * * When unset, the algorithm falls back to the regular `YGMeasureFunc` * invoked with the same `AtMost 0` constraint — preserving today's - * behavior. Setting this is a perf opt-in for Primitives whose min-content + * behavior — unless the node's measure function doesn't follow the measure + * modes (`YGNodeSetMeasureFuncFollowsMeasureModes`), whose content then + * contributes 0. Setting this is a perf opt-in for Primitives whose min-content * size is cheap to compute or differs from what the regular measure would * return. */ @@ -271,7 +303,8 @@ YG_EXPORT bool YGNodeHasMinContentMeasureFunc(YGNodeConstRef node); * Precedence inside the probe is: * 1. Static value via `YGNodeSetMinContentWidth/Height` (this API) * 2. Dynamic callback via `YGNodeSetMinContentMeasureFunc` - * 3. Regular `YGMeasureFunc` with `AtMost 0` (today's default) + * 3. Regular `YGMeasureFunc` with `AtMost 0` (today's default), if it + * follows the measure modes; else 0 for the content * 4. Container recursion (sum on main axis, max on cross) * * Static is preferred for known-constant values because it skips the JNI diff --git a/yoga/algorithm/Cache.cpp b/yoga/algorithm/Cache.cpp index 9154fc6ce9..fd7214deef 100644 --- a/yoga/algorithm/Cache.cpp +++ b/yoga/algorithm/Cache.cpp @@ -55,7 +55,8 @@ bool canUseCachedMeasurement( const float lastComputedHeight, const float marginRow, const float marginColumn, - const yoga::Config* const config) { + const yoga::Config* const config, + const bool measureFuncFollowsMeasureModes) { if ((yoga::isDefined(lastComputedHeight) && lastComputedHeight < 0) || ((yoga::isDefined(lastComputedWidth)) && lastComputedWidth < 0)) { return false; @@ -84,6 +85,13 @@ bool canUseCachedMeasurement( const bool hasSameHeightSpec = lastHeightMode == heightMode && yoga::inexactEquals(effectiveLastHeight, effectiveHeight); + // A measure function that doesn't follow the measure modes may size the node + // differently under any other spec, so nothing is inferred from a measurement + // under another: only the same spec reuses it. + if (!measureFuncFollowsMeasureModes) { + return hasSameWidthSpec && hasSameHeightSpec; + } + const bool widthIsCompatible = hasSameWidthSpec || sizeIsExactAndMatchesOldMeasuredSize( diff --git a/yoga/algorithm/Cache.h b/yoga/algorithm/Cache.h index f8857eaf35..1e81becbff 100644 --- a/yoga/algorithm/Cache.h +++ b/yoga/algorithm/Cache.h @@ -25,6 +25,7 @@ bool canUseCachedMeasurement( float lastComputedHeight, float marginRow, float marginColumn, - const yoga::Config* config); + const yoga::Config* config, + bool measureFuncFollowsMeasureModes); } // namespace facebook::yoga diff --git a/yoga/algorithm/CalculateLayout.cpp b/yoga/algorithm/CalculateLayout.cpp index 928b41e785..72e1dfbb0c 100644 --- a/yoga/algorithm/CalculateLayout.cpp +++ b/yoga/algorithm/CalculateLayout.cpp @@ -870,7 +870,10 @@ static float computeFlexBasisForChildren( // * Leaf with measure function: invoke it with `AtMost 0` on the // requested axis and `Undefined` on the other. Text measure-funcs // respond with longest-word width; image/collection-like measures -// respond with 0 along their scroll axis. +// respond with 0 along their scroll axis. A measure function that +// doesn't follow the measure modes (see +// `YGNodeSetMeasureFuncFollowsMeasureModes`) isn't invoked: without a +// static or callback min-content, its content contributes 0. // * Empty leaf: return 0. // * Container: iterate in-flow children. For each, take its // min-content along the container's own main axis (sum into @@ -915,19 +918,26 @@ static float computeMinContentMainSize( // 2. Dynamic min-content callback if set (for Primitives whose // min-content depends on state). Otherwise fall back to the regular // measure function with `AtMost 0`, which text measurers naturally - // answer with longest-word width. - const YGSize size = node->hasMinContentMeasureFunc() - ? node->measureMinContent( - wantRow ? 0.0f : YGUndefined, - wantRow ? MeasureMode::AtMost : MeasureMode::Undefined, - wantRow ? YGUndefined : 0.0f, - wantRow ? MeasureMode::Undefined : MeasureMode::AtMost) - : node->measure( - wantRow ? 0.0f : YGUndefined, - wantRow ? MeasureMode::AtMost : MeasureMode::Undefined, - wantRow ? YGUndefined : 0.0f, - wantRow ? MeasureMode::Undefined : MeasureMode::AtMost); - layout.minContent[axisIndex] = wantRow ? size.width : size.height; + // answer with longest-word width. A measure function that doesn't + // follow the measure modes isn't called: its answer at `AtMost 0` says + // nothing about its min-content, so its content contributes 0. + if (node->hasMinContentMeasureFunc()) { + const YGSize size = node->measureMinContent( + wantRow ? 0.0f : YGUndefined, + wantRow ? MeasureMode::AtMost : MeasureMode::Undefined, + wantRow ? YGUndefined : 0.0f, + wantRow ? MeasureMode::Undefined : MeasureMode::AtMost); + layout.minContent[axisIndex] = wantRow ? size.width : size.height; + } else if (node->measureFuncFollowsMeasureModes()) { + const YGSize size = node->measure( + wantRow ? 0.0f : YGUndefined, + wantRow ? MeasureMode::AtMost : MeasureMode::Undefined, + wantRow ? YGUndefined : 0.0f, + wantRow ? MeasureMode::Undefined : MeasureMode::AtMost); + layout.minContent[axisIndex] = wantRow ? size.width : size.height; + } else { + layout.minContent[axisIndex] = 0.0f; + } layout.minContentGeneration[axisIndex] = generationCount; } // Add the leaf's own padding and border, like the container branch below. @@ -2827,6 +2837,8 @@ bool calculateLayoutInternal( node->style().computeMarginForAxis(FlexDirection::Row, ownerWidth); const float marginAxisColumn = node->style().computeMarginForAxis(FlexDirection::Column, ownerWidth); + const bool measureFuncFollowsMeasureModes = + node->measureFuncFollowsMeasureModes(); // First, try to use the layout cache. if (canUseCachedMeasurement( @@ -2842,7 +2854,8 @@ bool calculateLayoutInternal( layout->cachedLayout.computedHeight, marginAxisRow, marginAxisColumn, - node->getConfig()) && + node->getConfig(), + measureFuncFollowsMeasureModes) && isCachedForOwnerSize( node, layout->cachedLayout, ownerWidth, ownerHeight)) { cachedResults = &layout->cachedLayout; @@ -2862,7 +2875,8 @@ bool calculateLayoutInternal( layout->cachedMeasurements[i].computedHeight, marginAxisRow, marginAxisColumn, - node->getConfig()) && + node->getConfig(), + measureFuncFollowsMeasureModes) && isCachedForOwnerSize( node, layout->cachedMeasurements[i], ownerWidth, ownerHeight)) { cachedResults = &layout->cachedMeasurements[i]; diff --git a/yoga/node/Node.cpp b/yoga/node/Node.cpp index 2cbe841625..2d797397be 100644 --- a/yoga/node/Node.cpp +++ b/yoga/node/Node.cpp @@ -33,6 +33,7 @@ Node::Node(Node&& node) noexcept isReferenceBaseline_(node.isReferenceBaseline_), isDirty_(node.isDirty_), alwaysFormsContainingBlock_(node.alwaysFormsContainingBlock_), + measureFuncFollowsMeasureModes_(node.measureFuncFollowsMeasureModes_), nodeType_(node.nodeType_), context_(node.context_), measureFunc_(node.measureFunc_), diff --git a/yoga/node/Node.h b/yoga/node/Node.h index 72b3d496db..04bcbcab82 100644 --- a/yoga/node/Node.h +++ b/yoga/node/Node.h @@ -67,6 +67,10 @@ class YG_EXPORT Node : public ::YGNode { return measureFunc_ != nullptr; } + bool measureFuncFollowsMeasureModes() const noexcept { + return measureFuncFollowsMeasureModes_; + } + YGSize measure( float availableWidth, MeasureMode widthMode, @@ -238,6 +242,10 @@ class YG_EXPORT Node : public ::YGNode { void setMeasureFunc(YGMeasureFunc measureFunc); + void setMeasureFuncFollowsMeasureModes(bool measureFuncFollowsMeasureModes) { + measureFuncFollowsMeasureModes_ = measureFuncFollowsMeasureModes; + } + void setMinContentMeasureFunc(YGMinContentMeasureFunc minContentMeasureFunc) { minContentMeasureFunc_ = minContentMeasureFunc; } @@ -343,6 +351,7 @@ class YG_EXPORT Node : public ::YGNode { bool isReferenceBaseline_ : 1 = false; bool isDirty_ : 1 = true; bool alwaysFormsContainingBlock_ : 1 = false; + bool measureFuncFollowsMeasureModes_ : 1 = true; NodeType nodeType_ : bitCount() = NodeType::Default; void* context_ = nullptr; YGMeasureFunc measureFunc_ = nullptr;