Skip to content

Layout

Layout is constraints-based and compositional. Public UI code builds typed components such as Row, Column, Text, and Rect, then converts them into the erased Element type at runtime/component boundaries. Internally, each Element wraps a crate-private node tree made of containers, leaves, and modifier nodes.

A plain empty component has no intrinsic size. Size, padding, alignment, offsets, visuals, and scroll behavior are added by wrapping the component in modifiers.

Modifiers are chainable and wrap the current element.

lurq::components::Rect::new(80.0, 40.0)
.padding(12.0)
.background("#3b82f6")
.rounded(8.0)

Common modifiers:

ModifierPurpose
.size(width, height)Force width and height
.width(width)Force width
.height(height)Force height
.min_size(width, height) / .max_size(width, height)Set minimum or maximum width and height
.min_width(width) / .max_width(width)Set a width bound
.min_height(height) / .max_height(height)Set a height bound
.aspect_ratio(ratio)Give the axis that is auto from the one that is known, by width over height
.padding(...) / .padding_horizontal(...) / .padding_vertical(...)Add insets around the child from a concrete dimension or SpacingSize
.background(color)Fill the element background from a concrete color or PaletteColor
.rounded(radius)Set border radius from f32 or RadiusSize
.border_inside(width, color)Draw an inside border from a concrete width or BorderSize
.offset(x, y)Shift visually without changing parent layout
.relative(x, y)Alias for .offset(x, y)
.offset_by_size(x, y)Shift by shares of the element’s own width and height, once it is laid out, on top of .offset: (-0.5, -0.5) puts its middle where its top left corner was
.absolute(x, y, width, height)Absolute stack positioning with forced size
.absolute_position(x, y)Absolute stack positioning with measured size
.transform(Transform2D)Apply a visual 2D transform around the element center
.align(Alignment)Override alignment within parent container
.flex(factor)Participate in row/column flex distribution
.flex_shrink(factor)Give up main-axis space when a row/column overflows
.shrink_order(order) / .shrink_limit(ShrinkLimit)When and how far a shrinking child gives way
.shrink_drop_below(size)Shrink a child down to size, then drop it
.drop_marker(bool)Lay a child out only while another child of its line is dropped
.drop_outside(SizeBounds)Lay a child of a stack out only while the stack is within a range of sizes

Sizing modifiers accept Dimension values. Passing a plain f32 is shorthand for Dimension::Px(value). Min/max sizing clamps a child’s measured size without forcing both bounds. Padding accepts f32, Dimension, or SpacingSize.

use lurq::node::dimension::Dimension;
lurq::components::Spacer::new().width(120.0)
lurq::components::Spacer::new().width(Dimension::Pct(50.0))
lurq::components::Spacer::new().width(Dimension::Auto)
lurq::components::Spacer::new().min_width(160.0).max_height(240.0)
lurq::components::Spacer::new().min_size(120.0, 80.0).max_size(320.0, 180.0)

.aspect_ratio(ratio) is CSS aspect-ratio: the box’s width over its height, 16.0 / 9.0 for a box of 16 by 9. It gives the axis that is auto from the one that is known.

use lurq::{components::Spacer, node::dimension::Dimension};
// 320 wide, so 180 high.
Spacer::new().width(320.0).aspect_ratio(16.0 / 9.0)
// As wide as the column it is in, and square.
Spacer::new().width(Dimension::Pct(100.0)).aspect_ratio(1.0)
  • An axis is known where it is said (.width(...), .height(...), a percentage of a parent whose size is known) or where the parent fixes it: a child that fills a row with .flex(1.0), a child stretched across a line.
  • With neither axis known, the box is as wide as the room it is given and its height follows. Where the width has no bound (in a row that scrolls sideways) it is as high as the room and its width follows.
  • With both axes known it does nothing. min_* and max_* still bound the axis it gives.
  • A ratio that is not a positive number is ignored.

An image has a ratio of its own, that of its pixels, which gives it the other axis when one is said. .aspect_ratio stands for that ratio: the box takes the ratio it is told, and the image’s fit places the pixels in it. It is also what holds the box of an image whose pixels are not there yet. An image decoded at runtime or loaded from a resource has no size until it arrives, so a page that does not say one moves when it does, as a page does around an <img> with no size. Say the ratio and the box is right from the first frame:

use lurq::{components::Image, node::dimension::Dimension};
Image::from_file("photos/lake.jpg")
.width(Dimension::Pct(100.0))
.aspect_ratio(3.0 / 2.0)

Layout follows the same high-level model as Flutter:

  1. Parent passes Constraints down to each child.
  2. Child picks a concrete Size within those constraints.
  3. Parent positions each child with an offset.
pub struct Constraints {
pub min_width: f32,
pub max_width: f32,
pub min_height: f32,
pub max_height: f32,
}

Constraint kinds:

  • Tight: min == max; forces an exact size.
  • Loose: min == 0; child can choose any size up to max.
  • Unbounded: max == f32::INFINITY; used by scroll containers on the scroll axis.

Application code normally does not call layout directly. Runtime computes layout when rendering, dispatching input, or looking up elements.

lurq::components::Column::new() arranges children top-to-bottom.

lurq::components::Column::new()
.spacing(8.0)
.align_items(Alignment::Center)
.child(lurq::components::Text::new("A"))
.child(lurq::components::Text::new("B"))

Column layout:

  1. Lays out non-flex children with loosened vertical constraints.
  2. Sums child heights plus spacing.
  3. Uses the max child width.
  4. Positions children vertically and applies cross-axis alignment.
  5. Distributes remaining height to flex children when present.

.spacing(...) accepts either a plain pixel value or a SpacingSize from the active theme.

lurq::components::Row::new() arranges children left-to-right.

lurq::components::Row::new()
.spacing(8.0)
.align_items(Alignment::Center)
.child(lurq::components::Text::new("A"))
.child(lurq::components::Text::new("B"))

Row layout is the horizontal equivalent of column layout.

.spacing(...) accepts either a plain pixel value or a SpacingSize from the active theme.

lurq::components::Stack::new() overlays children. Later children paint on top of earlier children.

lurq::components::Stack::new()
.stack_align(StackAlignment::Center)
.child(lurq::components::Rect::new(200.0, 120.0))
.child(lurq::components::Rect::new(40.0, 40.0).background("#ef4444"))

Stack layout:

  1. Lays out all children with the same constraints.
  2. Sizes itself to the max width/height of non-absolute children.
  3. Positions normal children using stack alignment or per-child .align(...).
  4. Positions absolute children at their explicit (x, y) offset.

Absolute children do not contribute to stack size.

.drop_outside(SizeBounds) lays a child of a stack out only while the stack is within a range of sizes. Outside it the child is dropped, as ShrinkLimit::Drop drops a child of a line: laid out at zero size, neither drawn nor hit, with no Tab stop in it and no focus kept in it, while it stays mounted and keeps its state. It is how a component is another thing at another size with nothing measured, no state and no frame in between: each form is a child of the stack with the bounds it lives in, and layout shows the one that holds.

use lurq::{
components::{Rect, Stack},
layout::layout_kind::SizeBounds,
node::dimension::Dimension,
};
// A picture that fills its room, with a bar from 240 wide and a single button under that.
Stack::new()
.width(Dimension::Pct(100.0))
.child(picture)
.child(bar.drop_outside(SizeBounds::new().min_width(240.0)))
.child(more_button.drop_outside(SizeBounds::new().below_width(240.0)))
  • min_width(w) is at w and wider, above_width(w) wider than w; max_width(w) is at w and narrower, below_width(w) narrower than w; the same four for the height. Bounds with nothing said hold at every size, and bounds of two children that leave no size out and share none show exactly one of them.
  • The size asked is the stack’s own, as its constraints and its other children make it. A child with bounds never makes its stack larger: it is laid out once the stack has its size, within that size, and a share it takes (Dimension::Pct) is a share of that size. In a stack that holds only such children the size is the least the stack’s constraints allow, which is the size the stack is given where it is told one.
  • So a stack sized by its content asks the bounds of that content, not of the room it was offered: a picture 200 wide in a column of 400 is asked at 200. This is what CSS container queries get from size containment, and why a child with bounds cannot change the answer it is given.
  • It is decided in the same layout pass as everything else, and again whenever the stack is laid out: a stack that becomes narrower drops what does not live there in the frame that makes it narrower.
  • On a child of a row, a column or a grid it does nothing.

ui::Picture chooses what it shows at a small size this way where its size is not said.

A size in percent of an absolute child (Dimension::Pct) is a share of what the stack is laid out in. Where that leaves a side unbounded (a stack as high as its content, in a column that scrolls), it is a share of the stack as its other children make it, as CSS sizes an absolutely positioned box by its container: a layer over what a stack holds, .absolute(0.0, 0.0, Dimension::Pct(100.0), Dimension::Pct(100.0)), is as large as that.

Grid lays its children out in the cells of columns and rows, as CSS grid does.

use lurq::{
components::{Grid, Text, TextInput},
layout::grid::GridTrack,
};
// A form: labels as wide as the widest, fields in the room that is left, notes across both.
Grid::new()
.columns([GridTrack::Auto, GridTrack::Fr(1.0)])
.gap(8.0)
.child(Text::new("Name"))
.child(TextInput::new(name))
.child(Text::new("Email"))
.child(TextInput::new(email))
.child(Text::new("Both are kept on this device.").column_span(2))

A track, a column or a row, is a GridTrack:

TrackSize
GridTrack::Px(120.0), or a plain 120.0A length in logical pixels.
GridTrack::Fr(1.0)A share of the room the other tracks and the gaps leave; Fr(1.0) and Fr(2.0) split it one to two.
GridTrack::AutoAs large as the largest item in it.
  • .columns([...]) and .rows([...]) name the tracks. Grid::with_columns(3) is three equal columns. Rows past the last one named are added as the items need them, as tall as their content; an item placed past the last column adds columns the same way.
  • .gap(v) is the gap between columns and between rows, .column_gap(v) and .row_gap(v) one of them: logical pixels or a SpacingSize role. There is no gap around the tracks; use .padding(...).
  • Children take the cells in their order, row after row, each in the next cell that has room for it. .column_span(n) and .row_span(n) make a child take several; .grid_column(i) and .grid_row(i) name where it starts, counted from 0. A child that names both is put there whatever is there already.
  • A child is stretched to its cell: .align_items(Alignment::...) says how it sits from top to bottom otherwise, and .justify_items(...) from side to side. A child with a size of its own keeps it, at the start of its cell when it is stretched.
  • In room of a known width a grid with Fr columns fills it. In unbounded room, as a child of a Row that does not flex, it is as wide as its columns, and an Fr column is as wide as its content needs, in proportion with the other Fr columns.
  • Fr rows share the height of a grid that is given one (.height(...), or stretched by its parent). In a grid as tall as its content they are as tall as theirs, in proportion.
  • Auto columns that do not fit the width give way in proportion, and their text wraps.
  • An absolutely positioned child takes no cell and is placed over the grid, as in a Stack.

A table’s header and each of its rows are elements of their own, each pressed, hovered and selected as one, and their cells line up in columns whatever is in them. ColumnTracks is the list of columns they share: a row given it with .column_tracks(&tracks) lays its children out side by side, one to a track, each as wide as its track; what holds the rows, given it with .measures_column_tracks(&tracks), measures the cells of the rows in it.

use lurq::{
components::{Column, Row, Text},
layout::column_tracks::{ColumnTracks, TrackSpec},
};
// Kept from render to render, in a component's field: another list is other columns.
let tracks = ColumnTracks::new([TrackSpec::share(1.0).min(120.0), TrackSpec::content(), TrackSpec::px(80.0)]);
let row = |name: &str, kind: &str, size: &str| {
Row::new()
.spacing(16.0)
.column_tracks(&tracks)
.child(Text::new(name))
.child(Text::new(kind))
.child(Text::new(size))
};
Column::new()
.measures_column_tracks(&tracks)
.child(row("Name", "Kind", "Size"))
.child(row("blur.rs", "Rust", "12 KB"))
TrackWidth
TrackSpec::px(120.0)A length in logical pixels.
TrackSpec::share(1.0)A share of the room the other tracks and the gaps leave, as a grid’s Fr. Where the room is not known (a row as wide as its content, what scrolls sideways before it is stretched), at its least: what is in it does not widen it.
TrackSpec::content()As wide as the widest of its cells that has been measured.
  • .min(px) and .max(px) hold a track between a least and a most. The shares split what is left between theirs; where the tracks do not fit, none gives way below its least, and the row is wider than its room.
  • The row’s .spacing(..) is the gap between two tracks. A cell is laid out as wide as its track, and the row is as tall as its tallest cell; .align_items(..) says how the others sit in it.
  • What measures the tracks measures the rows that are its children and the rows in those, three deep, before it lays them out, and a track keeps the widest cell it has had, so a column does not narrow as rows scroll by. Only rows that are built are measured: in a list of thousands that builds those in view, a column is as wide as what has been seen.
  • .track_span(n) on a child of a row makes it take n tracks, as wide as they are with the gaps between them, and what comes after it starts in the track after them. A table whose columns are out of view stands one such room for them in place of a cell each; a room is not measured.
  • A list is a handle: clones are the same list, and two lists are equal only where they are the same. A row whose list is another than before is laid out again, so columns that change are a new list.
lurq::components::Rect::new(50.0, 50.0).relative(10.0, 20.0)

Relative positioning is an offset. It moves the child visually but the parent still reserves space as if the offset were zero. Siblings are not moved by the offset.

Absolute positioning is intentionally scoped to Stack.

lurq::components::Stack::new()
.child(lurq::components::Rect::new(300.0, 120.0).background("#f8fafc"))
.child(
lurq::components::Rect::new(80.0, 32.0)
.background("#f97316")
.absolute(190.0, 24.0, 80.0, 32.0),
)

Use:

  • .absolute(x, y, width, height) when the positioned child should have a forced size.
  • .absolute_position(x, y) when the positioned child should keep its measured size.

There is no z-index. Rendering order is structural: later stack children paint above earlier children.

.repeat(Repeat) paints what an element holds again and again across the element’s box: a watermark, a pattern.

use lurq::{components::{Rect, Stack}, layout::Repeat};
Stack::new()
.size(lurq::node::dimension::Dimension::Pct(100.0), lurq::node::dimension::Dimension::Pct(100.0))
.repeat(Repeat::new().gap(27.0, 29.0).stagger(40.0))
.child(Rect::new(20.0, 20.0).background("#e4e4e7"));

What the element holds is laid out once, where it is, and is the first tile. The tiles are the first child’s box with the gap after it, across and down both ways from the first, every other row moved by the stagger, and they are cut to the element’s box where it clips. Only the tiles that can be seen are painted: in a scroll, those in its view, so a pattern over a page of any length costs the tiles in view and scrolling builds nothing. The copies are paint alone: no pointer hits them and tooling does not read them, and what the element holds is in the tree once. A child that fades fades in every tile. A tile that holds what cannot be painted twice (a text input) is painted once, where it is. ui::Watermark is built on it.

lurq::components::Column::new()
.align_items(Alignment::Center)
.child(lurq::components::Text::new("centered"))
pub enum Alignment {
Start,
Center,
End,
Stretch,
}
lurq::components::Column::new()
.align_items(Alignment::Start)
.child(lurq::components::Text::new("left"))
.child(lurq::components::Text::new("right").align(Alignment::End))
lurq::components::Stack::new()
.stack_align(StackAlignment::BottomEnd)
.child(lurq::components::Rect::new(40.0, 40.0))
pub enum StackAlignment {
TopStart,
TopCenter,
TopEnd,
CenterStart,
Center,
CenterEnd,
BottomStart,
BottomCenter,
BottomEnd,
}

Children inside Row or Column can consume remaining space with .flex(factor).

lurq::components::Row::new()
.child(lurq::components::Rect::new(100.0, 50.0))
.child(lurq::components::Spacer::new().flex(1.0))
.child(lurq::components::Rect::new(100.0, 50.0))

Flex layout:

  1. Lay out non-flex children first.
  2. Subtract fixed child sizes, spacing and flex bases from available space.
  3. Divide remaining space by flex factor, on top of each basis.
  4. Lay out flex children with tight constraints for their assigned size.

.flex_full(grow, shrink, basis) gives a child a basis: the length it starts from, as flex-basis does on the web. The bases come out of the free room first, so a growing child is its basis and its share of what is left after the gaps, the children sized on their own and every basis. Where nothing is left, a child is its basis, and the line shrinks what may shrink by the shortage.

// 200 wide: the first is 50 + (200 - 50 - 50) = 150, the second 50.
lurq::components::Row::new()
.width(200.0)
.child(lurq::components::Spacer::new().flex_full(1.0, 0.0, Some(50.0)))
.child(lurq::components::Spacer::new().width(50.0))

A basis is a least length for a child that grows and does not shrink: the line between two steps, which the steps give way before.

In an unbounded main axis (for example a column inside ScrollVertical, or a column measured by its own content) there is no remaining space: a flex child gets its basis, or its natural size when it has none. A line of unbounded room that is to be at least so long, as the content of a ScrollBoth::fill_width is, has the room that least length leaves: where every growing child has a basis, they grow into it, as a flex container with a min-width does on the web, and nothing shrinks, so the line is longer where the bases need more. ui::WindowTabs shares a strip’s width among its tabs so, and scrolls past their least.

.flex_shrink(factor) (or .flex_full(grow, shrink, basis)) lets a child give up main-axis space when the children overflow the row or column. The overflow is split by shrink factor, never below a child’s min_width/min_height. Each shrunk child is then laid out again with its shrunk size as a tight constraint, so its content matches the box it got: a shrunk scroll container reports the shrunk viewport and scrolls to its last row, and a shrunk column distributes its own flex children inside the smaller height.

lurq::components::Column::new()
.height(300.0)
.child(header)
.child(lurq::components::ScrollVertical::new(rows).flex_shrink(1.0))
.child(footer)

The scroll area takes its content height while that fits, and the space between header and footer otherwise.

By default every shrinking child gives way at once. .shrink_order(order) makes them give way in turn: the children with the lowest order absorb the overflow, down to their limit, before any child of the next order shrinks at all. Children of one order share their part by shrink factor, as above. The order is an i32 and defaults to 0, so a child without one gives way before children with a positive order. Both modifiers apply only to a child with a flex_shrink factor in a single-line Row or Column.

.shrink_limit(ShrinkLimit) sets how far a child gives way:

ShrinkLimitThe child shrinks
MinSizeDown to its min_width/min_height, 0 without one (the default)
ContentDown to its content minimum, never below an explicit min_width/min_height
DropNot at all: it keeps its natural size, or is dropped (zero size, no spacing, not drawn and not hit)
ContentFirstDown to its content minimum while its order can take the overflow, then below it to its min_width, the last first

The content minimum of a Row in a row (or a Column in a column) is its padding and spacing, the natural size of every child that does not shrink, and the limit of every child that does (a droppable child counts as gone). The content minimum of a line on the other axis (a Column in a row) is the widest of its children’s, where a child with a min_width/min_height of its own counts at it: a text that may wrap says min_width(0.0). Anything else (text, rects, stacks, scroll containers, wrapping rows) keeps its natural size, like a flex item with CSS min-width: auto.

ContentFirst is for what has a part to keep and a part to give: a step whose description wraps before its title is cut. The children of an order keep to their content minimum while they can take the overflow above it; when they cannot, the last of them gives way below it, then the one before, each down to its min_width. A child that gives way lays its own line out as collapsed, so what in it has ContentFirst gives way below its content too.

use lurq::{components::{Column, Spacer}, layout::layout_kind::ShrinkLimit};
// A title of 60 that keeps its width over a description that may wrap to nothing.
Column::new()
.flex_shrink(1.0)
.shrink_limit(ShrinkLimit::ContentFirst)
.min_width(0.0)
.child(Spacer::new().size(60.0, 16.0))
.child(Spacer::new().size(150.0, 32.0).min_width(0.0));
``` Within one order, droppable children are dropped, last first, only while the
shrinking children of that order cannot absorb the rest of the overflow. This holds for the line that gives way, not
inside a shrinking item of it: an item whose row holds droppable children drops them all at once when it collapses
(see below). A dropped child stays mounted and keeps its
state, and it comes back once the line has room for it. While it is dropped, nothing inside it is a Tab stop or takes
focus (`focus()` and `ctx.focus` requests for it are refused, keys never activate it), focus inside it moves off (the
focused node is blurred), and the element refs and bounds of everything inside it report a
zero-size rect at its place in the line, where the next child starts. Devtools and the MCP tree mark it `dropped`.
What gives way whole only accumulates as a line narrows: a child dropped at one width is dropped at every narrower
one. A dropped child frees its whole size and spacing, which can be more than the line needed; the rest goes back to
children that only trimmed (labels, spacers), never to a child that dropped, so the line stays filled without bringing
anything back. Where the line has a growing child (a spacer between two groups), what a drop freed beyond the need is that child's, as free room is: the group after the spacer stays at the end of the line. The same holds one line down. A shrinking item whose own row holds droppable children (a `Drop` or
`shrink_drop_below` child, or such an item nested in it) keeps its natural size until its line needs it to give way.
It then collapses, after the children of its order that drop, as a whole step like a drop: its row drops every one of
them (and collapses every such item in it) at once, so it holds its padding, its other children at their natural size
and the spacing between them, and from there it shrinks on toward its floor like any other child, never growing back.
The line decides this and the item's own layout follows it, so the two cannot disagree. Inside such an item, children
therefore give way only once it collapses: a trimming child does not trim while a droppable child beside it stays,
whatever their orders. To let a label trim before a time drops, make them separate children of the line that gives
way, the time in a later order than the label. An ellipsizing text with `Drop` and a shrink factor is
measured at its full width, so it drops rather than ellipsizes.
`.shrink_drop_below(size)` combines both: the child first shrinks like its limit, but no further than `size`, and when
its order still cannot absorb the overflow with every shrinking child at its floor, it drops (as with `Drop`) before
the next order shrinks at all. A child already narrower than `size` drops without shrinking; a negative or NaN `size`
counts as 0. Within one order, children with `Drop` are dropped first, then those with `shrink_drop_below`, each last
first, and either kind counts as gone in an ancestor's content minimum. With `ShrinkLimit::Drop` the size has no
effect. What a dropped child leaves beyond the overflow goes to the line's growing children, by their factors: a
`Spacer` with `flex(1.0)` before a button keeps the button at the end of the line as children before it drop.
```rust
// The request words trim to 100 px, then drop so the count stays whole.
Row::new()
.child(label("Designer asks to use pencil").flex_shrink(1.0).shrink_order(1).shrink_drop_below(100.0))
.child(label("1 approval waiting").flex_shrink(1.0).shrink_order(2))

A line that uses orders or limits also shares in whole pixels: within one order every child loses a whole number of pixels except the one with the largest shrink factor, which takes the fraction. A sliver of overflow therefore truncates one label instead of putting a stray ellipsis on several, and as the line narrows each child gives up a pixel at a time. If that child reaches its floor, the fraction it cannot take goes to a child that already loses a pixel or more, and only when there is none to one that loses nothing. A line without orders or limits shares exactly by factor.

Use orders, not factors, to say which child gives way first: shares are computed in f32, so keep the factors within one order of similar magnitude (a factor thousands of times smaller than its neighbours’ is lost in their sum).

use lurq::{
components::{Rect, Row, Text, TextOverflow},
layout::layout_kind::ShrinkLimit,
};
let label = |text: &str| Text::new(text).nowrap().text_overflow(TextOverflow::Elipsis);
// Icon and count stay whole; the detail inside the item gives way first.
let approvals = Row::new()
.child(Rect::new(14.0, 14.0))
.child(label("1 approval waiting"))
.child(label("Designer asks to use pencil").flex_shrink(1.0))
.flex_shrink(1.0)
.shrink_order(2)
.shrink_limit(ShrinkLimit::Content);
Row::new()
.spacing(8.0)
.child(label("15:32").flex_shrink(1.0).shrink_order(1).shrink_limit(ShrinkLimit::Drop))
.child(approvals)
.child(label("Run 3").flex_shrink(1.0).shrink_order(3))

As the row narrows, the time is dropped first, then the approval detail is ellipsized down to the icon and count, and only then does the run label shrink.

A row whose children drop where it is too narrow often needs one more child that stands for them: a More button at the end of a toolbar that opens a menu of what went. .drop_marker(true) makes a child of a single-line Row or Column that one: it takes its room only while another child of the line is dropped, and is dropped itself (zero size, no spacing, not drawn, not hit, no Tab stop) while none is. The line gives way as it would without the marker, and only when that drops or collapses a child does it give way again with the marker’s room taken, so what fits beside the marker stays and the rest drops. The marker itself does not shrink, and a line has one. In a wrapping row it has no effect.

The row says what it dropped through the element refs of its children: a dropped child, and everything in it, reports a zero-size rect where the next child starts, and ElementRef::observe_rect is called when that changes. A component that keeps a menu of the dropped children puts a ref on each and sets a signal from the observer, which renders it again with the menu as the layout left it; the row itself needs no second pass.

use lurq::{
components::{Button, Row},
core::{ElementRef, Signal},
layout::layout_kind::ShrinkLimit,
};
// In a component: `tools` holds a ref for each tool, `dropped` is `ctx.signal(vec![false; tools.len()])`.
let mut bar = Row::new().spacing(2.0);
for (index, name) in ["Bold", "Italic", "Link", "Image"].into_iter().enumerate() {
let (at, dropped) = (tools[index].clone(), dropped.clone());
at.observe_rect(move |rect| {
let gone = rect.width == 0.0 && rect.height == 0.0;
if dropped.get_untracked()[index] != gone {
dropped.update(|dropped| dropped[index] = gone);
}
});
bar = bar.child(
Button::new(name)
.tab_index(0)
.ref_element(at)
.flex_shrink(1.0)
.shrink_limit(ShrinkLimit::Drop),
);
}
// Laid out only while a tool is dropped; its menu lists the tools `dropped` marks.
bar.child(Button::new("More").tab_index(0).drop_marker(true))

A form that only shows or hides parts by the size of its own box needs nothing of what follows: put the parts in a stack and give each .drop_outside(...) (see Stack). What follows is for a form that has to be built differently, which only a render can do.

A component whose form depends on the room it is given, not on the window (a timeline whose two sides fold to one in a narrow panel), reads its width through an element ref. ElementRef::observe_rect calls its observer after layout, and a signal written there renders the component again in the next frame: the frame in between shows the old form. ElementRef::observe_rect_before_paint calls it at the same point, but what it changes is rendered and laid out again before that frame is painted: the component shows the form that fits from its first frame, and as a splitter’s divider drags its pane across the width, with no frame of the other.

The observer writes only where the rect crosses what it watches for, so a pane dragged within one side of the width renders nothing again. The element it is on takes the room it is given (width(Dimension::Pct(100.0))), not its content’s width, which the form would change.

What the observer gives an element through its ref is laid out before the frame is painted too: a size (ElementRefMut::set_size) renders nothing, and the frame that measured the room shows the element at it. ui::Splitter keeps its panes between their least and most sizes so, and a pane whose share of a narrow room is under its least size is at its least size in the first frame, with its divider at its edge.

What is laid out again may be measured anew: a splitter in the pane of a splitter that was put back has another room than it was first measured in. So the frame is laid out again until nothing that is watched changes, four times at most. An observer that writes another value on every rect it is given (a width that depends on what the width changes) uses all four in every frame and settles in none: write what the rect decides, not what it was.

use lurq::{components::Column, core::ElementRef, node::dimension::Dimension};
// In `create`: `roomy` is `ctx.signal(None::<bool>)`, `anchor` an `ElementRef` kept on the component.
let watch = roomy.clone();
anchor.observe_rect_before_paint(move |rect| {
let fits = Some(rect.width >= 480.0);
if watch.get_untracked() != fits {
watch.set(fits);
}
});
// In `render`: the room it is given, measured, around the form that fits it.
Column::new()
.width(Dimension::Pct(100.0))
.ref_element(anchor.clone())
.child(if roomy.get() == Some(false) { narrow() } else { wide() })

ui::Toolbar with overflow(true) is built this way.

Several observers of one ref. observe_rect and observe_rect_before_paint set the ref’s own observer: a second registration replaces the first, so the owner of the element registers it in every render and has one. Code that watches a ref it was given (a list of a page’s sections that follows their scroll, a tooltip on the app’s button) adds an observer beside it with ElementRef::add_rect_observer or add_rect_observer_before_paint, and takes no observer away. Each is called while the RectObserver it gives is kept and is removed when that is dropped: a component that adds one in each render keeps the handles of its last render and drops those of the one before, and its observers go with it when it is unmounted. An added observer is called when the rect changes, not for the rect the element has when it is added.

use lurq::core::{ElementRef, RectObserver};
// Kept on the component, `Mutex<Vec<RectObserver>>`: the observers of its last render.
let added: Vec<RectObserver> = sections
.iter()
.map(|section: &ElementRef| section.add_rect_observer_before_paint(move |rect| watch(rect.y)))
.collect();
*self.watching.lock().unwrap() = added; // those of the render before are removed here

ElementRef::observe_visibility tells an observer how much of an element shows, as a browser’s IntersectionObserver does: the page of a feed that fills the viewport is the current one, a thumbnail near the viewport loads its picture, a mark at the end of a list loads the next page.

use lurq::core::{ElementRef, Visibility, VisibilityObserver, VisibilityOptions};
// In `create`: the ref and the observer are kept on the component, `current` is `ctx.signal(false)`.
let page = ElementRef::new();
let watching: VisibilityObserver = page.observe_visibility(VisibilityOptions::new().thresholds([0.99]), {
let current = current.clone();
move |seen: Visibility| current.set(seen.ratio >= 0.99)
});
// In `render`: `.ref_element(page.clone())` on the page.
  • What is told. A Visibility: ratio, the share of the element’s box that is inside its root, from 0 to 1; visible, whether any of it is; visible_rect, the part that is, and rect, the element’s box, both in the window’s logical pixels with relative_x and relative_y from the root’s corner; and root_rect, the box it was measured against. An element of no size, a mark at the end of a list, has a ratio of 1 where it lies inside the root.
  • When. At the first layout after the observer was added, and then each time the share crosses one of its thresholds, either way: thresholds([0.99]) tells when the element all but fills its room and when it no longer does, thresholds([0.0, 0.5, 1.0]) when it comes in, is half in and is all in. With no threshold the observer is told when the element comes into view and when it leaves. Between two thresholds nothing is told, however the share changes. The observer is called after layout, as observe_rect’s is: a signal it writes is rendered in the next frame.
  • Against what. The scroll container nearest around the element, as much of its viewport as the containers around that one and the window show: a card in a strip that scrolls across, inside a page that scrolls down, shows where both show it. An element nothing scrolls is measured against the window. .root(&element_ref) measures against the box of an element around it instead, taken whole.
  • A margin grows the root before the element is measured, as rootMargin does: .margin(200.0) counts an element as showing from 200 logical pixels before it scrolls into view, which is how a grid loads the pictures near its viewport and no others. .margins(across, down) grows the two ways apart: a feed that scrolls down opens the video of the page under the one shown with .margins(0.0, page_height). A negative margin shrinks the root.
  • Whatever moved the content. The share is reckoned from the layout at every pass, not from scroll events: a finger, its momentum, a list on its way to a page, a wheel, the keys, the bar, the app’s own set_scroll, content that came in above, a window that was resized.
  • The observer lives as long as its handle. observe_visibility gives a VisibilityObserver; the observer is removed when that is dropped. A component keeps it in a field beside the ref, from create; one that adds observers in a render keeps those of its last render and drops the ones before, as with RectObserver above. An observer added after the element was laid out asks for a pass and is told in it.
  • The boxes are the layout’s: a transform (translate, scale) does not move them, and an element cut by a .clip() that does not scroll counts as showing. An element taken out of the tree is told of no more; one its row or column dropped for want of room is told that none of it shows.

A list that loads its next page when its end comes within a screen of the viewport:

// In `create`: `pages` is `ctx.signal(1usize)`, how many pages of rows the list shows.
let end = ElementRef::new();
let watching = end.observe_visibility(VisibilityOptions::new().margins(0.0, 600.0), {
let pages = pages.clone();
move |seen| {
// Told once as the end comes near, and again only after it went away and came back.
if seen.visible {
pages.update(|pages| *pages += 1);
}
}
});
// In `render`: the mark is the last child of the list's content.
ScrollVertical::new(Column::new().with_children(rows).child(Spacer::new().height(0.0).ref_element(end.clone())))
lurq::components::ScrollVertical::new(
lurq::components::Column::new()
.spacing(4.0)
.with_children(items),
)
.size(300.0, 180.0)

Scroll containers give their child unbounded constraints on the scroll axis and apply scroll offsets during layout/rendering. Without a fixed size on the scroll axis, a scroll container takes its content’s size within its constraints, so .max_height(...) makes it grow with its content up to the cap and scroll beyond it.

ScrollBoth::fill_width(true) lays the content out at least as wide as the viewport, and wider only where it needs more: a table’s columns share the room there is, and it scrolls sideways only where they do not fit. Without it the content of a ScrollBoth is as wide as it is itself, as unbounded room makes it. ScrollHorizontal::fill_width(true) does the same for what scrolls only sideways: a row of items that grow to share the viewport, and scroll once their least widths are more than it.

To bring an element into view, request it from a component with ctx.scroll_into_view(&element_ref) (the ref attached with .ref_element(...)), or call scroll_into_view() on the ElementHandle from tree.get_element_by_id_mut(id). Every scroll container around the element, nearest first, scrolls by the smallest amount that shows it, on each axis it scrolls, like the web’s scrollIntoView({ block: "nearest", inline: "nearest" }): an element already in view does not move anything, and one larger than a viewport is aligned to the viewport start. The request is resolved after the next layout, and the frame drawn after it already shows the element. Focusing an element by request or with Tab scrolls it into view the same way (see Focus And Keyboard Navigation).

// `details` is a ref retained by the component and attached with `.ref_element(details.clone())`.
ctx.scroll_into_view(&details);

ctx.scroll_into_view_start(&element_ref) brings the element’s top to the top of every container around it that scrolls down, as far as the content lets it, like the web’s scrollIntoView({ block: "start", inline: "nearest" }): an element already in view moves to the top too. It is what a list of a page’s sections does when one of them is pressed (ui::TableOfContents). The top is clear of what sticks to the container’s top, and a container that scrolls sideways moves by the smallest amount that shows the element.

// The heading comes to the top of the page, under the header that sticks there.
ctx.scroll_into_view_start(&heading);

To take a container back to its top, as a button at the foot of a long page does, ask from a component with ctx.scroll_to_top_of(&scroll_state), given the ScrollState the container was built with (with_scroll_state), or call tree.scroll_state_to_top(&scroll_state). The content goes there as a wheel’s scroll goes: over the frames that follow, on the wheel’s curve, with an on_scroll event of no delta for each step, and at once while motion is reduced or the theme’s smooth_scroll is off. A notch of the wheel that comes meanwhile adds to where the content is going, and anything else that scrolls the container (set_scroll, a drag of the thumb, a finger) stops it there. A state that scrolls nothing in the tree, or is at its top already, asks for nothing. ui::BackToTop is the design system’s button for it. (ctx.scroll_to_top(), with no state, is a phone’s tap on its status bar: the page at the middle of the window.)

// `scroll` is the ScrollState the page's ScrollVertical was given.
ctx.scroll_to_top_of(&scroll);

ctx.scroll_range_into_view(&text_ref, range) does the same for a range of a text, in bytes of its content: the lines the range covers are brought into view, and no more of the text, wherever it is wrapped. The current match of a search, in a long text that scrolls. The text must know where its characters are drawn, which one that is selectable or has highlights does; of another the whole element is brought into view.

// The current match: marked on the text with `Text::highlights`, and scrolled to.
ctx.scroll_range_into_view(&document, current.clone());

VirtualizedList sizes the same way: .height(...) or .flex(...) gives it a fixed viewport, while .max_height(...) alone lets a short list take its content height and a long one stop at the cap.

VirtualizedList::new(ctx, items)
.max_height(240.0)
.mount_keyed::<ItemRow, _, _, _>(|item| item.id, |item| item.clone())

.reveal_key(Some(key)) scrolls the row with that key into view, for example to show the selection again after navigating back to a list. The reveal fires on the first render and again each time the key changes, never on other re-renders, so it does not fight the user’s scrolling. A row that is already fully visible does not move; any other row is scrolled to the top of the viewport. The row does not need to be mounted: the list places it from its measured and estimated row heights and settles on the exact offset over the next few frames as the rows around it are measured. A key that is not among the items is dropped, except while the list has no items yet, so a list mounted before its data loads still opens on the row.

.reveal_request(n) reveals the reveal_key’s row again each time n changes, whether the key changed or not: for a list asked for one row twice, scrolled away from it between the two, as a focus group over rows the list builds only in part asks for the row its keys step to (see Focus And Keyboard Navigation).

// reveal: Signal<Option<String>>, asked: Signal<u64>; asking again adds one to `asked`.
VirtualizedList::new(ctx, items)
.height(480.0)
.reveal_key(reveal.get())
.reveal_request(asked.get())
.mount_keyed::<ItemRow, _, _, _>(|item| item.id, |item| item.clone())

When the items change so that the row keys differ (a row added, removed or moved), the list keeps the first visible row where it was, and a list at its end stays at its end. Rows added or removed below that row (a message appended to a chat, a trailing row dropped) cost no more than the rows in view. A change above it measures the rows not measured yet over the next frames to restore the exact offset. A scroll asked for in the same update wins over that: a pending scroll queued on the list’s ScrollState (scroll_to_bottom_pending, scroll_to_top_pending, set_scroll_pending), set_scroll, a reveal_key or a scroll into view, also when it lands while the list is still measuring its rows to keep that row in place.

Use reveal_key for rows of a VirtualizedList: only the rows in and near the viewport are mounted, so an element of any other row does not exist to be scrolled to. ctx.scroll_into_view does reach an element inside a mounted row, for example a field in the row being edited.

Before the list has measured a row it cannot size its window (the viewport is not laid out yet), so its first pass renders a fixed number of bootstrap rows, 16 by default or .bootstrap_rows(n), whose heights seed the estimate the next pass sizes the window with. They come from where the list opens: the last rows when scroll_to_bottom_pending was queued on its ScrollState (a chat), the rows from the reveal_key’s row, or else the first rows. A chat of 300 long replies opened at its end builds and lays out its last 16 only, however long it is; its first rows are built when they are scrolled to. A list whose rows are tall passes fewer; one whose rows are short can pass about a viewport’s worth so its first frame is full. When the items are swapped for others whose keys all differ (another conversation under the same list), the measured heights go but their average stays as the estimate, so the new rows are windowed where the list opens, about a viewport’s worth, instead of bootstrapped again. A row whose key stays but whose item changed (the same line number in another file) loses its measured height too and counts as the estimate until it is measured again.

Rows the list has not measured count as the average of the rows it has. When measured heights change, because a row grew (the person opened it) or the rows scrolled to measure other than their estimate, the first row in view stays where it is on screen: the offset moves with the content above it. A list at its end stays at its end instead, and a scroll asked for (set_scroll, a pending scroll, a reveal) lands where it asked. In a list whose rows differ much in height, one tall row measured among few pulls the average up for every row not measured yet; .estimate_height(|item| ...) gives the height of a row not measured yet instead, by kind for example, so the estimate does not move with the rows measured, and the list is sized from its first pass without bootstrap rows.

VirtualizedList::new(ctx, entries)
.estimate_height(|entry| if entry.is_output() { 240.0 } else { 56.0 })
.mount_keyed::<EntryRow, _, _, _>(|entry| entry.id, Clone::clone)

A wheel or a trackpad scrolls one container on each axis: the innermost one under the pointer that scrolls along that axis and can still move the way the event goes. It takes that axis of the event whole. What it cannot take, reaching its end within the event, is dropped and not handed to the container around it: one notch of the wheel over a list with 30 px left to scroll moves the list those 30 px and leaves the page where it is.

A container already at its end takes nothing, and the event goes to the container around it. So the next notch the same way scrolls the page, and one the other way scrolls the list again, which has room that way. A trackpad’s swipe is many events: those that come after the list reached its end scroll the page.

The two axes are decided separately. Over a strip that scrolls sideways inside a page that scrolls down, the sideways part of a slanted event scrolls the strip and its vertical part the page; a ScrollBoth list at its bottom hands on the vertical part alone and keeps scrolling sideways. A container that scrolls sideways only takes no part of a mostly vertical event, as a code block does.

on_scroll_reach_top and on_scroll_reach_bottom run on the container that moved.

A notch of a mouse’s wheel is animated, and which container takes it is decided on where each is going, not on where it is drawn: over a list that is still on its way to its end the next notch scrolls the page, as it would had the list been drawn there at once.

A finger’s scroll is a gesture with one container for all of it, chosen where the finger lands: see iOS.

components::Pager shows pages one at a time, each as large as the pager, down or across: a feed of videos that goes a video at a time, a strip of an album’s pictures in a page of it. Which page it is at is an index the app holds, and only the page shown and the ones beside it are built.

use lurq::{components::Pager, core::Signal};
let at: Signal<usize> = ctx.signal(0);
Pager::new(clips.len(), move |ctx, index| ctx.mount::<Clip>(clips[index].clone()))
.index(at.clone())
.on_index_change(|index| println!("at clip {index}"))
.mount(ctx)
Pager::new(count, |ctx, index| page)How many pages there are, and what builds the page at an index
index(Signal<usize>)The page it is at, held by the app: the pager goes to the page the signal says, and sets it to the page a person brought it to. Without one it starts at its first page and keeps where it is itself
on_index_change(|index| ..)Called with the page a person brought it to, after the signal was set. Not for a page the app set
vertical(), horizontal()Pages one under another, which is what it does unless told, or one beside another
beside(pages)How many pages are built on each side of the one shown: 1 unless told, never none
keys(bool)Whether the keys turn it: they do unless told
width(..), height(..)How large it is: all of its room unless told. A page is as large
id(..), key(..)The id of its box (the list of its pages is {id}-pages, a page {id}-page-{index}), and what tells it from the pagers beside it
  • The index is the truth, and it changes when the move is over. A finger drags the pages and lets go, and the index is as it was until the page it went to is at rest: on_index_change is then called once. A wheel and a key send the pages to the next one and the index follows the same way. A feed plays the video of the index and nothing else; what is to start earlier reads where the pages are going (ScrollState::target_page of a list of its own, or the page’s own visibility).
  • A page is a component of its own. What builds a page is called in the page’s own component: what it mounts there and what that keeps (a video that is open, a count) lives as long as the page is built, and is dropped with it when the pager is two pages away. A page that comes back is made anew, so what must outlive it is the app’s: the picture each album’s strip is at is a signal the app keeps, given to the strip as its index.
  • A thousand pages hold three. The pages that are not built are room and nothing else. An index the app sets to a page that is built (the one beside) takes the pager there over a few frames; one further away takes it there at once, and no page on the way is made.
  • One gesture, one page, one way. A finger never takes the pager further than the page beside the one it started on, however hard it throws. A pager across in a pager that goes down takes the finger that first went across, and the one around it the finger that first went down (Scroll containers inside one another); whatever ends the gesture, each comes to rest on a page.
  • A wheel turns a page for a notch, and a touchpad’s swipe turns one, with what it leaves rolling. A wheel that goes on turning turns again after two thirds of a second. A list inside a page scrolls first, as inside any scroll container, and the pager turns when it is at its end.
  • The keys. The arrow keys along its way turn a page; Page Up, Page Down, Home and End turn a pager that goes down. They are the pager’s where the focus is in it, and also where it is not while most of the pager shows (a strip in a page that is not shown takes none), unless a text input has the focus.
  • Only the page shown takes the pointer and the focus: Tab does not go into a page that is not there.

ui::Carousel is the design system’s component for slides with arrows and dots beside them, all built at once; a pager is the engine’s, for pages that fill their room and are too many, or too heavy, to build together.

.sticky(Sticky::top(0.0)) holds an element at an edge of the scroll container it is in while that scrolls, as CSS position: sticky does: a section’s header that stays at the top while its rows scroll under it.

use lurq::{
components::{Column, Row, ScrollVertical, Text},
layout::layout_kind::Sticky,
};
let section = Column::new()
.child(Row::new().background("#f4f4f5").child(Text::new("A")).sticky(Sticky::top(0.0)))
.child(Text::new("Ada"))
.child(Text::new("Alan"));
ScrollVertical::new(Column::new().child(section)).size(240.0, 320.0)
  • The element is laid out in flow and keeps its room there: nothing around it moves when it sticks.
  • Sticky::top, bottom, left and right take the distance to keep from that edge of the viewport, in logical pixels; with_top and the others add an edge, so Sticky::top(0.0).with_left(0.0) holds a corner cell of what scrolls both ways.
  • It never leaves the box of its parent, inside the parent’s padding. The end of a section takes the section’s header with it, and the next section’s header takes its place. An element whose parent is no larger than itself has nowhere to stick.
  • It sticks in the nearest scroll container around it. In none, it stays where it is laid out.
  • It is painted over its siblings and is hit before them, so a press on a stuck header does not reach the row under it.
  • Scrolling only moves it: nothing in it or around it is laid out again. An element ref on it reports where it is drawn.
  • A container’s bars run over the whole viewport, what sticks included, as a browser’s do beside a banner that stays. .scrollbars_clear_of_sticky(true) on ScrollVertical, ScrollHorizontal or ScrollBoth keeps them beside what scrolls: the bar down starts under what sticks at the top (a table’s header) and ends above what sticks at the bottom, the bar across runs from what sticks at the start (its first column) to what sticks at the end (a column pinned there), each as far in as that reaches (its inset and its size), and the thumb is the share of what scrolls that shows. Each keeps clear along its own axis only: the bar down stands at the container’s end edge, over the edge of what sticks at the right (a column pinned there) and never over what scrolls, and the bar across at its bottom edge, over what sticks at the bottom, or in a lane of its own. Painting, the pointer on the bar and a drag of its thumb go by that track, so a thumb at the track’s end is the end of the scroll. ui::Table asks for it.
  • An overlay bar across lies over the bottom of what scrolls, a table’s last row in view. .reserve_bar_across(true) on ScrollHorizontal or ScrollBoth gives it a lane of its own under the content, as wide as a Reserved gutter (the bar and its edge inset on both sides), while the content is wider than the viewport: the viewport ends above the lane, so nothing it shows is ever under the bar, and the bar down ends where the viewport does. Content that fits has no lane and no strip under it. ui::Table asks for it.
  • A wheel turned up and down scrolls a container down, or what holds it, and a container that scrolls only across lets it by. .wheel_across(true) on ScrollHorizontal or ScrollBoth takes such a turn sideways, as a browser’s strip of tabs does: turned down, the content moves to its end; what is left of the turn at the container’s end goes to what holds it, as with any scroll. A turn that has a sideways part (a touchpad’s) is taken as it is. Off by default, so a list across inside a page lets the page take the wheel. ui::WindowTabs asks for it.

A scroll container can scroll the way browsers do while the middle button is held: .middle_button_autoscroll(true) on ScrollVertical, ScrollHorizontal, ScrollBoth or VirtualizedList turns it on for that container; it is off by default, so an app picks the containers that have it (a long chat, not a code editor, for example).

VirtualizedList::new(ctx, entries)
.middle_button_autoscroll(true)
.flex(1.0)
.mount_keyed::<Entry, _, _, _>(|entry| entry.id, |entry| entry.clone())

A middle press over the container draws a mark where the button went down. While the button is held, the content scrolls toward the pointer, faster the farther the pointer is from the mark, on the axes the container scrolls; within about 12 logical pixels of the mark it stands still. Releasing the button, pressing Esc or the pointer leaving the window ends it, and that release clicks nothing. The container’s on_scroll handlers (and its scroll-reach handlers) hear each step, so a VirtualizedList mounts the rows it scrolls to.

The innermost container under the pointer that has it on and has content to scroll takes the press. A press on an element that takes the middle button itself is left to it: an on_mouse_click(MouseButton::Middle, ...) handler, a drag that starts with the middle button, or a on_mouse_down handler that calls prevent_default() (as a Markdown link does when the app takes middle clicks). The wheel, the scrollbar and text selection are unchanged.

A row that scrolls out of the rendered window (the viewport and overscan_px beyond it) is unmounted, and it is created again from its props when it scrolls back. Everything the row component holds itself starts over: fields set in create, signals from ctx.signal, element refs, the value signal of a text input the row created, and focus inside the row. Keep state that must survive scrolling above the list, keyed by the row key:

  • data belongs in the items themselves;
  • view state (expanded, a draft being edited) goes in a signal or store the screen owns, such as a Signal<HashMap<Key, RowState>>, or a HashMap<Key, Signal<String>> of text-input values. Hand it to the rows with ctx.provide in the screen and ctx.use_context in the row, or through the row props. A row that reads its entry during render re-renders when the entry changes.

Remove entries whose keys left the items when the items change. ctx.persistent_value is for values kept across app restarts, not for this.

// Screen `create`: one map for all rows, keyed like the rows.
let expanded: Signal<HashMap<TaskId, bool>> = ctx.signal(HashMap::new());
ctx.provide(expanded);
// Row `create` keeps the map; `render` reads the row's entry.
let expanded = ctx.use_context::<Signal<HashMap<TaskId, bool>>>().expect("provided by the screen");
let open = expanded.with(|rows| rows.get(&task.id).copied().unwrap_or(false));
// On toggle:
expanded.update(|rows| {
rows.insert(task.id, !open);
});
VirtualizedList::new(ctx, tasks)
.flex(1.0)
.reveal_key(selected.get().map(|id| id.to_string()))
.mount_keyed::<TaskRow, _, _, _>(|task| task.id, |task| task.clone())

A frame costs what changed and what is in view, not what the tree holds. A frame that only scrolls a document of 3,000 blocks (some 22,000 nodes) lays out the scroll container and draws what is in view, about the same as one of 300 blocks does.

  • Each subtree knows what is in it that a frame’s walks look for: an element ref, a layer (an overlay, a modal) or a dropdown’s anchor, a text input, a select, a scroll container, a child its line may drop (ShrinkLimit::Drop, shrink_drop_below, a drop marker), a transition, an animation that plays. The walks that index the tree’s layers and refs, tell the refs where their elements are, list the dropped nodes and check scroll offsets pass by a subtree that holds none. This knowledge is made again whenever the node, or anything under it, changes or is built again, so a ref added deep in a subtree nothing else touched is found in the frame it appears.
  • A cached subtree served as it was is not prepared again: a long content scrolled in its container is the tree laid out last frame, with no walk through its texts or its own scroll containers, while no text’s layout changed.
  • The paint culls a subtree that does not clip (overflow_visible) where all it may paint is out of view: the layout knows where each subtree paints (its box with its own shadows and outline, and its children’s where it does not clip them), and leaves 32 px of room for what states and text draw past it. A subtree that may move without a layout (a transform, a transition or an animation of where it is, a canvas, a border outside its box) is never culled for being out of view.
  • Transitions tick what may have changed: a subtree in which nothing runs is ticked clean, and not ticked again until it changes, a state of interaction (a hover, a press, the focus) or a theme changes anywhere, or a transition starts in it. Animations tick only where one plays.
  • A component built again on its own costs itself and its way to the root: its output is looked for only down the subtrees that hold a component’s output, the nodes it brought are numbered and take the disabled state of what they are in, and the rest of the tree is not numbered again; the column it is in is patched where it changed, the rest of the column not walked again. A component built again beside a document of 3,000 blocks takes 0.4 ms where it took 0.9.

perf_profile names these steps as frame sections, to see where a frame goes.

Text is measured by the glyph engine and wraps within its width constraint.

lurq::components::Text::styled("hello", TextStyle {
font_size: 18.0,
..TextStyle::default()
})

Text::max_lines(n) lays a wrapped text out in at most n lines, as CSS line-clamp does. A text that needs more keeps its start and ends in an ellipsis on the last line:

use lurq::components::Text;
// A card's description: two lines, then "…".
Text::new(description).max_lines(2)
  • The text keeps as much as leaves room for the ellipsis on the last line, and no whitespace before it.
  • Lines ended by a line break in the text count as lines.
  • A text that fits in n lines is left as it is, and 0 is no limit.
  • It applies to a text that wraps in a bounded width. nowrap() and TextOverflow::Elipsis, which keep a text on one line, are not affected; use TextOverflow::Elipsis for a single line cut at its width.
  • The limit holds for the text as it is painted, at any display scale: the text is cut so that neither the layout that sizes it nor the one that paints it, in device pixels, needs more lines.

A text draws a line under its words, or through them, like CSS text-decoration:

use lurq::{
components::Text,
layout::text_style::{TextStrikethrough, TextUnderline},
};
Text::new("Read the docs").underline(TextUnderline::new());
Text::new("12.99").strikethrough(TextStrikethrough::new().color(muted));
  • TextStyle::case draws a text in capitals (TextCase::Upper) or in small letters (Lower), like CSS text-transform: a typography role says it, as TypographyStyle::Heading6 does. Only what is drawn changes; the text, what is copied of it, what tooling reads and where a caret stands are the text as written. A letter whose other case is more than one letter or is written in more bytes (ß) is drawn as written.
  • Text::underline(...) and Text::strikethrough(...) set them on one text; TextStyle::underline and TextStyle::strikethrough set them in a style, a typography role’s included.
  • Each unset value follows the text: its color (the foreground it takes, when it names none), and the thickness and position the font gives its underline and its strikeout. TextUnderline also takes an offset.
  • The lines are drawn for every laid-out line of the text, wrapped lines included, under and through its words and not the whitespace a wrapped line ends in. They change neither the text’s size nor its wrapping.
  • Markdown draws ~~struck~~ text with a line through it (ThemeMarkdown::strikethrough).

The glyph engine also records caret positions for text selection, one before and one after every glyph of the layout the text is drawn with (a right-to-left glyph’s caret before it is at its right edge). Text::selectable(true) uses those positions for drag ranges, double-click word selection, and triple-click line selection. Wrapped or multiline selections render separate highlight rectangles for each selected row.

Transforms are visual-only for layout size, but render output and hit testing use the transformed coordinates. Text selection and text input carets therefore follow transformed text, including text inside a transformed parent.

See Animation And Transforms for transform composition, keyframe animation, and transition details.

TextTransformMode::Bitmap is the default. It rasterizes glyphs in their normal orientation and transforms those glyph quads during rendering. This path preserves float placement and is best for animated transforms because changing the transform does not create a new glyph atlas entry for every angle.

TextTransformMode::Rasterized is for static transformed text. It bakes the transform into the glyph mask, uses float screen-space placement for the baked mask, and emits identity-transform glyph quads. This produces sharper rotated edges than GPU-transforming the normal glyph bitmap, but the transform matrix is part of the glyph cache key, so continuously animated angles can grow the atlas.

use lurq::node::{TextTransformMode, transform::Transform2D};
lurq::components::Text::new("Static rotated text")
.text_transform_mode(TextTransformMode::Rasterized)
.transform(Transform2D::rotate_deg(-8.0))