Skip to content

Implement CSS vertical-align for inline formatting contexts - #18

Draft
nicoburns wants to merge 21 commits into
mainfrom
devin/1788383056-vertical-align
Draft

nicoburns wants to merge 21 commits into
mainfrom
devin/1788383056-vertical-align

Conversation

@nicoburns

@nicoburns nicoburns commented Sep 2, 2026

Copy link
Copy Markdown
Member

LLM Contributions: Written with Devin (Cognition AI); design and review by the author.

Implements the CSS 2.2 §10.8 inline alignment model. Commit-by-commit:

  1. Style tree parentsTreeStyleBuilder now materialises ancestor styles (even ones with no direct text) into the style table, parent-first, and each Style carries parent: u16. Root style is index 0 and is the strut. RangedBuilder styles all parent 0.
  2. VerticalAlign — new StyleProperty::VerticalAlign(VerticalAlign) and InlineBox::vertical_align. Following css-inline-3, VerticalAlign { alignment: AlignmentBaseline, shift: BaselineShift } is a compound of the two longhands (AlignmentBaseline::{Baseline, TextTop, TextBottom, Middle}, BaselineShift::{Length(f32), Sub, Super, Top, Bottom}), so vertical-align: text-top 2px is representable and callers with the longhands (Blitz/Stylo) pass them through losslessly. The CSS 2 keywords are associated constants (VerticalAlign::SUPER, ::TEXT_TOP, …) plus VerticalAlign::length(px). Percentages must be resolved by the caller.
  3. StyleMetrics pass (layout/style_metrics.rs) — once per layout, per style: primary-font ascent/descent/x-height (FontMetrics::from_variations), line-height as half-leading → over/under, then baseline_offset relative to the parent = alignment offset (middle uses the parent x-height and the child's expanded box; text-top/bottom the parent content box) + shift (sub/super use WebKit's fontSize/5, fontSize/3), and aligned_subtree (nearest top/bottom ancestor, else 0).
  4. Line breakingLineBoxMetrics becomes SmallVec<SubtreeExtents> + a per-line "contributed styles" set. Each line is seeded with the strut; each run/inline box adds its own style box at its baseline offset plus any not-yet-contributed ancestors. top/bottom subtrees are sized separately and, in finish_line, grow the line below/above when taller than the root subtree; their offsets are stored on LineData::aligned_subtree_offsets. Lines containing only empty inline boxes stay zero-height.
  5. OutputGlyphRun::baseline and PositionedInlineBox::y use the style's shifted baseline via Line::style_baseline / Line::inline_box_top. LineMetrics::baseline stays the root baseline; cursor/selection use whole-line block extents and are unaffected.

Behaviour changes for existing users: lines containing only inline boxes (or none of the text's styles) now get strut height, and a span's inline box uses the primary-font metrics of that style (six snapshots updated). New styles/vertical_align snapshot tests cover every keyword, nested super, ancestor-only spans, inline boxes and tall top/bottom subtrees; unit tests cover the metrics pass including composition of alignment + shift.

Blitz follow-up: DioxusLabs/blitz#832.

Changelog

Added

  • StyleProperty::VerticalAlign / VerticalAlign { alignment: AlignmentBaseline, shift: BaselineShift } and InlineBox::vertical_align, implementing CSS vertical-align (parent-relative and line-relative values).

Changed

  • Breaking change: InlineBox has a new vertical_align field.
  • Line boxes now follow the CSS 2.2 inline-box model more closely: every line includes the root style's strut, and nested tree-builder spans contribute their own inline boxes even when they have no direct text.

Link to Devin session: https://dioxus.staging.devinenterprise.com/sessions/da7669e341814cc7976e4ebf32b7eacb
Open in Devin Desktop: https://dioxus.staging.devinenterprise.com/desktop/session/da7669e341814cc7976e4ebf32b7eacb?variant=devin-insiders
Requested by: @nicoburns

@staging-devin-ai-integration

Copy link
Copy Markdown

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR that start with 'DevinAI' or '@devin'.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

The root style is always materialised at index 0 and every other style
records the index of its enclosing span's style. The tree builder now
materialises ancestor spans that contain no direct text so that they can
contribute their inline box to line metrics.
`VerticalAlign` mirrors css-inline-3 as a compound of `AlignmentBaseline`
(baseline, text-top, text-bottom, middle) and `BaselineShift` (length, sub,
super, top, bottom), so callers holding the longhands (e.g. Blitz over Stylo)
can pass them through losslessly and values such as `vertical-align: text-top
2px` compose. The CSS 2 keywords are available as associated constants
(`VerticalAlign::SUPER` etc.) plus `VerticalAlign::length`.

The property is plumbed through `StyleProperty`, `TextStyle`, both builders
and `ResolvedStyle`; atomic inline boxes carry their own `vertical_align` and
optional `baseline`. No layout behaviour changes yet.
Every style table entry gets `StyleMetrics`: primary-font ascent/descent/
x-height (honouring font variations), the line-height expanded `over`/`under`
box with CSS 2 §10.8.1 half-leading, and its baseline offset relative to the
root of its aligned subtree. Offsets accumulate parent-first through the
style's parent chain (`alignment-baseline` offset plus `baseline-shift`);
`top`/`bottom` start a new line-relative aligned subtree. `sub`/`super` use
the WebKit/Blink constants (font-size / 5 and / 3).

Per-character style indices are reset for each layout so an empty layout's
substitute space uses the root style rather than a stale index.
… glyphs/inline boxes

Line breaking now seeds every line with the root (strut) inline box, adds each
run's style box plus its not-yet-contributed ancestors, and tracks
vertical-align: top/bottom subtrees separately. Glyph runs and inline boxes are
positioned at their style's shifted baseline. Lines containing only inline boxes
now get strut height (snapshots updated).

Details folded in from review:
- Lines containing only empty or out-of-flow inline boxes have zero height;
  negative-height in-flow boxes still count as content and keep the strut.
- The trailing line after a final newline is sized by the newline's style
  chain rather than collapsing to the strut.
- With `quantize`, the exact baseline offset is accumulated down the style
  chain and rounded once per style (and once per top/bottom subtree), so
  glyph baselines are whole pixels without per-level rounding drift, and
  inline box ascent/descent are not rounded separately.
- Font queries and metrics are shared between styles with identical font
  selection inputs, run box metrics are computed once per run, and the
  shaped run's metrics are reused for its style; aligned-subtree offsets are
  stored per layout instead of per line.
…+0020 coverage check

CSS Fonts 4 defines the first available font via unicode-range coverage of U+0020, not glyph coverage. Parley has no unicode-range, so every available face qualifies and the first face of the stack is used.
…box"

Parley already uses "inline box" for `InlineBox`, an atomic box embedded in the text, so use "span" / "span box" for what CSS calls an inline box (the box generated by a style table entry on a line). Documents the term in the `style_metrics` module docs.
BreakerState::default() is public and can be passed to BreakLines::revert_to,
but its LineBoxMetrics had no root aligned subtree, so the next line would
index out of bounds. Default now contains the root subtree (without a strut)
and reset builds on it, so the breaker is valid from any BreakerState.
Split the font-derived part into BoxMetrics, whose from_font returns a
complete value and is what run_box_metrics needs; StyleMetrics::from_font
is only meaningful inside resolve_style_metrics, which fills in the
remaining tree-position fields.
Each style now resolves its first available font and metrics directly;
cross-layout caching of both is left to the FontContext font cache.
Every non-root span's parent must precede it in the style table
(debug-asserted); a malformed parent index falls back to the root rather
than producing a self-parented orphan, so ancestor walks always end at 0.
Replaces the parallel inline_boxes / inline_box_styles vectors with a single
Vec<LayoutInlineBox { inline_box, style_index }>, so sorting is a plain
stable sort_by_key and the two can no longer get out of step.

Layout::inline_boxes() / inline_boxes_mut() now return ExactSizeIterators
over &InlineBox / &mut InlineBox instead of slices.
Signed-off-by: Nico Burns <nico@nicoburns.com>
Fonts without OS/2 sxHeight previously fell back to half the ascent.
Gecko (DEFAULT_XHEIGHT_FACTOR) and Blink both estimate 0.56 * ascent
in that case; css-inline-3 Appendix A.2 only suggests 0.5em as a
last resort after glyph measurement.
@staging-devin-ai-integration
staging-devin-ai-integration Bot force-pushed the devin/1788383056-vertical-align branch from 043f32f to 2dcf528 Compare September 17, 2026 10:48
`LineBoxMetrics::contributed` (style indices already counted on the current line) was a `SmallVec<[u16; 8]>` cloned with `LineState` at every break opportunity and re-extended on every `reset`. It is append-only, so it can live once on `BreakerState` with a saved length in `PrevBoundaryState` and a truncate on revert. `subtrees` stays inline: its entries are mutated in place, so a length is not enough to roll them back (see `lines_revert_restores_line_height`).

Also reuse the `prev_state` allocation in `break_next` via `clone_from`.

Benchmarked on ~250KB of prose: break+align -7.6% (plain) / -6.1% (styled) / -8.2% (styled + vertical-align) vs before; layouts identical.
LineState is cloned at every soft-break opportunity, and the SmallVec<[SubtreeExtents; 2]> inside LineBoxMetrics made that a non-trivial clone/drop plus a 128-byte move in reset_to/take().

The root subtree's extents now live inline as a plain Copy field. Non-root (vertical-align: top/bottom) subtrees are recorded in an append-only Vec<SubtreeExtents> owned by BreakerState next to the `contributed` buffer. Entries at indices below the most recent saved break opportunity are never mutated: growing such a subtree pushes a new copy instead, so truncating the log in reset_to restores the exact extents at that opportunity. Later entries are updated in place, and nothing is pushed when the extents don't change. The current extents of a subtree are the last log entry for its root; earlier entries are stale and ignored when finishing a line. Plain prose never touches the log.

`append_atom_to_line` and `LineBoxMetrics::add_text` are #[inline(always)] so they fold back into break_remaining.

Adds tests for rolling back a tall top-aligned span at a break and for two aligned subtrees whose extents grow across several words/lines.

Break phase (250KB prose, 800/400px alternating, min of 5 interleaved rounds): plain 4.52 -> 3.46 ms, styled 5.69 -> 4.57 ms, styled+vertical-align 6.25 -> 4.90 ms; layout output unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant