Documentation
¶
Overview ¶
Package style implements the CSS side of Sweef's renderer: parsing of stylesheets, selector matching (via internal/net), the cascade, inheritance and computed values for the properties that affect layout and paint, plus a Chromium-faithful user-agent stylesheet.
Index ¶
- Constants
- func Blockify(d string) string
- func HashMix(h, v uint64) uint64
- func HashString(h uint64, s string) uint64
- func MediaMatches(q string, env *Env) bool
- func NewFaceDesc(family, src string, props map[string]string) (font.FaceDesc, error)
- func Supports(name, val string) bool
- func SupportsCond(c string) bool
- type BasicShape
- type BgLayer
- type BgPos
- type Calc
- type ClipPathVal
- type Color
- type Computed
- type ContCond
- type ContSize
- type ContentItem
- type CounterOp
- type Decl
- type Engine
- func (e *Engine) Anonymous(parent *Computed, display string) *Computed
- func (e *Engine) Compute(n *html.Node, parent *Computed, pseudo string) *Computed
- func (e *Engine) ContainerNodes() []*html.Node
- func (e *Engine) HasContainerQueries() bool
- func (e *Engine) InitialStyle() *Computed
- func (e *Engine) SetContainerSizes(m map[*html.Node]ContSize)
- func (e *Engine) SetWebFonts(w *font.WebSet)
- type Entry
- type EntryIndex
- type Env
- type FilterFn
- type FontFace
- type Gradient
- type GridLine
- type Image
- type Inherited
- type LenKind
- type Length
- type MaskLayer
- type Origin
- type Parsed
- type Persist
- type Rule
- type ScopeCond
- type Shadow
- type SheetIn
- type SizeKind
- type Stop
- type Sz
- type TOp
- type Track
- type TrackList
Constants ¶
const ( DecoUnderline = 1 DecoOverline = 2 DecoLineThrough = 4 )
Underline etc. bits for TextDecorLine.
const FNVOffset = fnvOff
FNVOffset is the starting value for HashString chains.
const (
FlagSelfShadow = 1 << iota
)
Flags bits.
Variables ¶
This section is empty.
Functions ¶
func HashString ¶
HashString and HashMix expose the cache's hashing to callers that derive keys from NodeKey.
func MediaMatches ¶
MediaMatches evaluates a media query list.
func NewFaceDesc ¶
NewFaceDesc builds a descriptor the way the FontFace constructor does: the family, the src descriptor text (empty when the source is binary data) and the descriptors keyed by their CSS names ("font-weight", "unicode-range", ...). An invalid value is reported as an error (SyntaxError in script).
Types ¶
type BasicShape ¶
type BasicShape struct {
Kind string // inset, circle, ellipse, polygon, path, rect, xywh
// inset / rect / xywh: edges. inset: top right bottom left offsets;
// rect(): top right bottom left (auto = LAuto); xywh(): x y width height.
Edges [4]Length
Round [4][2]Length // corner radii tl tr br bl (horizontal, vertical)
HasRound bool
// circle: R[0]; ellipse: R[0], R[1]. RKw holds closest-side / farthest-side.
R [2]Length
RKw [2]string
Pos [2]Length // center, resolved against the reference box (percent of its size)
Pts [][2]Length
D string // path() data
Evenod bool
}
BasicShape is a clip-path <basic-shape>.
type BgLayer ¶
type BgLayer struct {
Image Image
PosX Length // LPct/LPx/LCalc; resolved against container-image
PosY Length
SizeKind string // "", cover, contain
SizeW Length // auto allowed
SizeH Length
RepeatX string // repeat | no-repeat | space | round
RepeatY string
Origin string // border-box | padding-box | content-box
Clip string // border-box | padding-box | content-box | text
Attach string // scroll | fixed | local
RepeatSet bool
Blend string
}
BgLayer is one background layer.
type BgPos ¶
type BgPos struct{ Pct, Px float64 }
BgPos is one axis of background-position: Pct of (container-image) plus Px.
type Calc ¶
type Calc struct {
Op byte // 0 leaf length, 'n' number, '+', '-', '*', '/', 'm' min, 'M' max, 'c' clamp
Px float64
Pct float64
A, B *Calc
List []*Calc
Fn string // Op 'F': math function name
Strat string // round() strategy
// contains filtered or unexported fields
}
Calc is a calc()/min()/max()/clamp() expression tree.
type ClipPathVal ¶
type ClipPathVal struct {
Shape *BasicShape
URL string // url(...) reference (usually "#id")
Box string // geometry box: "" (= border-box), margin-box, border-box, padding-box, content-box, fill-box, stroke-box, view-box
}
ClipPathVal is a computed clip-path.
type Computed ¶
type Computed struct {
Inherited
Display string
UnicodeBidi string // normal | embed | isolate | bidi-override | isolate-override | plaintext
Position string
Float string
Clear string
BoxSizing string
OverflowX, OverflowY string
Contain string
ContentVisibility string // visible | hidden | auto
// CVSkip is set by layout (never by the cascade) on a content-visibility:auto
// element whose contents are not relevant to the user and so are skipped.
CVSkip bool
QuirkMarginTop bool // quirks mode: margin-top comes from the UA sheet of p, h1, ul ... (ignored at the start of body/td)
QuirkMarginBottom bool
BreakBefore string // auto | avoid | column | page ...
BreakAfter string
BreakInside string // auto | avoid
CIntrW, CIntrH Length // contain-intrinsic-width/height (LNone when unset)
CIntrAutoW bool
CIntrAutoH bool
Isolation string
Appearance string
Resize string
Scrollbar string // scrollbar-width: auto | thin | none
ScrollbarGutter string
OverflowClipMargin float64
Width, Height, MinWidth, MinHeight, MaxWidth, MaxHeight Length
Margin [4]Length // top right bottom left
Padding [4]Length
Inset [4]Length // top right bottom left
AspectRatio float64 // 0 = auto
AspectAuto bool // "auto <ratio>"
BorderWidth [4]float64
BorderStyle [4]string
BorderColor [4]Color
Radius [4][2]Length // tl tr br bl; [h v]
BorderImage bool
OutlineWidth float64
OutlineStyle string
OutlineColor Color
OutlineOffset float64
ZIndex int
ZAuto bool
BgColor Color
BgLayers []BgLayer
BoxShadow []Shadow
Opacity float64
OpacitySet bool
Transform []TOp
TransformOrigin [2]Length
TOriginZ float64
Translate, Rotate, Scale []TOp
Perspective float64
PerspectiveOrigin [2]Length // perspective-origin (default 50% 50%)
TransformStyle string // "" (flat) or "preserve-3d"
BackfaceHidden bool // backface-visibility: hidden
TransformBox string // transform-box: "" (view-box / border-box per element), content-box, border-box, fill-box, stroke-box, view-box
Filter []FilterFn
BackdropFilter []FilterFn
MixBlend string
ClipPath bool
ClipPathV *ClipPathVal // parsed clip-path (nil = none)
Mask []MaskLayer // mask layers (first = top-most)
WillChange string
MaskImage bool
VerticalAlign string // baseline sub super top text-top middle bottom text-bottom length
VerticalAlignLen Length
TextDecorLine uint8 // bit0 underline bit1 overline bit2 line-through
TextDecorStyle string
TextDecorColor Color
DecorCur bool
TextOverflow string
ObjectFit string
ObjectPos [2]Length
ListMarkerIsNone bool
// flex
FlexDirection string
FlexWrap string
FlexGrow float64
FlexShrink float64
FlexBasis Length
Order int
JustifyContent, AlignItems, AlignSelf, AlignContent, JustifyItems, JustifySelf string
RowGap, ColumnGap Length
BoxOrient string // -webkit-box-orient
// grid
GridCols, GridRows TrackList
GridAutoCols, GridAutoRows []Track
GridAutoFlow string
GridAreas [][]string
GridRowStart, GridRowEnd GridLine
GridColStart, GridColEnd GridLine
// table
TableLayout string
// containment
ContainerType string // "" / normal, size, inline-size
ContainerName []string // container-name idents
// multi-column
ColumnCount int
ColumnWidth Length
ColumnRuleW float64
ColumnRuleStyle string
ColumnRuleColor Color
ColumnFill string
BoxDecorationBreak string // slice (default, empty) | clone
ColumnSpan string
// generated content
Content []ContentItem
ContentSet bool // content specified (not normal)
ContentNone bool
CounterReset, CounterIncr, CounterSet []CounterOp
// internal helpers
Zoom float64
Flags uint32
OrigInline bool
// contains filtered or unexported fields
}
Computed is the computed style of an element or pseudo-element.
func Initial ¶
func Initial() *Computed
Initial returns the root's parent: the initial values of all properties.
func (*Computed) CVSkipped ¶
CVSkipped reports whether the element's contents are skipped: content-visibility: hidden, or auto while not relevant to the user.
func (*Computed) ContainsBlockSize ¶
ContainsBlockSize reports block-size containment.
func (*Computed) ContainsInlineSize ¶
ContainsInlineSize reports inline-size containment (container-type inline-size/size, contain: size / inline-size / strict, content-visibility hidden).
func (*Computed) ContainsLayout ¶
ContainsLayout reports layout containment (independent formatting context, containing block for positioned descendants).
func (*Computed) Transposed ¶
Transposed returns a copy of c as seen from the logical (flow-relative) frame of a vertical writing mode: the box is laid out by the horizontal engine with width and height, margins, paddings, borders and offsets exchanged. mode is VerticalMode() (1 rl, 2 lr).
func (*Computed) VerticalMode ¶
VerticalMode returns 0 for horizontal writing modes, 1 for vertical-rl and sideways-rl, 2 for vertical-lr and sideways-lr.
type ContCond ¶
ContCond is the condition of one @container rule (conditions of nested @container blocks are chained through Outer).
type ContSize ¶
type ContSize struct{ W, H float64 }
ContSize is the content-box size of a query container.
type ContentItem ¶
type ContentItem struct {
K string // str, attr, counter, counters, open-quote, close-quote, no-open-quote, no-close-quote, url
S string
Sep string
Style string
}
ContentItem is one piece of the content property.
type Decl ¶
type Decl struct {
Name string
Val string
L string // lower-cased Val (shared with Val when already lower)
Imp bool
}
Decl is one declaration. Name is lower-cased (except custom properties).
type Engine ¶
type Engine struct {
Fonts []FontFace
SysFont string
Quirks bool
RootFont float64
// contains filtered or unexported fields
}
Engine matches rules and computes styles for one document.
func NewEngineQ ¶
NewEngineQ is NewEngine with an optional quirks-mode user-agent sheet.
func (*Engine) Compute ¶
Compute returns the style of element n (pseudo "" ) or of one of its pseudo-elements. parent is the parent element's computed style (nil for the root). A nil result for a pseudo means no rule applies.
func (*Engine) ContainerNodes ¶
ContainerNodes returns the elements that are query containers.
func (*Engine) HasContainerQueries ¶
HasContainerQueries reports whether any @container rule was parsed.
func (*Engine) InitialStyle ¶
Initial returns the engine's initial-values style (parent of the root).
func (*Engine) SetContainerSizes ¶
SetContainerSizes supplies the content-box sizes of query containers from a previous layout pass.
func (*Engine) SetWebFonts ¶
SetWebFonts attaches the document's web font set: from now on the family names of font-family declarations that the set declares are replaced by their scoped form (font.WebSet.Scope), which is how layout and painting find the right faces of the right document. nil detaches.
type Entry ¶
type Entry struct {
Sel snet.SelectorEntry
Spec uint32
Pseudo string // "", before, after, marker, first-line, first-letter, placeholder, ...
Rule *Rule
// contains filtered or unexported fields
}
Entry is one comma-separated selector alternative of a rule.
type EntryIndex ¶
type EntryIndex struct {
// contains filtered or unexported fields
}
EntryIndex buckets the entries of a rule list by the id, class or tag of their rightmost compound selector, like the Engine does, so that code running its own cascade (the SVG scene builder) only matches the selectors that can apply to a node instead of every rule of the page.
func NewEntryIndex ¶
func NewEntryIndex(rules []*Rule) *EntryIndex
NewEntryIndex indexes the entries of rules.
func (*EntryIndex) Candidates ¶
func (ix *EntryIndex) Candidates(n *html.Node, out []*Entry) []*Entry
Candidates appends to out every entry that can match n (a superset: the caller still runs the selector).
type Env ¶
type Env struct {
Width, Height float64
DPR float64
ColorScheme string // light | dark
Print bool
ReducedMotion bool
}
Env describes the environment media queries and viewport units see.
type FontFace ¶
type FontFace struct {
Family string
Weight string
Style string
Src string
// Desc holds every descriptor parsed (fontface.go); source URLs are
// relative to the stylesheet.
Desc font.FaceDesc
}
FontFace is a parsed @font-face block.
func ParseFontFaces ¶
ParseFontFaces returns the @font-face rules of one stylesheet text whose conditions (@media, @supports) hold in env, in order. Source URLs are as written (relative to the stylesheet).
type Gradient ¶
type Gradient struct {
Kind string // linear, radial, conic
Repeating bool
// linear
Angle float64
ToCorner string // "top right" etc. when the direction is a corner keyword
// radial
Shape string // circle | ellipse
Extent string // closest-side farthest-side closest-corner farthest-corner (default farthest-corner)
RadiusX Length // explicit radii (circle uses RadiusX)
RadiusY Length
HasSize bool
Pos [2]Length // center (radial/conic) as lengths relative to the box (pct or px)
HasPos bool
From float64 // conic start angle
Stops []Stop
}
Gradient is a parsed CSS gradient image.
type Inherited ¶
type Inherited struct {
Color Color
FontFamily []string
FontSize float64
FontSizeKw int8
FontAbs bool
FontWeight int
FontStyle uint8 // 0 normal 1 italic 2 oblique
SmallCaps bool
FontStretch float64
LineHeight Length // LAuto = normal; LNumber multiplier; LPx absolute; LPct of font size (resolved to LPx)
LetterSpacing float64
WordSpacing float64
TextAlign string
TextAlignLast string
TextIndent Length
TextIndentHang bool
TextTransform string
WhiteSpace string
WordBreak string
OverflowWrap string
LineBreak string
Hyphens string
TextWrap string // wrap | nowrap | balance | pretty
Direction string
Visibility string
Cursor string
PointerEvents string
ListStyleType string
ListStylePos string
ListStyleImage Image
Quotes [][2]string
BorderCollapse bool
SpacingH float64
SpacingV float64
CaptionSide string
EmptyCellsHide bool
TabSize float64
TabSizePx bool
TextShadow []Shadow
TextFill Color
TextFillSet bool
TextStrokeW float64
TextStrokeC Color
TextStrokeSet bool
FontKerning string
TextRendering string
FontVariantNum string
FontLigOff bool // font-variant-ligatures: none / font-feature-settings "liga" 0 (render text shaping)
UserSelect string
ScrollBehavior string // auto | smooth
OverscrollX string // auto | contain | none
OverscrollY string
WritingMode string
TextOrientation string // mixed | upright | sideways
VertFrame int8 // set on transposed copies: the vertical mode of the original box
TextUnderlineOffset Length
TextDecorationThickness Length
TextUnderlinePos string
ColorScheme string
AccentColor Color
AccentSet bool
Custom map[string]string
ImageRendering string
LineClamp int
Orphans int
Widows int
CaretColor Color
CaretSet bool
}
Inherited holds inherited properties.
type Length ¶
Length is a CSS <length-percentage> or keyword. Absolute units are resolved to px at computed-value time; percentages are kept for layout.
func (Length) IsIntrinsic ¶
IsIntrinsic reports min-content / max-content / fit-content.
type MaskLayer ¶
type MaskLayer struct {
BgLayer
Mode string // match-source (default), alpha, luminance
Composite string // add (default), subtract, intersect, exclude
}
MaskLayer is one mask layer: a background-like layer plus the mask mode and compositing operator.
type Parsed ¶
Parsed is the result of parsing one stylesheet text.
func ParseSheet ¶
ParseSheet parses CSS text. order is a shared counter that gives rules a global source order across sheets; layers is shared between sheets so @layer ordering is document-wide.
type Persist ¶
type Persist struct {
// Stats (tests, SWEEF_STAGES): elements answered from the cache / computed.
Hits, Misses int
// contains filtered or unexported fields
}
persist.go: computed styles that survive from one layout pass to the next.
A layout pass used to build a style engine and compute the style of every element from scratch. For a page that changes a little at a time (typing in the browser's own chrome page) nearly all of that work repeats an identical answer. Persist keeps the engine (parsed sheets, rule index, sharing table) and the computed style of each element, and reuses an element's style when nothing it can depend on has changed:
- the element's own tag and the attributes some selector or presentational hint can read (the "relevant" attributes, derived from the rules);
- the same attributes of every ancestor (selectors with descendant and child combinators, table hints), folded into a chain value A;
- the parent's computed style, by identity (inheritance, em/rem);
- when some selector uses sibling combinators or structural pseudo-classes (:nth-child, :first-child, + ~ ...), the identity and relevant attributes of all the element children of its parent; when a selector uses them on an ancestor-side compound, those of every ancestor's siblings too;
- whether it has children, when :empty is used.
Nothing here observes mutations: a pass recomputes these values from the tree it is given, so a change that bypasses any DOM notification is still seen. Documents whose rules use :has(), :scope, @scope or @container are not cached (the engine is rebuilt every pass, as before), and so are documents that declare container-type. SWEEF_LAYOUT_CHECK=1 compares every pass with a from-scratch one.
func NewPersist ¶
func NewPersist() *Persist
NewPersist returns an empty cache. It is used by one document's layout provider, which runs one pass at a time.
func (*Persist) Acquire ¶
Acquire returns the engine for a pass over a document with these inputs and starts the pass. The engine is the previous one when the inputs are the same. Its Compute answers from the cache when it can.
func (*Persist) EndPass ¶
func (p *Persist) EndPass()
EndPass releases entries of nodes the last pass did not reach.
func (*Persist) NodeKey ¶
NodeKey identifies everything the cascade saw when it last computed the style of element n in the current pass: anc covers its ancestors, own the element itself (and its siblings when selectors use them). Equal keys (and an equal parent style) mean the same style. ok is false when n was not computed in this pass or the cache is not in use.
func (*Persist) SetWebFonts ¶
SetWebFonts says which web font set the next passes resolve family names against. Computed styles hold the scoped family names of the set (see Engine.scopeFamilies), so the cache is dropped whenever the set or the families it declares change; a font merely finishing loading does not.
type Rule ¶
type Rule struct {
Decls []Decl
Entries []*Entry
Origin Origin
Layer int // 0 unlayered; larger = later layer
Cont *ContCond
Scope *ScopeCond
Order int
// contains filtered or unexported fields
}
Rule is a style rule with its declarations.
type ScopeCond ¶
type ScopeCond struct {
Root, Limit *snet.Selector // Root nil: the document root
Outer *ScopeCond
}
ScopeCond is the condition of rules inside an @scope block.
type Shadow ¶
type Shadow struct {
DX, DY, Blur, Spread float64
Color Color
Inset bool
// contains filtered or unexported fields
}
Shadow is one box-shadow or text-shadow.
type Stop ¶
type Stop struct {
Color Color
Cur bool
Pos Length
HasPos bool
Hint bool // a color hint (position only)
}
Stop is a gradient color stop.
type TOp ¶
type TOp struct {
Fn string // matrix, translate, translateX, translateY, scale, scaleX, scaleY, rotate, skew, skewX, skewY, translate3d...
A [6]Length
N int
M *[16]float64 // matrix3d: the 16 values in CSS (column-major) order
}
TOp is one transform function.
type TrackList ¶
type TrackList struct {
Pre, Rep, Post []Track
RepMode string // "", fill, fit
RepCount int
EndNames []string // line names after the last track
RepEndNames []string // line names after the repeat group's last track
None bool
Subgrid bool
}
TrackList is a grid-template-columns/rows value.