Skip to main content

Announcing Yoga 3.1

· 2 min read
Nick Gerleman
Yoga Maintainer

Yoga 3.1 is a new minor version of Yoga, used by React Native 0.75.

Highlights

  1. Percentage support for gap properties
  2. Layout conformance and regression fixes
  3. Additional JavaScript bindings

Percentage support for gap properties

Yoga now supports gap values specified as percentages instead of points.

warning

Percentages in Yoga do not always act consistently with browsers when a definite container size is not provided. This may be improved in a future version of Yoga.

<Layout config={{useWebDefaults: true}}>
  <Node
    style={{
      columnGap: "10%",
      width: 200,
      height: 100,
    }}>
    <Node style={{flexGrow: 1}} />
    <Node style={{flexGrow: 1}} />
    <Node style={{flexGrow: 1}} />
  </Node>
</Layout>

Alignment changes to overflowed containers

Yoga has made several fixes to how flex-children of overflowed containers are aligned when using justify-content, align-content, or margin: "auto". This includes some cases where adding an alignment keyword could cause items to overlap, or padding to be removed.

<Layout config={{useWebDefaults: false}}>
  <Node
    style={{
      width: 100,
      height: 100,
      padding: 10,
      justifyContent: 'space-evenly',
    }}
  >
    <Node style={{height: 100, width: 100}} />
  </Node>
</Layout>

Fixes for regressions in Yoga 3.0

We fixed a couple of regressions added in Yoga 3.0, around percentage insets applied to some absolute containers (#1657), and start/end resolution when physical edge styles are also present (#1658).

Additional JavaScript bindings

We've added JavaScript bindings for setting layout direction to Yoga 3.1, along with JavaScript additions made in patch releases to Yoga 3.0, including bindings for hasNewLayout flag manipulation, and an entrypoint for users who are unable to use top-level await.

Announcing Yoga 3.0

· 9 min read
Nick Gerleman
Yoga Maintainer
Joe Vilches
Yoga Maintainer

Yoga 3.0 is a new major (breaking) version of Yoga, used by React Native 0.74.

Highlights

  1. Support for position: static
  2. Support for align-content: space-evenly
  3. Improvements to layout correctness
  4. Yoga’s JavaScript bindings are now distributed as an ES Module
  5. Fixes several crashes in Java bindings
  6. Some existing Yoga APIs have been removed

position: static

We added full support for the static position type which has existed in an incomplete state for some time now. With this release static is now web-compliant in the context of Flexbox. Some things that were added/changed:

  • The default position type is now relative again and not static. This should not have any effect on layout as the previously introduced YGPositionTypeStatic was not being used within Yoga, so it behaved just like relative.
  • static nodes ignore insets (left, right, top, bottom, etc.)
  • The idea of a containing block was introduced. For absolute nodes this is usually the nearest non-static ancestor. For every other position type this is just the parent since Yoga is a Flexbox implementation.
  • A new public API YGNodeSetAlwaysFormsContainingBlock which takes a boolean indicating if the node should always form a containing block for any descendant. This is useful for properly supporting things like transforms, which will force the node to form a containing block but is outside the scope of Yoga.

position: static affects some concerns outside of layout, like stacking context. The full set of behaviors is enabled in the React Native New Architecture.

Better support for absolute positioning

There were a variety of bugs with how absolute nodes were positioned under various Justify and Align values. Most of these bugs only ever manifested themselves with certain paddings, margins, and borders so the following examples mix those up to illustrate the differences. Additionally, the following positioning examples all share this core style:

parent: {
backgroundColor: 'green',
height: 200,
width: 200,
},
child: {
position: 'absolute',
backgroundColor: 'blue',
height: 50,
width: 50,
},
StyleBeforeAfter
parent: {
// core styles
paddingLeft: 10,
paddingRight: 20,
borderLeftWidth: 10,
borderRightWidth: 20,
alignItems: 'flex-start',
},
child: {
// core styles
paddingLeft: 10,
paddingRight: 20,
marginLeft: 10,
marginRight: 20,
borderLeftWidth: 10,
borderRightWidth: 20,
}

Previous layout

New layout

parent: {
// core styles
paddingTop: 10,
paddingBottom: 20,
borderTopWidth: 10,
borderBottomWidth: 20,
justifyContent: 'center',
},
child: {
// core styles
paddingTop: 10,
paddingBottom: 20,
marginTop: 10,
marginBottom: 20,
borderTopWidth: 10,
borderBottomWidth: 20,
}

Previous layout

New layout

parent: {
// core styles
paddingTop: 10,
paddingBottom: 20,
borderTopWidth: 10,
borderBottomWidth: 20,
justifyContent: 'flex-end',
},
child: {
// core styles
paddingTop: 10,
paddingBottom: 20,
marginTop: 10,
marginBottom: 20,
borderTopWidth: 10,
borderBottomWidth: 20,
}

Previous layout

New layout

There were other fixes not specifically mentioned above. Because this change may result in layout differences for many real-world scenarios, Yoga may be configured to prefer the legacy behavior, by setting the AbsolutePositioningIncorrect erratum. This means this fix is not enabled by default in frameworks like React Native, in order to preserve compatibility.

Additionally, Yoga will now correctly account for padding when calculating the size of absolutely positioned nodes with percentage lengths.

StyleBeforeAfter
parent: {
backgroundColor: 'green',
height: 200,
width: 200,
padding: 50,
},
child: {
position: 'absolute',
backgroundColor: 'blue',
height: '25%',
width: '25%',
},

Previous layout

New layout

Just like with positioning, this fix may result in layout differences in many cases. Setting the AbsolutePercentAgainstInnerSize erratum will preserve the legacy behavior, which is set by default in frameworks like React Native.

Better support for multiline containers

Yoga now offers better support for Flexbox containers which span multiple lines.

Yoga now supports align-content: space-evenly, contributed by @nicoburns, to distribute line boxes with equal space around them.

Align Content Values

https://www.w3.org/TR/css-align-3/#distribution-values

Yoga now correctly supports the combination of align-content and align-items when both cause changes to alignment.

StyleBeforeAfter

<Node
style={{
width: 300,
height: 300,
backgroundColor: 'red',
flexDirection: 'row',
flexWrap: 'wrap',
alignContent: 'space-around',
alignItems: 'flex-end',
}}
>
<Node
style={{
width: 150,
height: 50,
backgroundColor: 'powderblue',
}}
/>
<Node
style={{
width: 120,
height: 100,
backgroundColor: 'skyblue',
}}
/>
<Node
style={{
width: 120,
height: 50,
backgroundColor: 'steelblue',
}}
/>
</Node>

Previous layout

New layout

https://github.com/facebook/yoga/issues/1008

Yoga now correctly supports min-height set on a multiline container.

StyleBeforeAfter
<Node
style={{
flexDirection: 'row',
width: 150,
minHeight: 200,
backgroundColor: 'blue',
flexWrap: 'wrap',
justifyContent: 'center',
padding: 10,
gap: 10,
}}
>
<Node
style={{
backgroundColor: 'red',
height: 100,
width: 100,
}}
/>
<Node
style={{
backgroundColor: 'red',
height: 100,
width: 100,
}}
/>
</Node>

Previous layout

New layout

Correct handling of logical edges in row-reverse containers

Yoga would previously incorrectly reverse start and end edges, when operating on:

  1. The padding, border, or margin of a row-reverse container
  2. The position, of the child of a row-reverse container

In React Native, this also presents as left and right edges being swapped inside of row-reverse containers.

We determined that few enough surfaces are impacted by this bug to enable the correct behavior globally. Existing row-reverse containers which run into these cases may need to be updated to layout correctly in newer versions of Yoga.

StyleBeforeAfter
<Node
style={{
flexDirection: 'row',
backgroundColor: 'red',
margin: 10,
width: 200,
height: 100,
}}
>
<Node
style={{
flexDirection: 'row-reverse',
backgroundColor: 'blue',
flex: 1,
marginStart: 50,
}}
>
<Node
style={{
backgroundColor: 'green',
height: '50%',
flex: 1,
marginStart: 50,
}}
/>
</Node>
</Node>

Previous layout

New layout

Correct main-axis size calculation for indefinite containers using justify-content

Yoga previously calculated an incorrect main-axis size for containers which specified a min-dimension on the main axis, and have a justify-content of space-around or space-between.

StyleBeforeAfter
<Node
style={{
flexDirection: 'row',
backgroundColor: 'red',
height: 75,
minWidth: 200,
gap: 10,
padding: 10,
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<Node
style={{
backgroundColor: 'blue',
width: 50,
height: 50,
}}
/>
<Node
style={{
backgroundColor: 'blue',
width: 50,
height: 50,
}}
/>
</Node>

Previous layout

New layout

This change was observed to impact existing layouts rarely enough to enable globally, and while this change was not present in Yoga 2.0, it was present in the version of Yoga ultimately shipped in React Native 0.73.

Distribution as an ES Module

Yoga’s previous JavaScript package exported a convoluted matrix of different binaries, across asm.js and wasm, sync vs async, and browser vs node.

When it came time to look at adding ES Module support into the mix, we decided to take a forward looking approach, and distribute Yoga as an ES Module, using top-level await, loading WebAssembly. This allows distributing a single binary which presents a sync looking API, even in browsers.

The underlying binary is still distributed as a JavaScript blob of base64 encoded WebAssembly, usable across different environments and bundlers.

Java reliability improvements

Several crashes have been fixed in Yoga’s Java bindings:

  1. Yoga for Java no longer performs an invalid read if a message is logged
  2. Yoga for Java now makes more efficient use of JNI references. This can help avoid app crashes in large trees, or interaction with other layout systems also using JNI.

Infrastructure changes

Yoga’s implementation now targets a well-supported subset of C++ 20. Supported toolchains include:

  1. MSVC 2019+
  2. Clang/libc++ 14+
  3. GCC/libstdc++ 11+
  4. Android NDK 26+
  5. XCode 14.3+

Yoga’s reference Android build and accompanying artifacts now target Android SDK 34.

Yoga now compiles cleanly against higher warning levels, such as -Wextra and -Wconversion in Clang/GCC, and /W4 in MSVC.

Deprecations and removals

Changes to C++ APIs

Yoga’s previous structure made it easy to intermingle Yoga’s public APIs, and Yoga’s C++ implementation structures. The boundary between these two has been made firmer.

  1. Every top-level header is now a public API
  2. All public APIs may be used from C, C++, Objective C, and Swift

We have made some minor changes to this public API, which will require changes for Yoga integrators. The most significant is an increased const-correctness, which may require mechanical changes to measure functions. Yoga’s internal implementation has seen more radical changes.

Removal of UseLegacyStretchBehaviour

APIs related to UseLegacyStretchBehaviour were deprecated as part of Yoga 2.0, and have now been removed. Users of UseLegacyStretchBehaviour should most often set their errata level to All to opt-out of future conformance fixes.

Removal of YogaKit and the YogaLayout ViewGroup

Yoga previously provided direct integrations with UIKit, and the Android View System. These were deprecated as part of Yoga 2.0 and are no longer published as part of Yoga 3.0.

Per-node PointScaleFactor

Yoga would previously only ever read the PointScaleFactor associated with the root node, even if child nodes configured a different value. Yoga now respects the PointScaleFactor associated with a given node. This change may be breaking for code which previously set a scale factor on a config used by the root node, where a different value was provided to child nodes.

Integrating Yoga into your project

Yoga includes a reference CMake build, and has official bindings published across several package managers:

JavaScript

// package.json
{
"dependencies": {
"yoga-layout": "^3.0.0"
}
}

Android

// build.gradle.kts
dependencies {
implementation("com.facebook.yoga:yoga:3.0.0")
}

CocoaPods

# Podfile
pod 'Yoga', '~> 3.0.0'

SwiftPM (new, contributed by @cntrump)

// Package.swift
import PackageDescription

let package = Package(
dependencies: [
.package(url: "https://github.com/facebook/yoga.git", from: "3.0.0")
],
)

Announcing Yoga 2.0

· 6 min read
Nick Gerleman
Yoga Maintainer

We are excited to announce a new major (breaking) version of Yoga. This release contains 198 new commits from 64 contributors, and includes the first significant changes to Yoga in open-source since 2018.

While there has been a long gap in development, the React Native team believes Yoga is a critical tool in delivering the future of React, and we have resumed development of the engine. This release of Yoga is focused on:

  1. Delivering the features we have shipped to React Native to standalone Yoga users
  2. Updating toolchains, packaging, and build systems to make Yoga easier to consume
  3. API changes to allow us to evolve the engine towards conformance

Yoga continuously ships to thousands of surfaces across multiple frameworks at Meta. This version of Yoga corresponds to the version which will be included in React Native 0.73 shipping this fall.

Flexbox gap

The most significant new feature for users on an older stable release of Yoga is the addition of Flexbox gap support. This powers gap, rowGap, and columnGap in React Native 0.71.

// Example.cpp
YGNodeStyleSetGap(node, YGGutterRow, 2.0f);
// Example.java
node.setGap(YogaGutter.ROW, 2.0f);
// Example.ts
node.setGap(Gutter.Row, 2);

Toolchain

Meta uses Buck across its monorepo, but we recognize that Buck has acted as a barrier to be able to use Yoga outside of Meta. Yoga no longer ships build logic for Buck to open-source. We have instead added over 20 new validation jobs to GitHub Actions to continually validate that Yoga builds correctly in common systems and scenarios where Yoga is used in OSS.

New toolchain support includes:

  1. A reference CMake build for Yoga and its unit tests
  2. A modern Gradle build and published AARs
  3. Compatibility with XCode 14.3+
  4. Compatibility with Node 16+
  5. Support for WebAssembly in both Node and browsers
  6. Support for MSVC, higher warning levels, and building without exceptions

Aiming for Conformance

Our team wants to enable engineers to be able to create a single style which renders faithfully across Yoga and web. Conformance is a moving target, with browsers like Chromium regularly making behavior changes to better achieve it. This requires making behavior changes to Yoga which break existing behaviors, for better consistency with the web.

In Yoga 2.0, we’ve generalized UseLegacyStretchBehaviour to a new Errata API, to allow different parts of a Yoga tree to target different conformance levels. This allows rendering part of the tree to be compatible with styles written for web, with other parts compatible with styles written for older versions of Yoga.

Yoga's default behavior going forward is W3C compliance. We recommend users sensitive to the change to set YGErrataClassic, or YGErrataAll if you were already setting UseLegacyStretchBehaviour.

// Example.cpp
YGConfigRef config = YGConfigNew();
YGConfigSetErrata(config, YGErrataClassic);

YGNodeRef node = YGNodeNewWithConfig(config);
// Example.java
YogaConfig config = YogaConfigFactory.create();
config.setErrata(YogaErrata.CLASSIC);

YogaNode node = YogaNodeFactory.create(config);
// Example.ts
const config = Config.create();
config.setErrata(Errata.Classic);

const node = Node.create(config);

Yoga for JavaScript

Yoga’s previous JavaScript bindings are not installable when using Node 12+, making them effectively unusable in today’s JavaScript ecosystem. We now ship a new package with prebuilt binaries and first-class support for TypeScript and modern bundlers.

Two variants are shipped:

  1. An asmjs variant for compatibility
  2. A JS module with embedded WebAssembly (~50% faster)

Both are about 45KB when gzipped.

WebAssembly binaries must be asynchronously compiled and loaded in Chrome. In the absence of universal support for top-level await, we have made the breaking change to require explicitly asynchronously loading Yoga before using it.

import {loadYoga, Align} from 'yoga-layout';

const Yoga = await loadYoga();
const node = Yoga.Node.create();
node.setAlignContent(Align.Center);

The previous behavior of blocking to load the binary can be replicated by importing from the yoga-layout/sync entrypoint, but this is not recommended for new usages, and does not allow using WebAssembly on browsers.

import Yoga, {ALIGN_CENTER} from 'yoga-layout/sync';

const node = Yoga.Node.create();
node.setAlignContent(ALIGN_CENTER);

yoga-layout and yoga-layout/sync try to pick between asmjs and WebAssembly automatically based on the target environment set by your bundler, but you can choose this explicitly as well.

import {loadYoga} from 'yoga-layout/wasm-async';

Note: the yoga-layout package requires your bundler and typechecker to configured to be able to follow the package exports field.

Deprecations and removals

YogaKit and YogaLayout ViewGroup

We are deprecating, YogaKit and the YogaLayout ViewGroup. These libraries allow initegrating Yoga directly with UIKit and the Android view system, but are not widely used by Meta in production. We are instead focusing on higher-level libraries using Yoga like Litho and React Native. Because we aren’t in a place to continue development, or validate contributions, we are discontinuing development. These libraries will not receive future updates beyond the Yoga release-v2.0 branch.

UseLegacyStretchBehaviour

The functions to manipulate UseLegacyStretchBehaviour have been deprecated. Previous users of the API should now set an appropriate errata level, like YGErrataAll to opt-out of all future conformance fixes.

C# bindings

C# bindings were contributed to the Yoga repo but have since degraded. The bindings have not had working build validation, or a consistent contributor. We have removed them from the Yoga repo, but we will continue to provide a public C ABI for others to build bindings on top of.

Private C++ APIs

Yoga’s header structure has historically allowed the inclusion of concrete internal structures like YGStyle or YGNode. We will begin to enforce that users instead rely on the public C APIs provided by #include <yoga/Yoga.h>. Other C++ APIs may change without notice.

// Public API (GOOD)
#include <yoga/Yoga.h>

YGConfigRef config = YGConfigNew();
YGConfigSetPointScaleFactor(config, 1.0f);
// Private API (BAD)
#include <yoga/YGConfig.h>

YGConfig config{yogaLogger_};
config.pointScaleFactor = 1.0f;

C++ 11 Support

Yoga now requires a compiler which supports C++ 14. This will likely be bumped to C++ 17 in a future minor release.

How do I get it?

For users who don’t want to build from source, new Yoga packages have been published to the npmjs registry, Maven Central, and CocoaPods.

// package.json
dependencies: {
"yoga-layout": "^2.0.0"
}
// build.gradle
dependencies {
implementation("com.facebook.yoga:yoga:2.0.0")
}
# Podfile
pod 'Yoga', '~> 2.0.0'

Acknowledgements

Yoga 2.0 contains major external contributions from @intergalacticspacehighway, @jacobp100, @jeetiss and @nicoburns.