style

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package style matches CSS rules and computes values for DOM elements.

Index

Constants

View Source
const (
	// MaxAnimationsPerElement bounds comma-list work and retained state.
	MaxAnimationsPerElement = 32
	// MaxActiveAnimations bounds running Animation state for one page.
	MaxActiveAnimations = 4096
)

Variables

This section is empty.

Functions

func InterpolateColor

func InterpolateColor(from, to uint32, progress float64) uint32

InterpolateColor blends packed RRGGBBAA colors in premultiplied sRGB space.

func InterpolateOpacity

func InterpolateOpacity(from, to float32, progress float64) float32

InterpolateOpacity returns the linear interpolation of two computed opacity values. The used value remains in opacity's valid range even when an easing function produces an overshooting progress value.

Types

type Align

type Align uint8

Align controls cross-axis alignment. AlignAuto is only valid for align-self.

const (
	AlignStretch Align = iota
	AlignFlexStart
	AlignFlexEnd
	AlignCenter
	AlignBaseline
	AlignSpaceBetween
	AlignSpaceAround
	AlignSpaceEvenly
	AlignAuto
)

type AnimatedValues

type AnimatedValues map[string]TransitionValue

AnimatedValues stores sampled values by CSS property name.

type AnimationDirection

type AnimationDirection uint8

AnimationDirection controls iteration playback direction.

const (
	AnimationNormal AnimationDirection = iota
	AnimationReverse
	AnimationAlternate
	AnimationAlternateReverse
)

type AnimationFillMode

type AnimationFillMode uint8

AnimationFillMode controls the effect before and after active time.

const (
	AnimationFillNone AnimationFillMode = iota
	AnimationFillForwards
	AnimationFillBackwards
	AnimationFillBoth
)

type AnimationPlayState

type AnimationPlayState uint8

AnimationPlayState controls whether an animation advances.

const (
	AnimationRunning AnimationPlayState = iota
	AnimationPaused
)

type AnimationRegistry

type AnimationRegistry struct {
	// contains filtered or unexported fields
}

AnimationRegistry owns the running animation list for every styled element. Reconcile is called after style recalculation so DOM and interaction changes update animation definitions without restarting an unchanged animation.

func NewAnimationRegistry

func NewAnimationRegistry() *AnimationRegistry

NewAnimationRegistry creates an empty element animation registry.

func (*AnimationRegistry) Active

func (registry *AnimationRegistry) Active(current time.Time) bool

Active reports whether an animation can change on a future frame.

func (*AnimationRegistry) AnimatedStyles

func (registry *AnimationRegistry) AnimatedStyles(underlying Map, stylesheet *css.Stylesheet, current time.Time) Map

AnimatedStyles samples all registered keyframe animations and composites them over the immutable underlying computed styles.

func (*AnimationRegistry) Clear

func (registry *AnimationRegistry) Clear()

Clear discards every running animation owned by the page.

func (*AnimationRegistry) Count

func (registry *AnimationRegistry) Count(nodeID dom.NodeID) int

Count reports the executable animation count for one element.

func (*AnimationRegistry) Reconcile

func (registry *AnimationRegistry) Reconcile(styles Map, current time.Time)

Reconcile updates running animations from newly computed styles.

func (*AnimationRegistry) Sample

func (registry *AnimationRegistry) Sample(nodeID dom.NodeID, current time.Time) []SampledAnimation

Sample evaluates the animations attached to one element.

func (*AnimationRegistry) Total

func (registry *AnimationRegistry) Total() int

Total reports the number of running animations retained for the page.

type AnimationSample

type AnimationSample struct {
	Phase     animationmodel.Phase
	Progress  float64
	Iteration uint64
	Applies   bool
}

AnimationSample is one CSS animation's directed and eased progress.

type AnimationStack

type AnimationStack struct {
	// contains filtered or unexported fields
}

AnimationStack executes the comma-separated animation list of one element in source order. Later entries remain later in the returned samples so they can override earlier entries for the same property.

func NewAnimationStack

func NewAnimationStack(animations []CSSAnimation, start time.Time) *AnimationStack

NewAnimationStack starts every named animation on one shared timestamp.

func (*AnimationStack) Len

func (stack *AnimationStack) Len() int

Len reports the number of executable named animations.

func (*AnimationStack) Sample

func (stack *AnimationStack) Sample(current time.Time) []SampledAnimation

Sample evaluates every animation using the same timestamp and preserves comma-list order.

type AutoEdges

type AutoEdges struct {
	Top, Right, Bottom, Left bool
}

AutoEdges records which margins have the auto keyword.

type BackgroundImage

type BackgroundImage struct {
	Kind           BackgroundImageKind
	URL            string
	GradientAngle  float32
	GradientStops  []GradientStop
	GradientCenter BackgroundPosition
	RadialCircle   bool
}

BackgroundImage is either one URL image or one linear gradient.

type BackgroundImageKind

type BackgroundImageKind uint8

BackgroundImageKind identifies the single background layer supported by Growse.

const (
	BackgroundImageNone BackgroundImageKind = iota
	BackgroundImageURL
	BackgroundImageLinearGradient
	BackgroundImageRadialGradient
)

type BackgroundLayer

type BackgroundLayer struct {
	Image    BackgroundImage
	Repeat   BackgroundRepeat
	Position BackgroundPosition
	Size     BackgroundSize
}

BackgroundLayer groups one image with its layer-specific placement values.

type BackgroundPosition

type BackgroundPosition struct {
	X LengthPercentage
	Y LengthPercentage
}

BackgroundPosition is a position inside the background positioning area.

type BackgroundRepeat

type BackgroundRepeat struct {
	X bool
	Y bool
}

BackgroundRepeat stores repetition independently for each axis.

type BackgroundSize

type BackgroundSize struct {
	Kind   BackgroundSizeKind
	Width  SizeValue
	Height SizeValue
}

BackgroundSize contains the size of the single background layer.

type BackgroundSizeKind

type BackgroundSizeKind uint8

BackgroundSizeKind identifies automatic, intrinsic-ratio, or explicit sizing.

const (
	BackgroundSizeAuto BackgroundSizeKind = iota
	BackgroundSizeCover
	BackgroundSizeContain
	BackgroundSizeExplicit
)

type BorderRadii

type BorderRadii struct {
	TopLeft     RadiusValue
	TopRight    RadiusValue
	BottomRight RadiusValue
	BottomLeft  RadiusValue
}

BorderRadii contains corner radii in clockwise order.

type BorderSide

type BorderSide struct {
	Width float32
	Style BorderStyle
	Color uint32
}

BorderSide contains the computed width, style and color of one side.

type BorderStyle

type BorderStyle uint8

BorderStyle is the line style of one border side.

const (
	BorderNone BorderStyle = iota
	BorderSolid
	BorderDotted
	BorderDashed
	BorderDouble
)

type Borders

type Borders struct {
	Top    BorderSide
	Right  BorderSide
	Bottom BorderSide
	Left   BorderSide
}

Borders contains border sides in CSS clockwise order.

type BoxSizing

type BoxSizing uint8

BoxSizing controls whether declared sizes include padding and border.

const (
	BoxSizingContentBox BoxSizing = iota
	BoxSizingBorderBox
)

type CSSAnimation

type CSSAnimation struct {
	Name       string
	Timing     animation.Timing
	Iterations float64
	Direction  AnimationDirection
	FillMode   AnimationFillMode
	PlayState  AnimationPlayState
}

CSSAnimation is one computed entry from the animation property lists.

func (CSSAnimation) Sample

func (item CSSAnimation) Sample(start, current time.Time) AnimationSample

Sample evaluates delay, iteration count, direction, fill mode, and easing.

type ComputedStyle

type ComputedStyle struct {
	Color               uint32
	BackgroundColor     uint32
	BackgroundImage     BackgroundImage
	BackgroundRepeat    BackgroundRepeat
	BackgroundPos       BackgroundPosition
	BackgroundSize      BackgroundSize
	BackgroundLayers    []BackgroundLayer
	FontSize            float32
	FontWeight          int
	LineHeight          float32
	WhiteSpace          WhiteSpace
	OverflowX           Overflow
	OverflowY           Overflow
	Display             Display
	Visibility          Visibility
	FlexDirection       FlexDirection
	FlexWrap            FlexWrap
	JustifyContent      JustifyContent
	AlignItems          Align
	JustifyItems        Align
	AlignContent        Align
	Order               int
	FlexGrow            float32
	FlexShrink          float32
	FlexBasis           FlexBasis
	AlignSelf           Align
	JustifySelf         Align
	RowGap              LengthPercentage
	ColumnGap           LengthPercentage
	GridTemplateColumns []GridTrackSize
	GridTemplateRows    []GridTrackSize
	GridAutoColumns     []GridTrackSize
	GridAutoRows        []GridTrackSize
	GridColumnLines     map[string][]int
	GridRowLines        map[string][]int
	GridTemplateAreas   map[string]GridArea
	GridColumn          GridPlacement
	GridRow             GridPlacement
	GridAreaName        string
	GridAutoFlow        GridAutoFlow
	Position            Position
	Inset               Insets
	ZIndex              int
	ZIndexAuto          bool
	BoxShadows          []Shadow
	TextShadows         []Shadow
	Outline             BorderSide
	OutlineOffset       float32
	Transform           []TransformFunction
	TransformOrigin     BackgroundPosition
	AspectRatio         float32
	BoxSizing           BoxSizing
	Width               SizeValue
	Height              SizeValue
	MinWidth            SizeValue
	MinHeight           SizeValue
	MaxWidth            SizeValue
	MaxHeight           SizeValue
	Margin              Edges
	MarginAuto          AutoEdges
	Padding             Edges
	Border              Borders
	BorderRadius        BorderRadii
	TextDecoration      TextDecorationLine
	DecorationColor     uint32
	Opacity             float32
	Transitions         []Transition
	Animations          []CSSAnimation
	ImportantProperties map[string]bool
	BeforeContent       string
	AfterContent        string
	CustomProperties    map[string]string
}

ComputedStyle contains the MVP properties consumed by layout and paint.

func ApplyAnimatedCascade

func ApplyAnimatedCascade(underlying ComputedStyle, animations, transitions AnimatedValues) ComputedStyle

ApplyAnimatedCascade composites sampled CSS Animation and Transition values over an underlying computed style. CSS Animations override normal author declarations, author !important overrides Animations, and Transitions override both. The underlying style is not modified.

func ApplyAnimationSample

func ApplyAnimationSample(underlying ComputedStyle, values AnimatedValues, sample AnimationSample) ComputedStyle

ApplyAnimationSample applies an animation effect only while its timing and fill mode say the effect participates in the cascade.

func (ComputedStyle) Bold

func (s ComputedStyle) Bold() bool

Bold reports whether the computed weight should use a bold face.

func (ComputedStyle) Important

func (s ComputedStyle) Important(property string) bool

Important reports whether the winning author declaration for property was marked !important.

type Display

type Display uint8

Display controls whether an element participates in block or inline layout.

const (
	DisplayInline Display = iota
	DisplayBlock
	DisplayInlineBlock
	DisplayNone
	DisplayFlex
	DisplayInlineFlex
	DisplayGrid
	DisplayInlineGrid
)

type Edges

type Edges struct {
	Top    float32
	Right  float32
	Bottom float32
	Left   float32
}

Edges contains resolved pixel values in CSS clockwise order.

type Environment

type Environment struct {
	ViewportWidth  float32
	ViewportHeight float32
	RootFontSize   float32
	ResolutionDPI  float32
	ColorScheme    string
	Hover          bool
	Pointer        string
	ReducedMotion  bool
}

Environment contains rendering metrics needed during value computation.

type FlexBasis

type FlexBasis struct {
	Kind  FlexBasisKind
	Value LengthPercentage
}

FlexBasis retains percentages until the flex container size is known.

type FlexBasisKind

type FlexBasisKind uint8

FlexBasisKind identifies an automatic, content-based, or sized flex basis.

const (
	FlexBasisAuto FlexBasisKind = iota
	FlexBasisContent
	FlexBasisLength
)

type FlexDirection

type FlexDirection uint8

FlexDirection defines the main axis and its direction.

const (
	FlexDirectionRow FlexDirection = iota
	FlexDirectionRowReverse
	FlexDirectionColumn
	FlexDirectionColumnReverse
)

type FlexWrap

type FlexWrap uint8

FlexWrap controls whether flex items form multiple lines.

const (
	FlexNoWrap FlexWrap = iota
	FlexWrapLines
	FlexWrapReverse
)

type GradientStop

type GradientStop struct {
	Color    uint32
	Position float32
}

GradientStop is one color stop in a linear gradient. Position is normalized to the [0, 1] range after omitted stops have been distributed.

type GridArea

type GridArea struct {
	RowStart, RowEnd, ColumnStart, ColumnEnd int
}

GridArea is a zero-based half-open rectangle derived from grid-template-areas.

type GridAutoFlow

type GridAutoFlow struct {
	Column bool
	Dense  bool
}

GridAutoFlow selects the auto-placement major axis and optional backfilling.

type GridAutoRepeat

type GridAutoRepeat uint8

GridAutoRepeat identifies repeat(auto-fill, ...) and repeat(auto-fit, ...).

const (
	GridAutoRepeatNone GridAutoRepeat = iota
	GridAutoRepeatFill
	GridAutoRepeatFit
)

type GridLine

type GridLine struct {
	Index int
	Name  string
	Span  int
}

GridLine selects a numbered/named line or spans tracks from the opposite edge.

type GridPlacement

type GridPlacement struct {
	Start GridLine
	End   GridLine
}

GridPlacement stores the two edges of one grid axis.

type GridTrackKind

type GridTrackKind uint8

GridTrackKind identifies the sizing function used by one grid track.

const (
	GridTrackAuto GridTrackKind = iota
	GridTrackLength
	GridTrackFraction
	GridTrackMinContent
	GridTrackMaxContent
	GridTrackAutoRepeat
)

type GridTrackSize

type GridTrackSize struct {
	Kind          GridTrackKind
	Value         LengthPercentage
	Flex          float32
	MinKind       GridTrackKind
	MinValue      LengthPercentage
	MinSet        bool
	FitLimit      *LengthPercentage
	AutoRepeat    GridAutoRepeat
	RepeatPattern []GridTrackSize
}

GridTrackSize retains track sizing values until the grid container is laid out.

type Insets

type Insets struct {
	Top, Right, Bottom, Left SizeValue
}

Insets stores the four computed inset properties; SizeAuto means auto.

type InteractionState

type InteractionState struct {
	Hovered  map[dom.NodeID]bool
	Focused  dom.NodeID
	Document *dom.Document
}

InteractionState contains transient browser state used by selector matching.

type JustifyContent

type JustifyContent uint8

JustifyContent distributes free space on the main axis.

const (
	JustifyFlexStart JustifyContent = iota
	JustifyFlexEnd
	JustifyCenter
	JustifySpaceBetween
	JustifySpaceAround
	JustifySpaceEvenly
)

type LengthContext

type LengthContext struct {
	FontSize       float32
	RootFontSize   float32
	ViewportWidth  float32
	ViewportHeight float32
	PercentageBase float32
}

LengthContext contains the bases needed to resolve CSS length units.

type LengthPercentage

type LengthPercentage struct {
	Pixels     float32
	Percentage float32
}

LengthPercentage preserves the percentage component until a basis is known.

func ResolveLength

func ResolveLength(value string, context LengthContext) (LengthPercentage, bool)

ResolveLength parses and resolves a CSS3 length or percentage.

func (LengthPercentage) Resolve

func (value LengthPercentage) Resolve(percentageBase float32) float32

Resolve converts a length-percentage to CSS pixels for a concrete basis.

type Map

type Map map[dom.NodeID]ComputedStyle

Map stores computed styles by DOM NodeID.

func Compute

func Compute(document *dom.Document, stylesheet *css.Stylesheet) Map

Compute applies UA defaults, inheritance, selector matching and cascade.

func ComputeWithEnvironment

func ComputeWithEnvironment(document *dom.Document, stylesheet *css.Stylesheet, state InteractionState, environment Environment) Map

ComputeWithEnvironment applies styles using interaction and viewport state.

func ComputeWithState

func ComputeWithState(document *dom.Document, stylesheet *css.Stylesheet, state InteractionState) Map

ComputeWithState applies styles using transient browser interaction state.

func (Map) For

func (m Map) For(node *dom.Node) (ComputedStyle, bool)

For returns a node's computed style and whether one was calculated.

type Matrix

type Matrix struct {
	A, B, C, D, E, F float32
}

Matrix is a CSS 2D affine matrix [A C E; B D F; 0 0 1].

func IdentityMatrix

func IdentityMatrix() Matrix

func ResolveTransform

func ResolveTransform(functions []TransformFunction, width, height float32) Matrix

func (Matrix) Inverse

func (matrix Matrix) Inverse() (Matrix, bool)

Inverse returns the inverse affine matrix when it is non-singular.

func (Matrix) Multiply

func (left Matrix) Multiply(right Matrix) Matrix

func (Matrix) TransformPoint

func (matrix Matrix) TransformPoint(x, y float32) (float32, float32)

TransformPoint maps a point through the matrix.

type Overflow

type Overflow uint8

Overflow controls clipping and scroll-container creation on one axis.

const (
	OverflowVisible Overflow = iota
	OverflowHidden
	OverflowAuto
	OverflowScroll
)

type Position

type Position uint8

Position selects normal, offset, out-of-flow, viewport, or sticky positioning.

const (
	PositionStatic Position = iota
	PositionRelative
	PositionAbsolute
	PositionFixed
	PositionSticky
)

type RadiusValue

type RadiusValue struct {
	X LengthPercentage
	Y LengthPercentage
}

RadiusValue is one possibly elliptical corner radius.

type RunningAnimation

type RunningAnimation struct {
	Animation CSSAnimation
	StartTime time.Time
	// contains filtered or unexported fields
}

RunningAnimation tracks pause time separately from the CSS timing values.

func NewRunningAnimation

func NewRunningAnimation(animation CSSAnimation, start time.Time) *RunningAnimation

NewRunningAnimation creates an animation whose timeline begins at start.

func (*RunningAnimation) Pause

func (running *RunningAnimation) Pause(current time.Time)

Pause holds the current progress. Repeated calls have no effect.

func (*RunningAnimation) Paused

func (running *RunningAnimation) Paused() bool

Paused reports whether timeline progress is currently held.

func (*RunningAnimation) Resume

func (running *RunningAnimation) Resume(current time.Time)

Resume continues from the held progress. Repeated calls have no effect.

func (*RunningAnimation) Sample

func (running *RunningAnimation) Sample(current time.Time) AnimationSample

Sample returns progress without advancing time while paused.

type RunningTransition

type RunningTransition struct {
	StartedTransition
	StartTime                 time.Time
	Current                   TransitionValue
	ReversingAdjustedStart    TransitionValue
	ReversingShorteningFactor float64
}

RunningTransition retains the state needed to sample and interrupt one CSS transition without writing animated values back to author style.

func NewRunningTransition

func NewRunningTransition(started StartedTransition, frameTime time.Time) *RunningTransition

NewRunningTransition starts a transition at frameTime.

func (*RunningTransition) Advance

func (running *RunningTransition) Advance(frameTime time.Time) (TransitionValue, bool)

Advance samples the current value and reports whether the transition remains active.

func (*RunningTransition) Interrupt

func (running *RunningTransition) Interrupt(frameTime time.Time, target TransitionValue, timing animation.Timing)

Interrupt starts a replacement transition from the currently displayed value. Returning to the reversing-adjusted start shortens the new duration.

type SampledAnimation

type SampledAnimation struct {
	Name   string
	Sample AnimationSample
}

SampledAnimation associates a named list entry with its current sample.

type Shadow

type Shadow struct {
	Inset                  bool
	OffsetX, OffsetY, Blur float32
	Spread                 float32
	Color                  uint32
}

Shadow is one box-shadow or text-shadow layer.

type SizeKind

type SizeKind uint8

SizeKind identifies auto, a length-percentage, or an unbounded maximum.

const (
	SizeAuto SizeKind = iota
	SizeLength
	SizeNone
)

type SizeValue

type SizeValue struct {
	Kind  SizeKind
	Value LengthPercentage
}

SizeValue is a computed sizing property which still may contain a percentage.

type StartedTransition

type StartedTransition struct {
	NodeID   dom.NodeID
	Property string
	From     TransitionValue
	To       TransitionValue
	Timing   animation.Timing
}

StartedTransition describes a transition created by a computed-style change.

func StartTransitions

func StartTransitions(previous, next Map) []StartedTransition

StartTransitions compares two computed-style snapshots and creates the transitions selected by the new snapshot. It does not mutate either map.

type TextDecorationLine

type TextDecorationLine uint8

TextDecorationLine is a bit set of line decorations.

const (
	TextDecorationNone        TextDecorationLine = 0
	TextDecorationUnderline   TextDecorationLine = 1 << 0
	TextDecorationOverline    TextDecorationLine = 1 << 1
	TextDecorationLineThrough TextDecorationLine = 1 << 2
)

type TransformFunction

type TransformFunction struct {
	Kind             TransformFunctionKind
	X, Y             LengthPercentage
	A, B, C, D, E, F float32
}

TransformFunction retains percentage translations until box geometry is known.

func InterpolateTransform

func InterpolateTransform(from, to []TransformFunction, progress float64, width, height float32) []TransformFunction

InterpolateTransform interpolates two computed 2D transform lists. Missing functions are padded with the corresponding identity function. When the function kinds differ, the remaining suffixes are resolved and interpolated through decomposed affine matrices.

type TransformFunctionKind

type TransformFunctionKind uint8

TransformFunctionKind identifies a parsed CSS 2D transform function.

const (
	TransformTranslate TransformFunctionKind = iota
	TransformScale
	TransformRotate
	TransformSkew
	TransformMatrix
)

type Transition

type Transition struct {
	Property string
	Timing   animation.Timing
}

Transition is one computed CSS transition matched to a property.

type TransitionRegistry

type TransitionRegistry struct {
	// contains filtered or unexported fields
}

TransitionRegistry owns the transitions started by computed-style changes on one page. Author styles remain immutable while sampled values are composited at frame time.

func NewTransitionRegistry

func NewTransitionRegistry() *TransitionRegistry

NewTransitionRegistry creates an empty page transition registry.

func (*TransitionRegistry) Active

func (registry *TransitionRegistry) Active(current time.Time) bool

Active reports whether a transition can change on a future frame.

func (*TransitionRegistry) Apply

func (registry *TransitionRegistry) Apply(styles Map, current time.Time) Map

Apply samples transitions and composites them after CSS Animations.

func (*TransitionRegistry) Clear

func (registry *TransitionRegistry) Clear()

Clear discards every running transition owned by the page.

func (*TransitionRegistry) Count

func (registry *TransitionRegistry) Count(nodeID dom.NodeID) int

Count reports the transitions retained for an element.

func (*TransitionRegistry) Reconcile

func (registry *TransitionRegistry) Reconcile(previous, next Map, current time.Time)

Reconcile starts, interrupts, or cancels transitions after style recalculation. Initial style calculation must not call this method with a nil previous map.

type TransitionValue

type TransitionValue struct {
	Kind      TransitionValueKind
	Number    float32
	Color     uint32
	Transform []TransformFunction
}

TransitionValue is one supported computed value captured at a style change.

type TransitionValueKind

type TransitionValueKind uint8

TransitionValueKind identifies the representation used for interpolation.

const (
	TransitionNumber TransitionValueKind = iota
	TransitionColor
	TransitionTransform
)

type Visibility

type Visibility uint8

Visibility controls painting and hit testing while preserving layout.

const (
	VisibilityVisible Visibility = iota
	VisibilityHidden
)

type WhiteSpace

type WhiteSpace uint8

WhiteSpace controls collapsing, newline preservation and wrapping.

const (
	WhiteSpaceNormal WhiteSpace = iota
	WhiteSpaceNowrap
	WhiteSpacePre
	WhiteSpacePreWrap
	WhiteSpacePreLine
)

Jump to

Keyboard shortcuts

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