Help us shape the future of Go! Take the 2026 Go Developer Survey

render

package
v0.1.0-alpha.2 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package render turns an HTML document plus stylesheets into geometry and a display list: CSS cascade and computed values, box-model layout (block, inline, inline-block, flex, grid, table, float, positioned), text shaping with real font metrics, and paint operations. Rasterization lives in internal/raster, which consumes the display list defined here.

This file is the contract between the layout engine (producer) and the rasterizer / canvas packages (consumers). Coordinates are CSS pixels in document space (origin top-left of the page, y down) unless stated.

Index

Constants

This section is empty.

Variables

View Source
var StageHook func(stage string, d time.Duration)

StageHook, when set (SWEEF_STAGES in internal/engine), receives the time of each stage of a layout pass: build (styles + box tree), layout, finish (boxes, display list, hit testing).

Functions

func CollectSVGText

func CollectSVGText(root *SVGNode, ln func(n *SVGNode, s string, axis byte) float64) (chars []SVGTextChar, lens []SVGTextLen)

CollectSVGText flattens the text content of root (a <text> element) into addressable characters with the positioning attribute lists resolved. ln converts a length string of a node to user units (axis 'x' or 'y'). ok is false when a <textPath> in the content has no usable target (Chromium renders nothing for such an element).

func DiffResults

func DiffResults(a, b *Result) string

DiffResults compares two layout results of the same tree and returns a description of the first difference ("" when they are identical): document size, every box, and every display-list op (by content signature, falling back to deep comparison for ops without one). It backs SWEEF_LAYOUT_CHECK, which compares an incremental layout with a from-scratch one.

func IsQuirks

func IsQuirks(root *html.Node) bool

IsQuirks reports whether layout treats the document as quirks mode (document.compatMode).

func IsSVGFilterRef

func IsSVGFilterRef(name string) bool

IsSVGFilterRef reports whether a Filter.Name is an SVG filter reference.

func OpSig

func OpSig(op Op) (sig uint64, ok bool)

OpSig returns the content signature of op. ok is false for ops whose pixels depend on state outside the op (live bitmaps, backdrop filters, 3D layers, clip paths): the caller must then repaint everything.

func SVGParsePct

func SVGParsePct(s string, total float64) float64

SVGParsePct resolves a startOffset-style number or percentage of total.

func SVGPathContours

func SVGPathContours(d string) [][][2]float64

SVGPathContours flattens SVG path data into polylines (one per subpath). Closed subpaths end on their start point.

Types

type BackdropFilter

type BackdropFilter struct {
	Rect   Rect
	Radii  Radii
	Filter []Filter
}

BackdropFilter blurs/filters what is already painted behind Rect (clipped to the rounded rect) before the element's own content is drawn. Additive op for backdrop-filter.

type Bitmap

type Bitmap struct {
	Node  *html.Node
	Dst   Rect
	Fit   string // object-fit: fill, contain, cover, none, scale-down
	Pos   [2]float64
	Radii Radii
}

Bitmap draws live pixel content owned by something other than layout (canvas, WebGL, video frame, SVG raster). Read at paint time.

type Border

type Border struct {
	Rect   Rect // border box
	Widths [4]float64
	Colors [4]Color
	Styles [4]string
	Radii  Radii
}

Border strokes the four sides of a border box. Widths and Styles are in top, right, bottom, left order. Styles: solid, dashed, dotted, double, groove, ridge, inset, outset, none, hidden.

type Box

type Box struct {
	Border  Rect       // border box: what getBoundingClientRect reports (before transforms)
	Padding Rect       // padding box
	Content Rect       // content box
	Margin  [4]float64 // top, right, bottom, left
	Frags   []Rect     // one border-box fragment per line box for inline elements, per column for blocks split across columns (getClientRects)
	// Scroll sizes for overflow containers and the viewport.
	ScrollW, ScrollH float64
	ClientW, ClientH float64 // padding box minus scrollbars
	Display          string
	Position         string
	Visible          bool       // false for display:none / visibility:hidden
	Transform        [6]float64 // identity when no transform
	HasTransform     bool
	Xf3              *Xf3D // 3D transform data (nil without 3D involvement)
	OffsetParent     *html.Node
	ZIndex           int
	Style            *style.Computed // the element's computed style (getComputedStyle)
}

Box is the geometry of one element, in document coordinates.

type BoxShadow

type BoxShadow struct {
	Rect         Rect // the box casting the shadow (border box)
	Radii        Radii
	DX, DY       float64
	Blur, Spread float64
	Color        Color
	Inset        bool
}

BoxShadow paints an outer or inset shadow for a (rounded) box.

type ClipSub

type ClipSub struct {
	Kind string // rrect | ellipse | polygon | path
	// rrect
	Rect  Rect
	Radii Radii
	// ellipse
	CX, CY, RX, RY float64
	// polygon
	Pts [][2]float64
	// path: SVG path data transformed by M (HasM) before filling
	D       string
	M       [6]float64
	HasM    bool
	EvenOdd bool
}

ClipSub is one filled shape of a clip path. Coordinates are CSS px in the current (possibly transformed) space.

type Color

type Color = style.Color

Color is non-premultiplied 8-bit RGBA (an alias of style.Color so the style engine and the display list share one type).

type Env

type Env interface {
	// Image returns a decoded image for a resolved URL, or nil when it is not
	// available (not fetched, failed). Intrinsic sizes come from the bitmap.
	Image(url string) image.Image
	// Bitmap returns live pixels for <canvas>, <video> and similar nodes, or nil.
	Bitmap(n *html.Node) image.Image
	// IntrinsicSize returns the natural size of replaced content when known
	// (canvas width/height, video videoWidth/videoHeight); ok false if unknown.
	IntrinsicSize(n *html.Node) (w, h float64, ok bool)
	// Focused is the element with focus (for :focus and focus rings), or nil.
	Focused() *html.Node
}

Env supplies resources and live state to layout and paint.

type FillRect

type FillRect struct {
	Rect  Rect
	Color Color
	Radii Radii
}

FillRect fills a (possibly rounded) rectangle with a solid color.

type Filter

type Filter struct {
	Name  string // blur, brightness, contrast, grayscale, hue-rotate, invert, opacity, saturate, sepia, drop-shadow
	Args  []float64
	Color Color // drop-shadow
}

Filter is one CSS filter function with its numeric argument(s).

type FrameEnv

type FrameEnv interface {
	HasFrame(n *html.Node) bool
}

FrameEnv is an optional extension of Env for embedders that render <iframe> documents. When HasFrame reports true for an iframe element, layout emits a Bitmap op at its content box and the frame's pixels come from Env.Bitmap(n) at raster time, so the frame is clipped, transformed, faded and radius-clipped exactly like a canvas.

type Glyph

type Glyph struct {
	R    rune
	X    float64
	Face *font.Face // face that has the glyph (fallback may differ per glyph)
	GID  int        // additive: glyph id to draw instead of R's glyph (ligatures); 0 = use R
}

Glyph is one positioned character in a TextRun; X is the pen offset from the run origin in px (already includes kerning, letter- and word-spacing).

type Gradient

type Gradient struct {
	Rect  Rect
	Kind  string // linear, radial, conic
	Radii Radii
	Stops []GradientStop
	// linear: Angle in degrees (CSS convention, 0 = to top, 90 = to right).
	Angle float64
	// radial: center and radii in px relative to Rect's top-left; conic: center + FromAngle.
	CX, CY, RX, RY float64
	FromAngle      float64
	Repeating      bool
	Tile           *Tile
}

Gradient paints linear, radial or conic gradients into Rect.

type GradientStop

type GradientStop struct {
	Pos   float64
	Color Color
}

GradientStop is a color stop at Pos in [0,1] along the gradient line.

type Image

type Image struct {
	Img    image.Image
	Dst    Rect
	Src    Rect
	Radii  Radii
	Smooth bool  // bilinear; false = nearest (image-rendering: pixelated)
	Tile   *Tile // when set, the image repeats (background-repeat)
}

Image draws a decoded bitmap into Dst, optionally cropping Src (zero Src = whole image). Used for <img>, <canvas>, <video> frames and CSS images.

type ImageHinter

type ImageHinter interface {
	ImageHint(url string, r Rect)
}

ImageHinter is an optional Env extension. ImageHint reports, for an image that Env.Image could not supply (returned nil), the document-space rectangle where it would be drawn (a zero height means its size is not known yet). It is called during Layout, so implementations must be cheap and must not call back into layout.

type MaskLayerOps

type MaskLayerOps struct {
	Ops       []Op
	Mode      string // alpha | luminance
	Composite string // add | subtract | intersect | exclude
}

MaskLayerOps is one mask layer: Ops paint the layer's image (clipped to the layer's painting area) onto a transparent surface; Mode picks whether its alpha or its luminance is the mask value, Composite how it combines with the layers below it.

type Mat4

type Mat4 [4][4]float64

Mat4 is a 4x4 matrix acting on column vectors: p' = M * p, M[row][col].

type Op

type Op interface {
	// contains filtered or unexported methods
}

Op is one paint operation. Ops are applied in order (painter's algorithm); layout emits them in CSS paint order (backgrounds, borders, floats, inline content, positioned layers by z-index).

type Options

type Options struct {
	Width, Height float64 // viewport in CSS px
	DPR           float64 // device pixel ratio (for image-set, resolution media)
	ColorScheme   string  // "light" | "dark"
	BaseURL       string
	Sheets        []Sheet // author sheets in order; the UA sheet is built in
	Env           Env
	ReducedMotion bool
	Print         bool // media type print instead of screen
	// ScrollX, ScrollY is the viewport's scroll position, used to decide which
	// content-visibility:auto subtrees are on screen.
	ScrollX, ScrollY float64
	// CVRelevant, when set, reports content-visibility:auto elements that are
	// relevant to the user for another reason (they contain focus or the
	// selection); those are never skipped.
	CVRelevant func(n *html.Node) bool
	// Session, when set, carries styles and SVG scenes from one pass over a
	// document to the next (see Session). The caller owns it and must not run
	// two passes at once.
	Session *Session
	// Fonts is the document's web font set (see font.WebSet). Family names it
	// declares resolve to its faces, which are fetched when the text needs them.
	Fonts *font.WebSet
}

Options configure one layout pass.

type PopClip

type PopClip struct{}

PopClip ends the innermost clip.

type PopClipPath

type PopClipPath struct{}

PopClipPath ends the innermost PushClipPath.

type PopLayer

type PopLayer struct{}

PopLayer ends the innermost layer.

type PopMask

type PopMask struct{}

PopMask ends the innermost PushMask and composites the masked group.

type PopTransform

type PopTransform struct{}

PopTransform ends the innermost transform.

type PopTransform3D

type PopTransform3D struct{}

PopTransform3D ends the innermost PushTransform3D and composites the layer.

type PushClip

type PushClip struct {
	Rect  Rect
	Radii Radii
}

PushClip restricts painting to a (rounded) rectangle until PopClip.

type PushClipPath

type PushClipPath struct {
	Subs   []ClipSub
	Bounds Rect // area the clip can affect (the element's painted area)
}

PushClipPath clips painting to the union of Subs until PopClipPath.

type PushLayer

type PushLayer struct {
	Opacity float64
	Blend   string // normal, multiply, screen, overlay, darken, lighten, ...
	Filter  []Filter
	Bounds  Rect
}

PushLayer starts an isolated group composited back with Opacity and an optional blend mode when popped (opacity, mix-blend-mode, filter, transforms that need a layer).

type PushMask

type PushMask struct {
	Bounds Rect
	Layers []MaskLayerOps
}

PushMask paints everything until PopMask into an isolated group and multiplies it with the composite of Layers (top-most first, as written in CSS). Outside Bounds nothing is painted.

type PushTransform

type PushTransform struct {
	M          [6]float64
	Lattice    bool
	LatX, LatY float64
}

PushTransform applies an affine matrix [a b c d e f] (CSS matrix()) until PopTransform.

Lattice, when set, says the rasterizer must snap rectangles (backgrounds, borders, images, clips) to a whole-pixel grid anchored at (LatX, LatY) in the coordinates of the ops that follow, instead of snapping in device space. Chromium snaps in the local space of the nearest paint-offset container and transforms the snapped geometry afterwards, so a scaled or translated frame keeps its box edges on its own pixel grid. Without Lattice the old device-space snapping applies.

type PushTransform3D

type PushTransform3D struct {
	// M is the layer's matrix, row-major 4x4, acting on column vectors
	// (x, y, z, 1) of the layer's coordinates, relative to the coordinate space
	// the op itself is emitted in (the enclosing layer or the page). Only the
	// z = 0 plane (rows and columns 0, 1, 3) is needed to draw; z and the full
	// matrix are informative (depth, backface tests).
	M [16]float64
	// Bounds is the part of the layer's plane that can carry ink, in the ops'
	// coordinates. Nothing outside it is drawn.
	Bounds Rect
	// Clip, when not empty, restricts the layer to this convex polygon (in the
	// ops' coordinates). The splitter of a 3D rendering context uses it to draw
	// the two halves of a layer that a plane cuts apart.
	Clip [][2]float64
	// Lattice anchors the layer's pixel grid at (LatX, LatY) in the ops'
	// coordinates: the layer is rasterized with that point on a pixel
	// boundary, and rectangles snap to the grid (see PushTransform.Lattice).
	Lattice    bool
	LatX, LatY float64
}

PushTransform3D draws the ops up to PopTransform3D as one projectively transformed layer.

type Radii

type Radii [4][2]float64

Radii are the four corner radii (top-left, top-right, bottom-right, bottom-left), each with horizontal and vertical extent (elliptical corners).

func (Radii) IsZero

func (r Radii) IsZero() bool

IsZero reports whether all corners are square.

type Rect

type Rect struct{ X, Y, W, H float64 }

Rect is an axis-aligned rectangle.

func (Rect) Bottom

func (r Rect) Bottom() float64

func (Rect) Right

func (r Rect) Right() float64

Right and Bottom are the far edges.

type Result

type Result struct {
	Width, Height float64 // document scroll size (>= viewport)
	Viewport      Rect
	Boxes         map[*html.Node]*Box
	List          []Op
	// Hit returns the topmost element at a document point, honoring paint
	// order, pointer-events and clipping; nil when the point hits only the canvas.
	Hit func(x, y float64) *html.Node
	// HitAt is Hit plus the point in the hit element's own pre-transform
	// document space (what a nested viewport needs to translate input).
	HitAt func(x, y float64) (n *html.Node, lx, ly float64)
}

Result is the output of Layout.

func Layout

func Layout(root *html.Node, o Options) *Result

Layout lays out the document rooted at root (a document or html element).

Documents that use @container rules are laid out repeatedly: each pass evaluates the queries against the container sizes measured in the previous pass until the sizes stop changing.

func (*Result) ClientRect

func (r *Result) ClientRect(n *html.Node) (Rect, bool)

ClientRect returns the bounding rectangle of n as getBoundingClientRect reports it at scroll offset 0: the union of its fragments with the transforms of n and all its ancestors applied. ok is false for nodes without a box (display:none and descendants).

func (*Result) ClientRects

func (r *Result) ClientRects(n *html.Node) []Rect

ClientRects returns the per-fragment rectangles of n as getClientRects reports them: every fragment (line box piece or column) projected through the transform chain.

type SVGClipShape

type SVGClipShape struct {
	Shape *style.BasicShape
	Box   string // "" (= border-box, which is the stroke box for SVG), fill-box, stroke-box, view-box, ...
}

SVGClipShape is a parsed CSS clip-path basic shape on an SVG element (circle(), inset(), polygon(), path(), ... plus the reference box).

func ParseSVGClip

func ParseSVGClip(v string) (*SVGClipShape, bool)

ParseSVGClip parses the value of a clip-path property holding a basic shape (not url(#id)) with the style engine's parser, the same one that serves clip-path on HTML elements.

func (*SVGClipShape) Resolve

func (c *SVGClipShape) Resolve(R Rect) ClipSub

Resolve resolves the shape against reference box R.

type SVGDoc

type SVGDoc struct {
	Root *SVGNode
	ByID map[string]*SVGNode
	// Inherit carries inherited SVG properties declared on HTML ancestors of
	// an inline <svg> (fill, stroke, ...).
	Inherit map[string]string
	// IntrW/IntrH are the intrinsic size from width/height (0 = none) and
	// Ratio the viewBox aspect ratio (0 = none).
	IntrW, IntrH, Ratio float64

	// Base is the URL relative references of this scene resolve against; Src
	// the markup of a standalone image (kept to re-evaluate @media for the
	// size it is painted at); depth the nesting level of external documents.
	Base     string
	Src      string
	HasMedia bool
	// contains filtered or unexported fields
}

SVGDoc is a resolved SVG scene.

func ParseSVG

func ParseSVG(markup string) *SVGDoc

ParseSVG parses standalone SVG markup (an .svg file, a data: URI payload or an <img>/canvas source) into a scene. Returns nil when no <svg> root is found. The scene is styled only by its own <style> elements and attributes.

func (*SVGDoc) IntrinsicSize

func (d *SVGDoc) IntrinsicSize() (w, h float64)

IntrinsicSize reports the image's natural size the way <img>/drawImage see it (width/height, else viewBox ratio against 300x150).

type SVGDraw

type SVGDraw struct {
	Dst      Rect
	Doc      *SVGDoc
	Color    Color // computed `color` of the embedding element (currentColor)
	FontSize float64
	Family   string
	Weight   int
	Italic   bool
}

SVGDraw paints an SVG scene. The root's viewBox / preserveAspectRatio map onto Dst (CSS px). This op was added for SVG painting; it is additive.

type SVGFilterRef

type SVGFilterRef struct {
	Doc  *SVGDoc
	Node *SVGNode
	ID   string
}

SVGFilterRef is a resolved url(#id) filter reference.

func LookupSVGFilter

func LookupSVGFilter(name string) (*SVGFilterRef, bool)

LookupSVGFilter resolves a Filter.Name produced for filter: url(#id).

type SVGGlyphPos

type SVGGlyphPos struct {
	X, Y   float64
	Angle  float64
	ScaleX float64
	Adv    float64
	Hidden bool
}

SVGGlyphPos is the placement of one character: the glyph origin on its baseline, its rotation (radians) and horizontal scale.

func LayoutSVGText

func LayoutSVGText(in []SVGTextIn, lens []SVGTextLen) []SVGGlyphPos

LayoutSVGText places characters. lens are the textLength adjustments (inner first).

func LayoutSVGTextVertical

func LayoutSVGTextVertical(in []SVGTextIn, lens []SVGTextLen) []SVGGlyphPos

LayoutSVGTextVertical lays out text whose inline axis is y (writing-mode tb, vertical-rl, vertical-lr): the characters' x and y roles are swapped for the horizontal algorithm. Adv is the advance along y and YOff the offset across (added to x). The positions returned are x across and y along the line.

type SVGNode

type SVGNode struct {
	Tag  string
	A    map[string]string
	Kids []*SVGNode
	Text string

	// External resolution done at layout time through the Env: Img is the
	// decoded raster of an <image>/<feImage> href, Sub the parsed SVG of an
	// external .svg (SubID is the fragment of <use href="other.svg#id">).
	Img   image.Image
	Sub   *SVGDoc
	SubID string
	// Ops is the display list of a <foreignObject>'s HTML content in the
	// object's user space; the rasterizer plays it where the element sits in
	// the SVG paint order, under the ancestors' transforms, clips and effects.
	Ops []Op
	// contains filtered or unexported fields
}

SVGNode is one element of a resolved SVG scene. A holds the element's attributes (lower-cased keys, xlink:href normalised to "href") overlaid by the declarations of the page cascade (author rules, then the style attribute) for every SVG property, so the rasterizer sees one flat map. Text content appears as children with Tag "#text".

type SVGSourcer

type SVGSourcer interface {
	SVGSource(url string) (string, bool)
}

SVGSourcer is an optional Env extension: it returns the markup of an SVG resource (for <img src=*.svg> and CSS backgrounds) when the host has fetched one.

type SVGTextChar

type SVGTextChar struct {
	R          rune
	Node       *SVGNode // innermost content element that holds the character
	Path       *SVGNode // enclosing <textPath>, nil when not on a path
	HasX, HasY bool
	X, Y       float64
	DX, DY     float64
	Rot        float64 // degrees
	// Explicit is set when one of the x/y/dx/dy/rotate lists has a value for
	// this character (Blink then lays it out as a fragment of its own).
	Explicit bool
}

SVGTextChar is one addressable character of a <text> element.

type SVGTextIn

type SVGTextIn struct {
	SVGTextChar
	Adv    float64 // advance including letter and word spacing
	YOff   float64 // baseline offset (dominant/alignment/baseline-shift), positive = down
	Anchor int     // 0 start, 1 middle, 2 end (of the character's own style)
	Space  bool    // the character is whitespace (still advances)
	PathM  *SVGTextPath
}

SVGTextIn describes one character for LayoutSVGText.

type SVGTextLen

type SVGTextLen struct {
	From, To int
	Length   float64
	Glyphs   bool // lengthAdjust=spacingAndGlyphs
}

SVGTextLen is a textLength adjustment over chars [From, To).

type SVGTextPath

type SVGTextPath struct {
	Start float64 // startOffset in path units
	// contains filtered or unexported fields
}

SVGTextPath measures a path for text-on-a-path layout (see svgpathmeasure.go for how Blink and Skia measure).

func NewSVGTextPath

func NewSVGTextPath(d string, k float64) *SVGTextPath

NewSVGTextPath measures the path data d, scaled by k; Start is left zero.

func NewSVGTextPolyline

func NewSVGTextPolyline(contours [][][2]float64) *SVGTextPath

NewSVGTextPolyline builds a path from polylines (one per subpath).

func (*SVGTextPath) At

func (p *SVGTextPath) At(s float64) (x, y, tx, ty float64, ok bool)

At returns the point and unit tangent at distance s along the path.

func (*SVGTextPath) Length

func (p *SVGTextPath) Length() float64

Length is the total length of all contours.

type ScrollCorner

type ScrollCorner struct {
	Rect Rect
	Dark bool
}

ScrollCorner fills the square where two scrollbars meet.

type Scrollbar

type Scrollbar struct {
	Rect     Rect
	Vertical bool
	// Thumb is the thumb's offset from the bar start and its length in px;
	// Len 0 means "no thumb" (nothing to scroll).
	ThumbOff, ThumbLen float64
	Dark               bool
}

Scrollbar paints a classic (non-overlay, 15px) Chromium/Linux scrollbar inside Rect: track, two arrow buttons and a thumb.

type Session

type Session struct {
	Style *style.Persist
	// contains filtered or unexported fields
}

Session carries work from one layout pass over a document to the next: the style engine and computed styles (style.Persist) and resolved inline SVG scenes. The caller (one document's layout provider) owns it and runs one pass at a time. A nil *Session in Options means every pass starts from scratch, which is always correct; a Session must produce results identical to that (SWEEF_LAYOUT_CHECK in internal/engine verifies it).

func NewSession

func NewSession() *Session

NewSession returns an empty session.

type Sheet

type Sheet struct {
	Text      string
	BaseURL   string // for resolving url() references
	Media     string // media query from the <link>/<style> media attribute
	UserAgent bool
}

Sheet is one stylesheet in cascade order.

type TextRun

type TextRun struct {
	X, Y        float64
	Size        float64
	Color       Color
	Glyphs      []Glyph
	Width       float64 // total advance
	Bold        bool    // synthetic bold when the face has no bold variant
	Italic      bool    // synthetic oblique when the face has no italic variant
	Underline   bool
	Overline    bool
	LineThrough bool
	DecoStyle   string // solid, double, dotted, dashed, wavy
	DecoColor   Color
	DecoThick   float64 // text-decoration-thickness in px (0 = auto); additive
	UnderOffset float64 // text-underline-offset in px (0 = auto); additive
	Shadows     []TextShadow
	Stroke      float64 // -webkit-text-stroke width
	StrokeColor Color
}

TextRun draws shaped text. X, Y is the baseline origin.

type TextShadow

type TextShadow struct {
	DX, DY, Blur float64
	Color        Color
}

TextShadow is one text-shadow entry.

type Tile

type Tile struct {
	Origin           [2]float64
	Size             [2]float64
	Step             [2]float64
	RepeatX, RepeatY bool
}

Tile describes background tiling: the image is drawn at Size, repeated every Step starting at Origin, clipped to Dst.

type Xf3D

type Xf3D struct {
	L        [16]float64 // local space -> container space, row-major Mat4
	Preserve bool        // transform-style: preserve-3d is in effect
}

Xf3D is the 3D transform data of a laid-out element for geometry queries.

Jump to

Keyboard shortcuts

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