Measure Functions
When a leaf node's size depends on its content (e.g. text, images, or platform-specific widgets), Taffy cannot calculate the size purely from style properties. In these cases, you must provide a Measure Function.
When to Use
Use computeLayoutWithMeasure() instead of the standard computeLayout() when your tree contains nodes that need custom measurement. Taffy will invoke your callback for leaf nodes that require content-based sizing (e.g. width: auto or measure mode).
How it Works
The measure function is a callback that Taffy invokes during the layout process. It asks you: "Given these constraints, how big is this content?"
Arguments
knownDimensions: Dimensions that are explicitly defined in the node's style (e.g. ifwidth: 100is set,knownDimensions.widthwill be100).availableSpace: The space offered by the parent node. This constraints how large the content can be.
Return Value
The function must return a Size object containing the measured width and height in pixels.
Example
Loading Preview…
Typical Use Cases
- Text Layout: Calculating width/height based on font size, text content, and wrapping width.
- Images: Returning the intrinsic dimensions of an image.
- Native UI Widgets: wrapping platform-specific controls that have their own sizing logic.
Performance Tips
- Cache Results: Measurement can be expensive. Cache the result based on the inputs (
knownDimensions,availableSpace, content string, etc.) to avoid re-calculating identical measures. - Avoid Side Effects: The measure function should be pure. Do not modify the DOM or external state inside it.