layout

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package layout is NSGo's layout engine: a Go reimplementation of the CSS layout algorithms of Taffy 0.15 with the features NSH enables (block, flexbox, grid and content sizes; no floats, no calc(), no balanced flex wrapping).

The caller implements Node over its own tree, then calls Compute on a layout root and, to snap to whole pixels as Taffy does by default, Round. Every node's State then holds its layout. Each root is laid out independently, so separate roots (a list's cells, an overlay) can be computed on their own.

The algorithms follow Taffy's source closely, function by function, so that they produce the same results; the fixture tests in this package run Taffy's own XML test suite to prove it. Comments in the algorithm files keep Taffy's references to the CSS specifications.

All arithmetic is float32, as in Taffy. Opt stands in for Rust's Option<f32>.

Index

Constants

This section is empty.

Variables

View Source
var (
	Auto       = Length{Unit: UnitAuto}
	MinContent = Length{Unit: UnitMinContent}
	MaxContent = Length{Unit: UnitMaxContent}
	FitContent = Length{Unit: UnitFitContent}
	Stretch    = Length{Unit: UnitStretch}
	Content    = Length{Unit: UnitContent}
)

Keyword lengths.

View Source
var (
	MinContentSpace = AvailableSpace{Kind: SpaceMinContent}
	MaxContentSpace = AvailableSpace{Kind: SpaceMaxContent}
)

The sizing constraints.

Functions

func Boundary

func Boundary(n Node, parent *Style) bool

Boundary reports whether nothing inside n can change what its parent's layout takes from it, parent being the style of the node laying it out: n is an in-flow flex item with a size of fixed points both ways, so everything the flex algorithm takes from it follows from that size. Its flex basis is auto, its main size (a percentage basis against a parent of no definite size, or another length under a content-based minimum, would follow its content); it does not shrink (its automatic minimum, its content's, only matters to shrinking); growing takes the free space its parent and siblings leave; it is not aligned by its baseline. And its parent laid it out before. What it gives back that the size does not fix, its overflow, Relayout compares.

An absolutely positioned n is one too when its size is its style's points and its place follows from its insets: its containing block takes nothing else from it, as what it overflows by is clipped or Relayout finds it the same.

func Compute

func Compute(root Node, available Size[AvailableSpace])

Compute lays out the tree under root in the available space, which is usually the viewport, and stores every node's State.Unrounded layout. Nodes whose cache still holds a result for their inputs are not laid out again. Call Round afterwards to snap the layouts to whole pixels.

The root's margin box is placed at the origin of the initial containing block, which has the available size; out-of-flow boxes with no positioned ancestor are positioned against it.

func MeasuresAsBefore

func MeasuresAsBefore(n Node) bool

MeasuresAsBefore reports whether leaf n, whose content changed, gives every input layout asked of it since its cache was last cleared the answer it gave then: every layout above it was computed from those answers alone, so all of them stand and nothing needs laying out again. A leaf never asked (new, or invalidated already) measures as before; one asked too often to tell does not.

func Relayout

func Relayout(n Node) bool

Relayout lays boundary n out again with what its parent's last layout gave it, and reports whether it gave back what its parent takes from it as before: then its parent's layout stands, and its subtree needs only rounding (RoundFrom). Otherwise the caller lays its parent out again.

func Round

func Round(root Node, ratio float32)

Round snaps the Unrounded layouts of the tree under root to device pixels of ratio pixels per point (0 is 1), storing them as State.Rounded. It rounds edges' cumulative positions rather than each size, so that adjacent boxes stay adjacent.

func RoundFrom

func RoundFrom(n Node, origin Point[float32], ratio float32)

RoundFrom snaps the Unrounded layouts of n's subtree to device pixels, as Round does for a whole tree, where origin is the unrounded position of the box n's location is relative to in its layout root.

Types

type AbsoluteAxis

type AbsoluteAxis uint8

AbsoluteAxis is the horizontal or vertical axis.

const (
	Horizontal AbsoluteAxis = iota
	Vertical
)

type AbstractAxis

type AbstractAxis uint8

AbstractAxis is the inline or block axis. Taffy only supports the horizontal-tb writing mode, so the inline axis is always horizontal.

const (
	Inline AbstractAxis = iota
	Block
)

type Align

type Align struct {
	Keyword AlignKeyword
	Safety  AlignmentSafety
}

Align is a value of align-items, justify-items, align-self or justify-self.

type AlignContent

type AlignContent struct {
	Keyword ContentKeyword
	Safety  AlignmentSafety
}

AlignContent is a value of align-content or justify-content.

type AlignKeyword

type AlignKeyword uint8

AlignKeyword is the keyword of an Align.

const (
	// AlignAuto is unset: normal for align-items and justify-items, the
	// parent's items alignment for align-self and justify-self.
	AlignAuto AlignKeyword = iota
	AlignNormal
	AlignStart
	AlignEnd
	AlignFlexStart
	AlignFlexEnd
	AlignSelfStart
	AlignSelfEnd
	AlignCenter
	AlignBaseline
	AlignStretch
)

type AlignmentSafety

type AlignmentSafety uint8

AlignmentSafety is the safe or unsafe overflow-position modifier of an alignment.

const (
	// SafetyDefault is neither safe nor unsafe: the alignment's default
	// overflow behavior.
	SafetyDefault AlignmentSafety = iota
	Unsafe
	Safe
)

type AvailableSpace

type AvailableSpace struct {
	Value float32
	Kind  SpaceKind
}

AvailableSpace is the space a node may lay out in on one axis: a definite size, or the min-content or max-content sizing constraint. The zero value is a definite 0.

func Definite

func Definite(v float32) AvailableSpace

Definite returns definite available space.

type BoxSizing

type BoxSizing uint8

BoxSizing is the CSS box-sizing property.

const (
	BorderBox BoxSizing = iota
	ContentBox
)

type Contain

type Contain uint8

Contain is the CSS contain property, a set of flags.

const (
	ContainLayout Contain = 1 << iota
	ContainPaint
	// ContainContent is layout and paint containment.
	ContainContent = ContainLayout | ContainPaint
)

type ContentKeyword

type ContentKeyword uint8

ContentKeyword is the keyword of an AlignContent.

const (
	ContentNormal ContentKeyword = iota
	ContentStart
	ContentEnd
	ContentFlexStart
	ContentFlexEnd
	ContentCenter
	ContentStretch
	ContentSpaceBetween
	ContentSpaceEvenly
	ContentSpaceAround
)

type Direction

type Direction uint8

Direction is the CSS direction property.

const (
	LTR Direction = iota
	RTL
)

type Display

type Display uint8

Display is the CSS display property.

const (
	DisplayFlex Display = iota
	DisplayBlock
	DisplayFlowRoot
	DisplayGrid
	// DisplayNone hides the node and its subtree: they get zero layouts.
	DisplayNone
)

type FlexDirection

type FlexDirection uint8

FlexDirection is the CSS flex-direction property.

const (
	Row FlexDirection = iota
	Column
	RowReverse
	ColumnReverse
)

type FlexWrap

type FlexWrap uint8

FlexWrap is the CSS flex-wrap property.

const (
	NoWrap FlexWrap = iota
	Wrap
	WrapReverse
)

type GridAutoFlow

type GridAutoFlow uint8

GridAutoFlow is the CSS grid-auto-flow property.

const (
	FlowRow GridAutoFlow = iota
	FlowColumn
	FlowRowDense
	FlowColumnDense
)

type GridPlacement

type GridPlacement struct {
	Kind PlacementKind
	// Line is the line of a PlacementLine: 1-based, negative counting from
	// the end of the explicit grid. For a named line it is the occurrence of
	// the name, negative counting from the end; 0 is a bare name, which
	// first matches a named area's edge and otherwise means 1.
	Line int16
	// Span is the number of tracks or named lines of a PlacementSpan.
	Span uint16
	// Name is the line name of a named line or span, empty otherwise.
	Name string
}

GridPlacement is the start or end of an item's grid-row or grid-column. The zero value is auto.

func GridLine

func GridLine(line int16) GridPlacement

GridLine returns a placement at a numbered line.

func GridSpan

func GridSpan(span uint16) GridPlacement

GridSpan returns a placement spanning tracks.

func ParseGridPlacement

func ParseGridPlacement(s string) (GridPlacement, error)

ParseGridPlacement parses grid-row-start or one of its siblings.

type GridTemplateArea

type GridTemplateArea struct {
	Name                   string
	RowStart, RowEnd       uint16
	ColumnStart, ColumnEnd uint16
}

GridTemplateArea is a named area, from its start lines to its end lines (1-based).

type GridTemplateAreas

type GridTemplateAreas struct {
	Areas []GridTemplateArea
	// Rows and Columns are the number of rows and columns the areas span.
	Rows, Columns uint16
}

GridTemplateAreas is the CSS grid-template-areas property. The zero value is none.

type GridTemplateComponent

type GridTemplateComponent struct {
	Track  TrackSizing
	Repeat *Repetition
}

GridTemplateComponent is one entry of grid-template-rows or grid-template-columns: a single track, or a repeat() when Repeat is set.

func ParseGridTemplate

func ParseGridTemplate(s string) ([]GridTemplateComponent, [][]string, error)

ParseGridTemplate parses grid-template-rows or grid-template-columns into tracks and line names.

type Layout

type Layout struct {
	// Order is the node's paint order among its siblings.
	Order uint32
	// Location is the position of the border box's top-left corner,
	// relative to the parent's border box, or for an out-of-flow box to its
	// containing block's.
	Location Point[float32]
	// Size is the border box size.
	Size Size[float32]
	// ScrollableOverflow is the extent of the content's scrollable overflow,
	// as edge coordinates relative to the padding box's start.
	ScrollableOverflow Rect[float32]
	// ScrollbarSize is the space taken by scrollbars: the width of a
	// vertical one and the height of a horizontal one.
	ScrollbarSize Size[float32]
	Border        Rect[float32]
	Padding       Rect[float32]
	Margin        Rect[float32]
}

Layout is a node's computed layout.

func (*Layout) ContentBoxSize

func (l *Layout) ContentBoxSize() Size[float32]

ContentBoxSize is the size inside the padding and border.

func (*Layout) ScrollHeight

func (l *Layout) ScrollHeight() float32

ScrollHeight is how far the content can scroll vertically.

func (*Layout) ScrollWidth

func (l *Layout) ScrollWidth() float32

ScrollWidth is how far the content can scroll horizontally.

type Length

type Length struct {
	Value float32
	Unit  Unit
}

Length is a CSS length, percentage, auto or sizing keyword: Taffy's Dimension, LengthPercentage, LengthPercentageAuto and track sizing functions in one type. Which units a property accepts follows CSS; layout treats the others as auto.

The zero Length is unset: the initial value of the property holding it, auto for sizes, insets, flex-basis and grid tracks, 0 for margins, padding, borders and gaps.

func FitContentPercent

func FitContentPercent(limit float32) Length

FitContentPercent returns fit-content(<percentage>), the limit given as a fraction.

func FitContentPx

func FitContentPx(limit float32) Length

FitContentPx returns fit-content(<length>).

func Fr

func Fr(v float32) Length

Fr returns a flexible grid track size.

func Percent

func Percent(f float32) Length

Percent returns a percentage given as a fraction: Percent(0.5) is 50%.

func Px

func Px(v float32) Length

Px returns a length in pixels.

func (Length) IsAuto

func (l Length) IsAuto() bool

IsAuto reports whether l is auto or unset.

type Line

type Line[T any] struct {
	Start, End T
}

Line is a start and an end, such as a grid item's start and end lines or a range on one axis.

type Node

type Node interface {
	// Style returns the node's style. Layout only reads it.
	Style() *Style
	// ChildCount returns the number of children, out-of-flow ones included.
	ChildCount() int
	// Child returns the child at index i.
	Child(i int) Node
	// Measure returns the size of a leaf's content box, given the
	// dimensions already known and the space available for the rest. Layout
	// calls it only for nodes without children; a node with no content
	// returns a zero size, or the known dimensions.
	Measure(known Size[Opt], available Size[AvailableSpace]) Size[float32]
	// LayoutState returns the storage layout keeps for the node. It must
	// return the same State every time.
	LayoutState() *State
}

Node is a box layout reads and writes. The caller implements it over its own tree; layout never keeps a Node beyond the call that received it except in the State of its containing block (see State.Hoisted).

type Opt

type Opt struct {
	Value float32
	Valid bool
}

Opt is a float32 that may be absent, Rust's Option<f32>. The zero Opt is absent.

var None Opt

None is the absent Opt.

func Some

func Some(v float32) Opt

Some returns a present Opt.

func (Opt) Or

func (o Opt) Or(d float32) float32

Or returns the value, or d when it is absent.

func (Opt) OrOpt

func (o Opt) OrOpt(d Opt) Opt

OrOpt returns o if it is present and d otherwise.

type Overflow

type Overflow uint8

Overflow is the CSS overflow property on one axis.

const (
	OverflowVisible Overflow = iota
	OverflowClip
	OverflowHidden
	OverflowScroll
)

type PlacementKind

type PlacementKind uint8

PlacementKind is the kind of a GridPlacement.

const (
	PlacementAuto PlacementKind = iota
	PlacementLine
	PlacementSpan
)

type Point

type Point[T any] struct {
	X, Y T
}

Point is a position.

type Position

type Position uint8

Position is the CSS position property.

const (
	PositionStatic Position = iota
	PositionRelative
	PositionAbsolute
	PositionFixed
	PositionSticky
)

type Rect

type Rect[T any] struct {
	Left, Right, Top, Bottom T
}

Rect holds one value per side of a box.

type Repetition

type Repetition struct {
	Count  RepetitionCount
	Tracks []TrackSizing
	// LineNames names the repetition's lines: group i names the line before
	// track i, and the last group the line after the last track.
	LineNames [][]string
}

Repetition is repeat(Count, Tracks…).

type RepetitionCount

type RepetitionCount int32

RepetitionCount is a positive repeat() count, AutoFill or AutoFit.

const (
	AutoFill RepetitionCount = -1
	AutoFit  RepetitionCount = -2
)

type Size

type Size[T any] struct {
	Width, Height T
}

Size is a width and a height.

type SpaceKind

type SpaceKind uint8

SpaceKind is the kind of an AvailableSpace.

const (
	SpaceDefinite SpaceKind = iota
	SpaceMinContent
	SpaceMaxContent
)

type State

type State struct {
	// BeginWork optionally attributes this node's recursive layout work.
	// Its returned function restores the caller's attribution.
	BeginWork func() func()

	// Unrounded is the layout Compute last stored.
	Unrounded Layout
	// Rounded is Unrounded snapped to whole pixels by Round.
	Rounded Layout
	// contains filtered or unexported fields
}

State is what layout keeps for a node: its results, its cache and the out-of-flow boxes it positions. The zero State is ready to use.

func (*State) Hoisted

func (s *State) Hoisted() []Node

Hoisted returns the out-of-flow (absolutely or fixed positioned) boxes for which the node was the containing block in the last layout. Their layouts are relative to this node rather than to their parent.

func (*State) Invalidate

func (s *State) Invalidate() bool

Invalidate drops the node's cached results, as it must be when the node's style, children or content change; its ancestors must be invalidated too. It reports whether there was anything to drop, so that a caller walking up the tree may stop at an ancestor already invalidated.

func (*State) Rounds

func (s *State) Rounds() uint64

Rounds is how many times Round has snapped the children: what walks the rounded tree need not go under a node whose count it saw, but for what is rounded through another containing block.

type Style

type Style struct {
	// Display picks the layout algorithm for the node's children. Zero is flex.
	Display Display
	// ItemIsTable makes an absolutely positioned or block item size as a
	// table: it is never stretched narrower than its content.
	ItemIsTable bool
	// ItemIsReplaced marks a replaced element such as an image.
	ItemIsReplaced bool
	// ItemIsCompressibleReplaced marks a replaced element whose min-content
	// contribution may be compressed, such as a text field.
	ItemIsCompressibleReplaced bool
	// BoxSizing says whether sizes include padding and border. Zero is
	// border-box.
	BoxSizing BoxSizing
	// Direction is the inline direction. Zero is left to right.
	Direction Direction

	// Overflow is the overflow on each axis. Zero is visible.
	Overflow Point[Overflow]
	// ScrollbarWidth is the space reserved for a scrollbar on an axis whose
	// overflow is scroll.
	ScrollbarWidth float32
	// Contain is the CSS contain property. Zero is none.
	Contain Contain

	// Position says how the node is positioned. Zero is static.
	Position Position
	// Inset is top, right, bottom and left. Zero is auto.
	Inset Rect[Length]

	// Size, MinSize and MaxSize are the preferred, minimum and maximum
	// sizes. Zero is auto (none for MaxSize).
	Size, MinSize, MaxSize Size[Length]
	// AspectRatio is width divided by height, when present.
	AspectRatio Opt

	// Margin, Padding and Border are the box's edges. Zero is 0px. Margins
	// may be Auto.
	Margin, Padding, Border Rect[Length]

	// AlignItems and JustifyItems are the default self-alignment of
	// children. Zero is normal.
	AlignItems, JustifyItems Align
	// AlignSelf and JustifySelf override the parent's AlignItems and
	// JustifyItems. Zero is auto: use the parent's.
	AlignSelf, JustifySelf Align
	// AlignContent and JustifyContent distribute lines, tracks or items.
	// Zero is normal.
	AlignContent, JustifyContent AlignContent
	// Gap is the column gap (Width) and the row gap (Height). Zero is 0px.
	Gap Size[Length]

	// TextAlign is the legacy -webkit-left/right/center alignment of block
	// children. Zero is auto.
	TextAlign TextAlign

	// FlexDirection is the main axis of a flex container. Zero is row.
	FlexDirection FlexDirection
	// FlexWrap says whether flex items wrap. Zero is nowrap.
	FlexWrap FlexWrap
	// FlexBasis is the flex item's initial main size. Zero is auto.
	FlexBasis Length
	// FlexGrow is the flex grow factor. Zero is 0.
	FlexGrow float32
	// FlexShrink is the flex shrink factor. Absent is CSS's initial 1.
	FlexShrink Opt

	// GridTemplateRows and GridTemplateColumns are the explicit grid's
	// tracks.
	GridTemplateRows, GridTemplateColumns []GridTemplateComponent
	// GridTemplateRowNames and GridTemplateColumnNames name the explicit
	// grid's lines: group i names line i, repetitions counting as one track.
	GridTemplateRowNames, GridTemplateColumnNames [][]string
	// GridTemplateAreas names areas of the explicit grid.
	GridTemplateAreas GridTemplateAreas
	// GridAutoRows and GridAutoColumns size implicit tracks. Empty is auto.
	GridAutoRows, GridAutoColumns []TrackSizing
	// GridAutoFlow places auto-placed grid items. Zero is row.
	GridAutoFlow GridAutoFlow
	// GridRow and GridColumn place the node in its parent grid. Zero is auto.
	GridRow, GridColumn Line[GridPlacement]
}

Style is a node's layout style, Taffy's Style. Every field's zero value is unset, which means the property's initial value: CSS's where Taffy follows CSS, Taffy's otherwise (display flex, border-box sizing). NSGo's core sets React Native's defaults itself when it maps its own styles onto this one.

func (*Style) Equal

func (s *Style) Equal(o *Style) bool

Equal reports whether s and o are the same style, an empty list the same as none. It compares field by field: reflect.DeepEqual, which the core's restyle used, took a tenth of the web page's time in a fast scroll of a table's cells. TestStyleEqualSeesEveryField keeps it to every field.

type TextAlign

type TextAlign uint8

TextAlign is the legacy text-align values that align block children.

const (
	TextAlignAuto TextAlign = iota
	TextAlignLegacyLeft
	TextAlignLegacyRight
	TextAlignLegacyCenter
)

type TrackSizing

type TrackSizing struct {
	// Min is a fixed length or percentage, auto, min-content or max-content.
	Min Length
	// Max is any of Min's values, fr or fit-content(<length-percentage>).
	Max Length
}

TrackSizing is a grid track's sizing function, minmax(Min, Max). A single size such as 1fr or 40px is written as both: Track(Fr(1)).

func MinMax

func MinMax(min, max Length) TrackSizing

MinMax returns minmax(min, max).

func ParseGridAutoTracks

func ParseGridAutoTracks(s string) ([]TrackSizing, error)

ParseGridAutoTracks parses grid-auto-rows or grid-auto-columns.

func Track

func Track(size Length) TrackSizing

Track returns the track sizing function for a single CSS track size, as CSS parses one: the minimum of 1fr or fit-content(…) is auto.

type Unit

type Unit uint8

Unit says how to read a Length's Value.

const (
	// UnitUnset is the zero Unit: the property's initial value.
	UnitUnset Unit = iota
	UnitAuto
	// UnitPx is a length in pixels (points).
	UnitPx
	// UnitPercent is a percentage of the containing block's size, as a
	// fraction: 0.5 is 50%.
	UnitPercent
	// UnitFr is a fraction of a grid's free space.
	UnitFr
	UnitMinContent
	UnitMaxContent
	// UnitFitContent is the fit-content keyword.
	UnitFitContent
	// UnitFitContentPx is fit-content(<length>), Value being the limit.
	UnitFitContentPx
	// UnitFitContentPercent is fit-content(<percentage>), Value being the
	// limit as a fraction.
	UnitFitContentPercent
	UnitStretch
	// UnitContent is flex-basis's content keyword.
	UnitContent
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL