Documentation
¶
Overview ¶
Package style is lys-ui's CSS engine: a tokenizer and parser for the GTK-flavored subset docs/css.md scopes, the rule index, and the matcher/cascader that computes one widget's style — custom properties with var() substitution, calc(), color-mix(), and per-longhand cascade across prioritized stylesheets and per-widget inline declarations. It knows nothing about widgets; the widget package fills the Target, walks the tree, and layers the result over the typed Theme.
The error policy is CSS's: a malformed declaration drops that declaration, a malformed selector drops that rule, an unknown at-rule drops its block, and everything around them still applies. A declaration whose var() references make it invalid is invalid at computed-value time and behaves as `unset`. Warnings go to the injected library logger at Warn, silent by default — the same contract as SetTheme's contrast warnings.
Index ¶
- Constants
- Variables
- func Changed(a, b *Values, p Prop) (changed, known bool)
- func Compose(dst, under *Values, p Prop)
- func Compute(layers []Layer, n Node, parent, old *Values, env Env, sc *Scratch, v *Values)
- func ComputePseudo(layers []Layer, n Node, parent *Values, env Env, sc *Scratch, v *Values, ...) bool
- func CopyLonghand(dst, src *Values, p Prop)
- func FileImport(ref, base string) (string, string, error)
- func Interpolate(dst, a, b *Values, p Prop, t float64)
- func NamedColor(name string) (render.Color, bool)
- func SetParseWarn(f func(msg string))
- func SetSystemColors(s SystemColors)
- func Smooth(a, b *Values, p Prop) bool
- func Warn(msg string)
- type AnimLists
- type Animation
- type Appearance
- type Attr
- type AutoTracks
- type AxisPos
- type Background
- type Block
- type BorderImage
- type BorderImageLen
- type BorderImageLenKind
- type BorderStyle
- type BoxAlign
- type BoxAlignKind
- type BoxSizing
- type CaretShape
- type Clear
- type ClipShape
- type ClipShapeKind
- type Container
- type ContainerType
- type Corners
- type CounterEntry
- type CounterScope
- type CursorSpec
- type Display
- type Env
- type FlexDirection
- type FlexWrap
- type Float
- type FontFace
- type FontMetrics
- type FontPalette
- type FontSynthesis
- type FontVariantAlternates
- type FontVariantCaps
- type FontVariantEastAsian
- type FontVariantLigatures
- type FontVariantNumeric
- type FontVariantPosition
- type Gradient
- type GradientStop
- type GridArea
- type GridAreas
- type GridAutoFlow
- type GridLine
- type GridLineKind
- type HyphensK
- type ImageLayer
- type ImageSource
- type ImportResolver
- type Keyframe
- type Keyframes
- type Layer
- type LayerAttachment
- type LayerBox
- type LayerLength
- type LayerRepeat
- type LayerSize
- type LayerSizeKind
- type Layout
- type LayoutMotion
- type Length
- type LineBreakK
- type LineSpan
- type Mask
- type Media
- type Node
- type NumVal
- type Overflow
- type OverflowWrapK
- type Overscroll
- type PointerEvents
- type Position
- type Prop
- type PropSet
- func (s PropSet) And(o PropSet) PropSet
- func (s PropSet) AndNot(o PropSet) PropSet
- func (s PropSet) Each(fn func(Prop))
- func (s PropSet) Empty() bool
- func (s PropSet) Has(p Prop) bool
- func (s PropSet) Or(o PropSet) PropSet
- func (s PropSet) With(p Prop) PropSet
- func (s PropSet) Without(p Prop) PropSet
- type PropertyReg
- type RepeatKind
- type Scalars
- type Scratch
- type Sensitivity
- type Shadow
- type Shadows
- type Sheet
- type Sides
- type Sizing
- type SizingKind
- type SnapAlign
- type SnapAlignK
- type SnapAxis
- type SnapType
- type State
- type SystemColors
- type Target
- type TextAlign
- type TextOverflowK
- type TextTransform
- type TileKind
- type Timing
- type TouchAction
- type TrackBreadth
- type TrackKind
- type TrackList
- type TrackRun
- type TrackSize
- type Transition
- type TransitionTarget
- type TransitionTiming
- type UnicodeBidi
- type UnitReads
- type UserSelect
- type Values
- func (v *Values) Declares(p Prop) bool
- func (v *Values) EffBorder() Sides
- func (v *Values) EffOutline() int
- func (v *Values) Equal(o *Values) bool
- func (v *Values) Has(p Prop) bool
- func (v *Values) HasAny(ps ...Prop) bool
- func (v *Values) Origin() (frac, px [2]float64)
- func (v *Values) UsedBorderImage() BorderImage
- func (v *Values) Var(name string) (string, bool)
- type Vars
- type VerticalAlignK
- type Visibility
- type WhiteSpace
- type WordBreak
- type WritingMode
- type Xform
- type XformOp
- type XformPart
Examples ¶
Constants ¶
const ( DirNormal uint8 = iota DirReverse DirAlternate DirAlternateReverse )
The animation-direction values.
const ( FillNone uint8 = iota FillForwards FillBackwards FillBoth )
The animation-fill-mode values.
const ( CompReplace uint8 = iota CompAdd CompAccumulate )
The animation-composition values.
const ( PriorityFallback = 1 PriorityTheme = 200 PrioritySettings = 400 PriorityApplication = 600 PriorityUser = 800 )
Priorities, GTK's STYLE_PROVIDER_PRIORITY_* values.
const ( BarWidthAuto uint8 = iota BarWidthThin BarWidthNone )
The scrollbar-width values.
const ( GutterStable uint8 = 1 << iota GutterBothEdges )
The scrollbar-gutter flags: Stable reserves the bar's space even without overflow, BothEdges reserves a matching space on the opposite edge too.
const GridLineLimit = 10000
GridLineLimit bounds grid line numbers and track counts, as browsers clamp them: a placement past it clamps to it and a repeat() expanding past it stops there, so a stylesheet cannot ask for unbounded grids.
const MaxLinearPts = 8
MaxLinearPts bounds a linear() point list; points past it are dropped with a warning, like the gradient stop budget.
const MaxResolvedStops = MaxStops * hintSteps
MaxResolvedStops bounds Gradient.Resolve's output: a hint expands into hintSteps-1 stops.
const MaxShadows = 4
MaxShadows bounds the box-shadow list; later layers past it are dropped with a warning. Four covers every stacked-elevation idiom.
const MaxStops = 16
MaxStops bounds a gradient's color stops and color hints; a double-position stop counts twice.
Variables ¶
var ( TimingLinear = Timing{X1: 0, Y1: 0, X2: 1, Y2: 1} TimingEase = Timing{X1: 0.25, Y1: 0.1, X2: 0.25, Y2: 1} TimingEaseIn = Timing{X1: 0.42, Y1: 0, X2: 1, Y2: 1} TimingEaseOut = Timing{X1: 0, Y1: 0, X2: 0.58, Y2: 1} TimingEaseInOut = Timing{X1: 0.42, Y1: 0, X2: 0.58, Y2: 1} )
The named timing functions (CSS Easing 2 §2.2, §2.3).
var LayoutProps = setOf(PropDisplay, PropPosition, PropTop, PropRight, PropBottom, PropLeft, PropZIndex, PropWidth, PropHeight, PropMinWidth, PropMinHeight, PropMaxWidth, PropMaxHeight, PropBoxSizing, PropAspectRatio, PropFlexDirection, PropFlexWrap, PropJustifyContent, PropAlignItems, PropAlignSelf, PropAlignContent, PropFlexGrow, PropFlexShrink, PropFlexBasis, PropOrder, PropRowGap, PropColumnGap, PropOverflowX, PropOverflowY, PropVisibility, PropFloat, PropClear).Or(gridContainerProps).Or(setOf(PropGridColumnStart, PropGridColumnEnd, PropGridRowStart, PropGridRowEnd, PropJustifyItems, PropJustifySelf, PropObjectFit, PropObjectPosition))
LayoutProps are the longhands of the Layout group.
var XformIdentity = Xform{M: render.Identity, P: render.Identity3, /* contains filtered or unexported fields */}
XformIdentity moves nothing.
Functions ¶
func Changed ¶
Changed reports whether p's computed value differs between a and b, for the longhands a transition can carry — the smooth ones and the discrete ones allow-discrete flips; known is false for the rest.
func Compose ¶
Compose joins the effect value of p in dst onto the underlying value under by additive composition (css-animations-2 §4.1: add and accumulate agree on these value types): numbers and lengths sum, colors add per channel, transforms append the effect's functions. A longhand that does not add keeps the effect value, the replace composition.
func Compute ¶
Compute runs the cascade for n: match every layer (and n's inline block), resolve the node's custom properties over parent's, substitute var() and parse the winning declarations, then inherit the unset inherited longhands from parent. parent is nil at the root. old, when non-nil, is the node's previous result: an unchanged custom-property environment keeps its old pointer so equality stays cheap.
func ComputePseudo ¶
func ComputePseudo(layers []Layer, n Node, parent *Values, env Env, sc *Scratch, v *Values, name string) bool
ComputePseudo is Compute for one pseudo-element (::before, ::after) of n: only the rules addressing that pseudo-element cascade, and the result inherits from parent, the element's own computed style. A content declaration's quote keywords move the element's inherited quote depth, so descendants' open-quote continues the count. It reports whether any rule addressed the pseudo-element: without one, v holds only what it inherited, and the pseudo-element draws nothing.
func CopyLonghand ¶
CopyLonghand copies longhand p's computed value from src to dst, whether src sets it included.
func FileImport ¶
FileImport is the default resolver: the filesystem, relative to the importing file's directory.
func Interpolate ¶
Interpolate writes longhand p's value at progress t between a (t=0) and b (t=1) into dst and marks it set: smoothly where p interpolates, else discretely, flipping at t = 0.5 (a side that does not declare p then leaves it unset). An endpoint that does not declare a smooth longhand reads its initial value.
func NamedColor ¶
NamedColor is the CSS named color name (lowercase), as markup languages that share the table (Pango's) resolve them.
func SetParseWarn ¶
func SetParseWarn(f func(msg string))
SetParseWarn installs f as the parse-warning sink; nil restores the library logger. One sink per process, like the widget package's theme warning sink.
func SetSystemColors ¶
func SetSystemColors(s SystemColors)
SetSystemColors installs the system color mapping; the zero value restores the defaults. One mapping per process, like the theme layer.
Types ¶
type AnimLists ¶
type AnimLists struct {
Names []string
Durations []float64
Timings []Timing
Iterations []float64
Directions []uint8
Running []bool
Delays []float64
Fills []uint8
Compositions []uint8
}
AnimLists are the animation-* longhands as declared, one list each; Compute zips them against the names into Values.Animation. A nil list is the longhand's initial value. An empty name is `none`.
type Animation ¶
type Animation struct {
Name string
Duration float64 // seconds
Delay float64 // seconds; negative starts mid-flight
Timing Timing
// Iterations is the iteration count, +Inf for infinite.
Iterations float64
Direction uint8 // DirNormal..DirAlternateReverse
Fill uint8 // FillNone..FillBoth
Running bool
// Composition is animation-composition: how a frame joins the
// underlying value (CompReplace, CompAdd, CompAccumulate).
Composition uint8
Keyframes *Keyframes
}
Animation is one computed animation: which @keyframes rule runs, for how long after what delay, along which curve, how many times, in which direction, what holds outside the active interval, whether it plays, and how its effect composes onto the underlying style.
func (*Animation) End ¶
End is the local time the animation's active interval ends at, +Inf for an infinite one.
func (*Animation) Sample ¶
Sample is the animation's state at local time t, the seconds since it was applied (web-animations-1 §4.6-§4.9): its directed progress within the current iteration and whether it was sampled from the before phase, the before flag the step functions read. ok is false where the animation has no effect — before or after its active interval without a fill covering that side. The timing function is not applied here: CSS animations ease each keyframe interval.
type Appearance ¶
type Appearance uint8
Appearance is the appearance keyword.
const ( AppearanceAuto Appearance = iota AppearanceNone )
Appearance values.
type Attr ¶
Attr is one app-set data attribute a widget carries: attribute selectors test it by name.
type AutoTracks ¶
type AutoTracks struct {
Sizes []TrackSize
}
AutoTracks is a computed grid-auto-columns or grid-auto-rows value: the sizes the implicit tracks cycle through. A nil list is auto.
func (*AutoTracks) At ¶
func (a *AutoTracks) At(k int) TrackSize
At is the size of implicit track k: k counts from zero after the explicit grid, and from -1 backwards before it, so the first track after takes the first size and the last track before the last size.
type AxisPos ¶
type AxisPos struct {
Frac, Px float64
}
AxisPos is one axis of a CSS <position>: the point Frac of the free space along the axis plus Px pixels.
type Background ¶
type Background struct {
Images []ImageSource
Sizes []LayerSize
Positions [][2]AxisPos
Repeats []LayerRepeat
Clips []LayerBox
Origins []LayerBox
Attachments []LayerAttachment
}
Background is the background-* longhands' lists as declared; a nil list is the initial value (none, auto, 0% 0%, repeat, border-box, padding-box, scroll).
func (*Background) Equal ¶
func (b *Background) Equal(o *Background) bool
Equal reports whether two backgrounds hold the same lists.
func (*Background) Layer ¶
func (b *Background) Layer(i int) ImageLayer
Layer zips layer i, top first: each list matched by index and repeating.
func (*Background) Len ¶
func (b *Background) Len() int
Len is the layer count: one per image, at least one.
func (*Background) Painted ¶
func (b *Background) Painted() bool
Painted reports whether any layer has an image.
type Block ¶
type Block struct {
// contains filtered or unexported fields
}
Block is a parsed declaration list: one rule's body, or a widget's inline style.
func ParseDeclarations ¶
ParseDeclarations parses a bare declaration list — `color: red; --x: 1px` — the body a widget's inline style carries. Malformed declarations are warned about and dropped.
type BorderImage ¶
type BorderImage struct {
Source ImageSource
Slice [4]NumVal
Fill bool
Width [4]BorderImageLen
Outset [4]BorderImageLen
Repeat LayerRepeat
}
BorderImage is the border-image group's computed value. Slice holds the four slice offsets (top, right, bottom, left) as image pixels or percentages of the image's size.
func (*BorderImage) Equal ¶
func (b *BorderImage) Equal(o *BorderImage) bool
Equal reports whether two border images are the same.
type BorderImageLen ¶
type BorderImageLen struct {
Kind BorderImageLenKind
V float64
}
BorderImageLen is one side of border-image-width or -outset.
type BorderImageLenKind ¶
type BorderImageLenKind uint8
BorderImageLenKind is a border-image-width or -outset side's form.
const ( ImageLenNumber BorderImageLenKind = iota ImageLenLength ImageLenPercent ImageLenAuto )
The forms: a multiple of the side's border width (a plain number, the initial 1 for widths), a length, a percentage of the border image area, and auto (the slice's own size).
type BorderStyle ¶
type BorderStyle uint8
BorderStyle is a border or outline line style. The subset draws solid lines; every other visible style strokes solid, and none/hidden zero the width, per the CSS computed-value rule.
const ( BorderNone BorderStyle = iota BorderHidden BorderSolid BorderDashed BorderDotted BorderDouble BorderGroove BorderRidge BorderInset BorderOutset // BorderAuto is outline-style: auto, the platform focus ring; no // border takes it. BorderAuto )
Border styles.
func (BorderStyle) Visible ¶
func (b BorderStyle) Visible() bool
Visible reports whether the style draws a line.
type BoxAlign ¶
type BoxAlign struct {
Kind BoxAlignKind
Safe bool
}
BoxAlign is one computed alignment: the keyword and its overflow mode, Safe falling back to start when the subject overflows the alignment container.
type BoxAlignKind ¶
type BoxAlignKind uint8
BoxAlignKind is one CSS Box Alignment keyword, shared by justify-content, align-items, align-self and align-content.
const ( BoxNormal BoxAlignKind = iota BoxAuto BoxStretch BoxStart BoxEnd BoxFlexStart BoxFlexEnd BoxSelfStart BoxSelfEnd BoxCenter BoxLeft BoxRight BoxBaseline BoxLastBaseline BoxSpaceBetween BoxSpaceAround BoxSpaceEvenly )
Alignment keywords. Normal is the initial value of every one of the properties but align-self, whose initial Auto defers to the container's align-items.
type CaretShape ¶
type CaretShape uint8
CaretShape is the caret-shape keyword.
const ( CaretAuto CaretShape = iota CaretBar CaretBlock CaretUnderscore )
Caret shapes.
type ClipShape ¶
type ClipShape struct {
Kind ClipShapeKind
// Inset is top, right, bottom, left.
Inset [4]NumVal
InsetRad [4]int
// Rad is circle()'s radius; RadX and RadY ellipse()'s pair.
Rad, RadX, RadY NumVal
CenterX, CenterY NumVal
// Poly is polygon()'s points as x, y pairs.
Poly []NumVal
Path string
}
ClipShape is the computed clip-path: the shape's kind and its geometry against the border box — the inset's per-side insets (with rounded corner radii), the circle and ellipse radii and centers, the polygon's points, or the path() data string.
type ClipShapeKind ¶
type ClipShapeKind uint8
ClipShapeKind names one clip-path shape.
const ( ClipNone ClipShapeKind = iota ClipInset ClipCircle ClipEllipse ClipPolygon ClipPathData )
The clip-path shapes.
type Container ¶
Container is one query container a @container condition and the container-query units resolve against: an ancestor widget with container-type set, as the widget layer reports it. Size is false for an inline-size container, whose block axis stays unqueryable; Names is its container-name list.
type ContainerType ¶
type ContainerType uint8
ContainerType is the container-type keyword.
const ( ContainerNormal ContainerType = iota ContainerInlineSize ContainerSize )
container-type keywords.
type Corners ¶
type Corners struct {
TopLeft, TopRight, BottomRight, BottomLeft int
}
Corners is a per-corner radius set, clockwise from top-left.
type CounterEntry ¶
CounterEntry is one counter of a node's counter set: its name, its value at the node, and the element that instantiated it.
type CounterScope ¶
type CounterScope struct {
// contains filtered or unexported fields
}
CounterScope is a node's CSS counters set, outermost counter first. A computed set is never mutated: a node that changes it clones it.
func (*CounterScope) Equal ¶
func (cs *CounterScope) Equal(o *CounterScope) bool
Equal reports whether two counter sets hold the same counters with the same values.
type CursorSpec ¶
type CursorSpec struct {
// Name is the keyword, or with a URL the fallback keyword the
// list ends with; empty is auto.
Name string
// URL is the first url() image and HotX, HotY its hotspot.
URL string
HotX, HotY int
}
CursorSpec is the cursor property's value: a CSS keyword, or a url() file cursor with its hotspot in pixels. The zero value is auto — the widget's own shape decides.
type Display ¶
type Display uint8
Display is the display keyword. The two-keyword forms (block flow, inline flex, inline flow-root, ...) compute to these.
type Env ¶
type Env struct {
// Rem is the root font size in logical pixels: what 1rem is.
Rem float64
// FontPx is the font size a node computes when nothing in its
// ancestry sets one (CSS's `medium`); zero means Rem.
FontPx float64
// Font is the node's face metrics the ch, ex, cap, ic and lh units
// resolve against, as ratios of the font size (render.Font.Metrics).
// The zero value falls back to the CSS default ratios.
Font FontMetrics
// RootLineHeight is what 1rlh is; zero falls back to the natural
// line height of Font at Rem.
RootLineHeight float64
// Media is what @media conditions evaluate against (the viewport
// and appearance state); the zero value is a 0×0 viewport at 96dpi.
// Its Width and Height also resolve the vw/vh unit family and its
// Dark flag picks light-dark()'s half.
Media Media
// InlineContainerUnits reports that an inline style names a
// container-query unit, which no sheet's summary shows: the
// container resolution runs for every node, since a custom property
// carries the unit down the tree.
InlineContainerUnits bool
}
Env is the unit environment a compute resolves against.
type FlexDirection ¶
type FlexDirection uint8
FlexDirection is the flex-direction keyword.
const ( FlexRow FlexDirection = iota FlexRowReverse FlexColumn FlexColumnReverse )
flex-direction keywords.
type Float ¶
type Float uint8
Float is the float keyword; the logical sides resolve against the direction at layout time.
type FontFace ¶
type FontFace struct {
// Family is the font-family descriptor, the name a font-family
// declaration matches.
Family string
// Src is the resolved url() path of the first loadable src entry.
Src string
// Format is that src's format() hint, empty when none was given.
Format string
// WeightLo and WeightHi are the font-weight descriptor's range
// (equal for a single weight); 400 when unset.
WeightLo, WeightHi int
// Italic is the font-style descriptor: italic or oblique.
Italic bool
}
FontFace is one @font-face rule: an app font a stylesheet declares, loaded from its src and matched by font-family and font-weight. The widget layer loads the file and serves it to the font-family resolver; format hints outside the truetype/opentype family warn and drop that src.
type FontMetrics ¶
type FontMetrics struct {
Ch, Ex, Cap, Ic, LineHeight float64
}
FontMetrics is a face's font-relative unit bases as ratios of the font size: what one ch, ex, cap, ic and lh of the node's font is, per em. A zero field falls back to the CSS default ratio. The widget layer fills it from the resolved face (render.Font.Metrics).
type FontPalette ¶
type FontPalette uint8
FontPalette is the font-palette keyword.
const ( PaletteNormal FontPalette = iota PaletteLight PaletteDark )
font-palette keywords.
type FontSynthesis ¶
type FontSynthesis uint8
FontSynthesis is font-synthesis' flag set: which face qualities the engine may synthesize when the chosen face lacks them.
const ( SynthWeight FontSynthesis = 1 << iota SynthStyle SynthSmallCaps )
font-synthesis flags.
type FontVariantAlternates ¶
type FontVariantAlternates uint8
FontVariantAlternates is the font-variant-alternates keyword.
const ( AlternatesNormal FontVariantAlternates = iota AlternatesHistorical )
font-variant-alternates keywords.
type FontVariantCaps ¶
type FontVariantCaps uint8
FontVariantCaps is the font-variant-caps keyword.
const ( CapsNormal FontVariantCaps = iota CapsSmallCaps CapsAllSmallCaps CapsPetiteCaps CapsAllPetiteCaps CapsUnicase CapsTitlingCaps )
font-variant-caps keywords.
type FontVariantEastAsian ¶
type FontVariantEastAsian uint16
FontVariantEastAsian is font-variant-east-asian's flag set.
const ( EAJis78 FontVariantEastAsian = 1 << iota EAJis83 EAJis90 EAJis04 EASimplified EATraditional EAFullWidth EAProportional EARuby )
font-variant-east-asian flags.
type FontVariantLigatures ¶
type FontVariantLigatures uint16
FontVariantLigatures is font-variant-ligatures' flag set: each group's on and off keyword, neither meaning the font's default.
const ( LigCommon FontVariantLigatures = 1 << iota LigNoCommon LigDiscretionary LigNoDiscretionary LigHistorical LigNoHistorical LigContextual LigNoContextual )
font-variant-ligatures flags.
type FontVariantNumeric ¶
type FontVariantNumeric uint16
FontVariantNumeric is font-variant-numeric's flag set.
const ( NumLining FontVariantNumeric = 1 << iota NumOldStyle NumProportional NumTabular NumDiagonalFractions NumStackedFractions NumOrdinal NumSlashedZero )
font-variant-numeric flags.
type FontVariantPosition ¶
type FontVariantPosition uint8
FontVariantPosition is the font-variant-position keyword.
const ( PositionNormal FontVariantPosition = iota PositionSub PositionSuper )
font-variant-position keywords.
type Gradient ¶
type Gradient struct {
Kind render.GradientKind
Repeat bool
Angle float64
CenterX, CenterY float64
Circle bool
Size render.RadialSize
RadiusX, RadiusY float64
N int
Stops [MaxStops]GradientStop
}
Gradient is a gradient background image - linear, radial, or conic, optionally repeating - in render's geometry terms. N zero means none. Angle is in degrees, CSS convention: 0 points up, 90 right (a conic gradient's start). CenterX/Y place a radial or conic center as box fractions; RadiusX/Y are explicit radial radii in px.
func (*Gradient) Resolve ¶
func (g *Gradient) Resolve(line float64, dst []render.GradientStop) []render.GradientStop
Resolve lays g's stops on a gradient line line pixels long: CSS Images 3's color-stop fixup (an auto first stop at 0%, an auto last at 100%, every position at least its predecessors', runs of auto stops spread evenly between their neighbors), then each color hint drawn as a power curve of hintSteps segments between its stops. The result appends to dst, which should hold MaxResolvedStops.
type GradientStop ¶
GradientStop is one color stop or color hint. At a stop's position is Pos of the gradient line plus Px pixels (a <length-percentage>, resolved against the line by Gradient.Resolve); without At the position is auto. A Hint carries no color: it moves the midpoint of the interpolation between its neighbor stops.
type GridAreas ¶
GridAreas is a computed grid-template-areas value other than none: the template's size and its named areas, in order of first appearance.
type GridAutoFlow ¶
type GridAutoFlow struct {
Column, Dense bool
}
GridAutoFlow is grid-auto-flow: the axis auto-placement fills (rows unless Column) and whether it packs densely.
type GridLine ¶
type GridLine struct {
Kind GridLineKind
N int
Name string
}
GridLine is one computed grid-row-start, grid-row-end, grid-column-start or grid-column-end value.
type GridLineKind ¶
type GridLineKind uint8
GridLineKind is the form of one placement line.
const ( GridLineAuto GridLineKind = iota GridLineIdent GridLineNumber GridLineSpan )
Placement line kinds. Ident is a lone <custom-ident>: a named area's edge (the line called <ident>-start or <ident>-end), else the first line of that name. Number is the Nth line, negative from the end, counting only lines called Name when it is set. Span spans N tracks, or to the Nth line called Name.
type ImageLayer ¶
type ImageLayer struct {
Image ImageSource
Size LayerSize
Pos [2]AxisPos
Repeat LayerRepeat
Clip LayerBox
Origin LayerBox
Attach LayerAttachment
}
ImageLayer is one zipped background layer.
type ImageSource ¶
type ImageSource struct {
Gradient *Gradient
URL string
// Grain is lys-ui's -lys-grain(): a fine noise at this opacity
// (0 to 1) over the layer's area, the etching of frosted glass.
Grain float64
}
ImageSource is one <image>: a gradient, a url() file, or none (both zero). image-set() resolves to one of its candidates when it computes.
func (ImageSource) None ¶
func (s ImageSource) None() bool
None reports an image that paints nothing.
type ImportResolver ¶
ImportResolver loads an @import target: ref resolved against base, the importing stylesheet's path ("" for a string stylesheet, when ref stands alone). An error drops the import with a warning.
type Keyframe ¶
Keyframe is one stop of a keyframes rule: its offset in the iteration, the longhands it declares with their computed values, and its own animation-timing-function, which eases the interval from it to the next stop (nil: the animation's).
type Keyframes ¶
Keyframes is one @keyframes rule: its stops in offset order, and the longhands any of them declares.
func (*Keyframes) Apply ¶
func (kf *Keyframes) Apply(dst, under *Values, progress float64, timing *Timing, before bool, comp uint8)
Apply writes the rule's effect at iteration progress into dst for every longhand the rule animates, eased per keyframe interval (css-animations-1 §3.2) and composed onto under — the value beneath the animation — by comp. A longhand missing from the 0% or 100% stop takes under's value there.
type Layer ¶
Layer is one stylesheet in a cascade with its priority: GTK's provider priority, compared before specificity. Among equal priorities, a later layer wins ties.
type LayerAttachment ¶
type LayerAttachment uint8
LayerAttachment is background-attachment.
const ( AttachScroll LayerAttachment = iota AttachFixed AttachLocal )
The attachments: scroll and local move with the box (no box here scrolls its own background), fixed positions against the viewport.
type LayerLength ¶
LayerLength is one explicit size dimension: a length or percentage of the positioning area, or auto.
type LayerRepeat ¶
type LayerRepeat [2]TileKind
LayerRepeat is a layer's horizontal then vertical repeat style.
type LayerSize ¶
type LayerSize struct {
Kind LayerSizeKind
W, H LayerLength
}
LayerSize is background-size or mask-size.
type LayerSizeKind ¶
type LayerSizeKind uint8
LayerSizeKind is a layer size's form.
const ( SizeAuto LayerSizeKind = iota SizeCover SizeContain SizeExplicit )
The layer size forms: auto (the image's natural size, a gradient filling the positioning area), cover, contain, and explicit widths and heights.
type Layout ¶
type Layout struct {
Display Display
Position Position
// Inset is top, right, bottom, left: auto or a length.
Inset [4]Sizing
// ZIndex is z-index; auto computes to 0, the stacking order a
// container's children share.
ZIndex int
Width, Height Sizing
MinWidth, MinHeight Sizing
MaxWidth, MaxHeight Sizing
BoxSizing BoxSizing
// AspectRatio is width over height; zero is auto.
AspectRatio float64
FlexDirection FlexDirection
FlexWrap FlexWrap
JustifyContent BoxAlign
AlignItems BoxAlign
AlignSelf BoxAlign
AlignContent BoxAlign
FlexGrow float64
FlexShrink float64
FlexBasis Sizing
Order int
// RowGap and ColumnGap are the gaps between a flex container's
// lines and its items; normal computes to zero.
RowGap, ColumnGap Length
OverflowX, OverflowY Overflow
Visibility Visibility
Float Float
Clear Clear
// The grid container's explicit grid (grid.go): its track lists and
// area map, nil for none, the implicit tracks' sizes, nil for auto,
// and the auto-placement flow.
GridTemplateColumns, GridTemplateRows *TrackList
GridTemplateAreas *GridAreas
GridAutoColumns, GridAutoRows *AutoTracks
GridAutoFlow GridAutoFlow
// A grid item's placement lines and its inline-axis alignment;
// JustifyItems is the container's default for its items'
// justify-self: auto.
GridColumnStart, GridColumnEnd GridLine
GridRowStart, GridRowEnd GridLine
JustifyItems, JustifySelf BoxAlign
// ObjectFit is object-fit as the render scale policy implementing
// it; ObjectPosition is object-position, horizontal then vertical
// (objectfit.go).
ObjectFit render.ImageScale
ObjectPosition [2]AxisPos
}
Layout is the computed CSS layout group, comparable so a restyle diffs it with == (the grid's interned lists compare by value that way). Each field's longhand Set bit says whether the stylesheet declared it: an undeclared display, flex-direction, flex-grow, align-self or gap leaves the widget's programmatic layout in charge (docs/css.md's interaction rule).
type LayoutMotion ¶
type LayoutMotion uint8
LayoutMotion is a -lys-layout-motion value: how a box animates a change of its laid-out rect - not at all, or on one of the named springs.
const ( LayoutMotionNone LayoutMotion = iota LayoutMotionSmooth LayoutMotionSnappy LayoutMotionBouncy )
The layout motions.
type Length ¶
Length is a computed <length-percentage>: Px logical pixels plus Pct percent of the basis the layout resolves it against. A calc() sum mixes the two (calc(100% - 2em)); a plain length leaves Pct zero and a plain percentage Px.
func (Length) Negative ¶
Negative reports whether the length is negative whatever its basis: what a property taking no negative sizes rejects. A mix negative only for some bases (calc(100% - 20px)) is valid, and the layout clamps its used value at zero, as CSS does.
type LineBreakK ¶
type LineBreakK uint8
LineBreakK is the line-break keyword (K for the line-break clash with the render-side breaker).
const ( LineBreakAuto LineBreakK = iota LineBreakLoose LineBreakNormal LineBreakStrict LineBreakAnywhere )
Line-break keywords.
type LineSpan ¶
type LineSpan struct{ Start, End int }
LineSpan is a run of grid lines, zero-based, End exclusive of the tracks: a grid area's extent along one axis.
type Mask ¶
type Mask struct {
Image ImageSource
Size LayerSize
Pos [2]AxisPos
Repeat LayerRepeat
Luminance bool
}
Mask is the computed mask group (css-masking-1 §7): one image layer — its image, size, position and repeat, positioned and clipped in the border box — and whether it reads luminance instead of alpha.
type Media ¶
type Media struct {
Width, Height float64
DPI float64
Dark bool
HighContrast bool
ReducedMotion bool
}
Media is the environment @media conditions evaluate against: the viewport's size and density, and the appearance preferences the theme carries (dark polarity, high contrast, motion). The widget layer fills it per compute: the viewport from SetMediaViewport, the preferences derived from the active Theme (IsDark, Animations) and SetMediaContrast, so a theme swap re-evaluates prefers-* rules.
type Node ¶
type Node interface {
// StyleTarget fills t with the node's selector facts.
StyleTarget(t *Target)
// StyleParent returns the parent node, or nil at the root.
StyleParent() Node
// StylePrev returns the previous visible sibling, or nil.
StylePrev() Node
// StylePosition returns the node's 1-based index among its visible
// siblings and their count; a root reports (1, 1).
StylePosition() (index, count int)
// StyleTypedPosition returns the 1-based index among the visible
// siblings of element name and their count (:nth-of-type and
// friends).
StyleTypedPosition(element string) (index, count int)
// StyleChildren returns the visible children, or nil for a leaf;
// :empty and :has() read it.
StyleChildren() []Node
}
Node is one node of the widget tree as the matcher sees it.
type NumVal ¶
NumVal is one length-or-percentage argument: the value and whether it is a percentage of the box dimension it applies to.
type Overflow ¶
type Overflow uint8
Overflow is an overflow-x/overflow-y keyword.
overflow keywords.
type OverflowWrapK ¶
type OverflowWrapK uint8
OverflowWrapK is the overflow-wrap keyword (and its word-wrap alias).
const ( OverflowWrapNormal OverflowWrapK = iota OverflowWrapBreakWord OverflowWrapAnywhere )
Overflow-wrap keywords: break-word and anywhere both break an otherwise unbreakable word that overflows its line; only anywhere's opportunities count toward the min-content size.
type Overscroll ¶
type Overscroll uint8
Overscroll is one axis's overscroll-behavior.
const ( OverscrollAuto Overscroll = iota OverscrollContain OverscrollNone )
The overscroll-behavior values.
type PointerEvents ¶
type PointerEvents uint8
PointerEvents is the pointer-events keyword: none takes the widget (and its subtree) out of hit testing.
const ( PointerAuto PointerEvents = iota PointerNone )
Pointer-events values.
type Position ¶
type Position uint8
Position is the position keyword.
type Prop ¶
type Prop uint8
Prop names one longhand property of the docs/css.md table. Shorthands (padding, margin, border, border-radius, background, outline, transition, all) expand onto these at parse time; the cascade runs per longhand, exactly like CSS.
const ( PropColor Prop = iota PropBackgroundColor PropBackgroundImage PropOpacity PropFilter PropPaddingTop PropPaddingRight PropPaddingBottom PropPaddingLeft PropMarginTop PropMarginRight PropMarginBottom PropMarginLeft PropBorderTopWidth PropBorderRightWidth PropBorderBottomWidth PropBorderLeftWidth PropBorderTopStyle PropBorderRightStyle PropBorderBottomStyle PropBorderLeftStyle PropBorderTopColor PropBorderRightColor PropBorderBottomColor PropBorderLeftColor PropBorderTopLeftRadius PropBorderTopRightRadius PropBorderBottomRightRadius PropBorderBottomLeftRadius PropBoxShadow PropOutlineWidth PropOutlineStyle PropOutlineColor PropOutlineOffset PropMinWidth PropMinHeight PropBorderSpacing PropFontFamily PropFontSize PropFontWeight PropFontStyle PropLetterSpacing PropTextTransform PropLineHeight PropFontFeatures PropFontVariations PropTransform PropTransformOrigin PropIconSize PropTransitionProperty PropTransitionDuration PropTransitionTiming PropTransitionDelay PropAnimation PropAnimationPlayState PropAnimDuration PropAnimDelay PropAnimDirection PropAnimFill PropIconTransform PropIconSource PropIconPalette PropCaretColor PropTextDecorationLine PropCursor PropPointerEvents PropUserSelect PropCaretShape PropAccentColor PropAppearance PropTouchAction PropTextAlign PropTextIndent PropWhiteSpace PropWordBreak PropLineBreak PropHyphens PropWordSpacing PropVerticalAlign PropLineClamp PropTextOverflow PropFontVariantCaps PropFontVariantNumeric PropFontVariantLigatures PropFontVariantEastAsian PropFontVariantPosition PropFontVariantAlternates PropFontSynthesis PropFontOpticalSizing PropDirection PropUnicodeBidi PropWritingMode PropBackdropFilter PropMixBlendMode PropIsolation PropClipPath PropMaskImage PropMaskPosition PropMaskSize PropMaskRepeat PropMaskMode PropPerspective PropTransformStyle PropBackfaceVisibility PropLayoutMotion PropScrollBehavior PropScrollMarginTop PropScrollMarginRight PropScrollMarginBottom PropScrollMarginLeft PropScrollPaddingTop PropScrollPaddingRight PropScrollPaddingBottom PropScrollPaddingLeft PropScrollSnapType PropScrollSnapAlign PropScrollSnapStop PropOverscrollX PropOverscrollY PropScrollbarColor PropScrollbarWidth PropScrollbarGutter PropTransitionBehavior PropAnimComposition PropContainerType PropContainerName PropDisplay PropPosition PropTop PropRight PropBottom PropLeft PropZIndex PropWidth PropHeight PropMaxWidth PropMaxHeight PropBoxSizing PropAspectRatio PropFlexDirection PropFlexWrap PropJustifyContent PropAlignItems PropAlignSelf PropAlignContent PropFlexGrow PropFlexShrink PropFlexBasis PropOrder PropRowGap PropColumnGap PropOverflowX PropOverflowY PropVisibility PropFloat PropClear PropGridTemplateColumns PropGridTemplateRows PropGridTemplateAreas PropGridAutoColumns PropGridAutoRows PropGridAutoFlow PropGridColumnStart PropGridColumnEnd PropGridRowStart PropGridRowEnd PropJustifyItems PropJustifySelf PropObjectFit PropObjectPosition PropTextDecorationStyle PropTextDecorationColor PropTextShadow PropFontPalette PropOverflowWrap PropAnimTiming PropAnimIteration PropBackgroundSize PropBackgroundPosition PropBackgroundRepeat PropBackgroundClip PropBackgroundOrigin PropBackgroundAttachment PropBorderImageSource PropBorderImageSlice PropBorderImageWidth PropBorderImageOutset PropBorderImageRepeat )
The longhand properties, as bit indexes into PropSet.
type PropSet ¶
type PropSet struct {
// contains filtered or unexported fields
}
PropSet is a set of longhands, one bit per Prop over three words: separate fields rather than an array, so a set stays in registers through the cascade's per-longhand loops.
func SetOf ¶
SetOf builds a PropSet from its members; the exported form for the consumers outside the engine.
type PropertyReg ¶
type PropertyReg struct {
// Name is the custom property name, leading dashes included.
Name string
// Syntax is the descriptor's syntax string ("<length>", "*",
// "<length> | <percentage>", ...).
Syntax string
// Inherits is the inherits descriptor: false makes the property
// resolve to its initial value on nodes that do not declare it,
// however their ancestors set it.
Inherits bool
// Initial is the initial-value descriptor's tokens, nil for a
// universal syntax without one (then the name resolves to
// nothing, like an unregistered custom property).
Initial []token
}
PropertyReg is one @property registration: a typed custom property with its syntax string, inheritance control, and initial value. Registration fixes var() resolution for the name everywhere the sheet applies; animating a registered property is deferred — the transition engine keys on the longhand table, which custom properties sit outside.
type RepeatKind ¶
type RepeatKind uint8
RepeatKind is the keyword of an auto repetition.
const ( RepeatNone RepeatKind = iota RepeatFill RepeatFit )
Auto repetition keywords; RepeatNone is a track list without one.
type Scalars ¶
type Scalars struct {
Set PropSet
// Own are the properties the node's own rules declared, before
// inheritance filled in the rest of Set: a part that styles only
// what a stylesheet names for it (an entry's placeholder color)
// reads these.
Own PropSet
Color render.Color
Background render.Color
Opacity float64
Brightness float64
// Filter is the computed filter list; Brightness stays the
// brightness-only fast path's product, kept in sync by the
// parser so the tween engines keep their channel.
Filter render.Filters
// Backdrop is the computed backdrop-filter list, applied to what
// paints behind the widget rather than the widget itself.
Backdrop render.Filters
// Blend is the computed mix-blend-mode; BlendNormal composites as
// plain source-over.
Blend render.BlendMode
// Isolate is isolation: isolate — the subtree becomes its own
// compositing group.
Isolate bool
// Perspective is the perspective distance in px; zero is none.
Perspective float64
// Preserve3D is transform-style: preserve-3d; flat otherwise. The
// painter flattens either way today — see docs/css.md.
Preserve3D bool
// BackfaceHidden is backface-visibility: hidden.
BackfaceHidden bool
// LayoutMotion is lys-ui's -lys-layout-motion: the spring a change
// of the box's laid-out rect animates on, none by default.
LayoutMotion LayoutMotion
Padding Sides
Margin Sides
BorderWidth Sides
BorderStyle [4]BorderStyle // top, right, bottom, left
BorderColor [4]render.Color
Radius Corners
Shadow Shadows
OutlineWidth int
OutlineStyle BorderStyle
OutlineColor render.Color
OutlineOffset int
// OutlineAuto is outline-color: auto (the initial value): the
// focus ring's accent under outline-style auto, currentColor
// otherwise.
OutlineAuto bool
// MarginAuto marks the margin sides declared auto (top, right,
// bottom, left): Margin holds zero there, and the CSS layout
// engines hand those sides the free space.
MarginAuto [4]bool
// Layout is the CSS layout group: display, the box sizes,
// positioning, flexbox, grid, overflow, visibility and float.
Layout Layout
// BorderSpacing is GTK's border-spacing: the gap a box leaves between
// its children, horizontal and vertical.
BorderSpacingH, BorderSpacingV int
FontFamily string
FontSize float64
FontWeight int
Italic bool
LetterSpacing float64
TextTransform TextTransform
// LineHeight is the computed line-height in pixels; 0 is `normal`,
// the font's own line box.
LineHeight float64
// LineHeightFactor is the unitless number line-height was given,
// 0 for normal, a length or a percentage: a number inherits as
// itself, so each element resolves it against its own font-size.
LineHeightFactor float64
// Features is the font-feature-settings tag list in canonical form
// (`on=1;ss01=0;tnum=1`, sorted); empty is `normal`. The text
// shaper honors the tags it knows (tnum today).
Features string
// Variations is the font-variation-settings axis list in canonical
// form (`wdth=80.5;wght=650`, sorted); empty is `normal`.
Variations string
// TransformOrigin is the transform's pivot: fraction-of-box plus
// pixel offset per axis; the default is the box's center.
OriginFrac, OriginPx [2]float64
IconSize int
// IconSource is -gtk-icon-source's -gtk-icontheme() name: a themed
// symbolic icon a widget draws instead of its painted mark (the
// checkbutton's tick).
IconSource string
// PaletteTint is -gtk-icon-palette's recolor: the color the source
// icon takes (the stylesheet writes `success <color>`).
PaletteTint render.Color
// CaretColor is caret-color: an entry's caret takes it over the
// text color.
CaretColor render.Color
// Decoration is the text-decoration group: text-decoration-line,
// -style and -color, each its own longhand.
Decoration render.Decoration
// TextShadow is the text-shadow list (spread and inset are always
// zero); it inherits.
TextShadow Shadows
// Cursor is cursor: the hover shape a stylesheet asks for, a
// keyword or a url() file cursor with its hotspot. The zero value
// is auto; it inherits.
Cursor CursorSpec
// PointerEvents is pointer-events: none takes the widget out of
// hit testing.
PointerEvents PointerEvents
// UserSelect is user-select on the text surfaces that select.
UserSelect UserSelect
// CaretShape is caret-shape: the caret's painted form.
CaretShape CaretShape
// AccentColor is accent-color over the theme accent; AccentAuto
// marks the auto keyword falling back to the theme.
AccentColor render.Color
AccentAuto bool
// Appearance is appearance: parsed only, none's chrome stripping
// is deferred (docs/css.md).
Appearance Appearance
// TouchAction is touch-action: the pan axes a touch scroll may
// move.
TouchAction TouchAction
// The scroll-container group: scroll-behavior gates animated
// programmatic scrolls, scroll-padding insets the viewport for
// reveal and snap math, scroll-snap-type turns snapping on,
// overscroll-behavior gates chaining to the parent scroll, and
// scrollbar-gutter reserves the bar's space in measure. The
// scrollbar-color/width pair is inherited and reaches the bars.
ScrollSmooth bool
ScrollPad Sides
Snap SnapType
Overscroll [2]Overscroll
BarThumb render.Color
BarTrack render.Color
// BarColorAuto marks scrollbar-color: auto (the default look).
BarColorAuto bool
BarWidth uint8
BarGutter uint8
// The scrolled-child group: scroll-margin insets the revealed rect,
// scroll-snap-align names the child a snap position, and
// scroll-snap-stop makes one the gesture cannot skip past.
ScrollMargin Sides
SnapAlign SnapAlign
SnapStopAlways bool
// The CSS Text 3 properties. TextAlign, TextIndent, WhiteSpace,
// WordBreak, LineBreak, Hyphens, WordSpacing and the font-variant
// family inherit; VerticalAlign, LineClamp, TextOverflow,
// UnicodeBidi and FontSynthesis do not.
TextAlign TextAlign
TextIndent float64
WhiteSpace WhiteSpace
WordBreak WordBreak
LineBreak LineBreakK
Hyphens HyphensK
WordSpacing float64
VerticalAlign VerticalAlignK
VerticalAlignPx float64
// VerticalAlignPct marks VerticalAlignPx a fraction of the line
// box instead of pixels.
VerticalAlignPct bool
LineClamp int
Overflow TextOverflowK
VariantCaps FontVariantCaps
VariantNumeric FontVariantNumeric
VariantLig FontVariantLigatures
VariantEA FontVariantEastAsian
VariantPos FontVariantPosition
VariantAlt FontVariantAlternates
Synthesis FontSynthesis
OpticalSizing bool
// Palette is font-palette; it inherits.
Palette FontPalette
// OverflowWrap is overflow-wrap; it inherits.
OverflowWrap OverflowWrapK
// Direction is the CSS direction: 1 ltr, 2 rtl (0 cannot be set -
// direction takes no auto keyword).
Direction uint8
UnicodeBidi UnicodeBidi
WritingMode WritingMode
// ContainerType is container-type (container queries): normal
// (the default) names no query container, inline-size one whose
// inline axis its descendants query, size one whose both axes do.
ContainerType ContainerType
// ContainerNames is container-name: the space-separated custom-ident
// list a @container name filter matches against.
ContainerNames string
// Content is a pseudo-element's resolved content (::before,
// ::after): the strings, attr() values, and counter readings joined;
// HasContent reports a content declaration won at all.
Content string
HasContent bool
// ContentURL is content: url(...): an image painted as the
// pseudo-element's generated content, beside Content's text.
ContentURL string
// QuoteDepth is the open-quote nesting depth after this node's
// content resolved: descendants' open-quote/close-quote start from
// it, CSS's inherited quote counter.
QuoteDepth int
// Vars is the node's custom-property environment: its own
// declarations over the inherited chain. Nodes that declare none
// share their parent's pointer, so equality stays cheap.
Vars *Vars
}
Scalars are the comparable computed values of a node.
type Scratch ¶
type Scratch struct {
// contains filtered or unexported fields
}
Scratch holds one matcher's reusable buffers. Style work runs on the event-loop goroutine, so one Scratch per process serves every compute; it is not safe for concurrent use.
func (*Scratch) SetPrevCounters ¶
func (sc *Scratch) SetPrevCounters(prev, src *CounterScope)
SetPrevCounters supplies the widget layer's half of CSS's counter inheritance (css-lists-3 §4.4.1): prev is the previous sibling's counter set (nil without one), and src the set of the element immediately preceding the node in tree order — the previous sibling's last descendant — whose values the inherited counters take (nil reads the parent's). Compute consumes and clears both.
type Sensitivity ¶
type Sensitivity struct {
// AncestorStates are the state bits some selector tests on a
// non-rightmost compound.
AncestorStates State
// AncestorClasses are the classes some selector tests on a
// non-rightmost compound.
AncestorClasses map[string]bool
// Structural reports structural pseudo-classes or sibling
// combinators anywhere: a sibling's add, removal, reorder or
// visibility can then restyle its neighbors.
Structural bool
// SiblingFacts reports sibling combinators or an :nth-*(... of S)
// anywhere: a sibling's class or state can then restyle its
// neighbors. Position alone (:last-child) reads neither.
SiblingFacts bool
// HasRelational reports a :has() anywhere: a descendant or
// following sibling's facts then feed an ancestor's match, so class
// and state changes restyle up the tree too.
HasRelational bool
// Pseudo reports a ::before/::after rule: the widget layer then
// computes pseudo-element styles.
Pseudo bool
// Counters reports counter-reset or counter-increment in play: the
// widget layer then chains siblings' counter scopes.
Counters bool
// Container reports a @container rule: it makes the per-compute
// container resolution (and a viewport change's restyle) necessary,
// since containers resize with the window.
Container bool
// Units reports the size-relative units the sheet's values name.
Units UnitReads
// Revert reports a revert or revert-layer value: the cascade then
// records every declaration, the chain the two roll back along.
Revert bool
}
Sensitivity summarizes what a sheet's selectors read beyond a node's own facts, so a state or class flip restyles no more than it must: a state bit or class named left of a combinator makes descendants (or following siblings) depend on it.
type Shadows ¶
type Shadows struct {
N int
Layers [MaxShadows]Shadow
}
Shadows is a fixed-capacity box-shadow list, comparable so a restyle can diff it.
type Sheet ¶
type Sheet struct {
// contains filtered or unexported fields
}
Sheet is a parsed stylesheet: the rules in source order plus the match index. It is immutable after Parse and safe for concurrent readers.
func Parse ¶
Parse compiles css into a Sheet. Malformed declarations and rules are warned about and skipped; the valid remainder still applies. An empty (or all-invalid) input yields an empty Sheet — never nil.
Example ¶
s := Parse(`:root { --danger: #a00; } button.destructive { background-color: var(--danger); }`)
var sc Scratch
var root, v Values
layers := []Layer{{Sheet: s, Priority: PriorityApplication}}
win := el("window")
btn := win.add("button", "destructive")
Compute(layers, win, nil, nil, Env{}, &sc, &root)
Compute(layers, btn, &root, nil, Env{}, &sc, &v)
fmt.Println(v.Has(PropBackgroundColor), v.Background == render.RGB(0xaa, 0, 0))
Output: true true
func ParseCollecting ¶
ParseCollecting parses css like Parse and returns the sheet plus every warning the parse produced, without routing them to the sink: the caller reports them its own way (a file loader turns them into an error carrying the path).
func ParseImporting ¶
func ParseImporting(css, base string, resolve ImportResolver) (*Sheet, []string)
ParseImporting parses css whose base is the importing file's path and whose @import targets load through resolve (nil: the filesystem, relative to the importing file). It is the file-backed loader's parse: imports resolve beside the file, and a cycle or a missing import reports precisely.
func (*Sheet) ContainerQueries ¶
ContainerQueries reports how many distinct @container conditions the sheet's rules carry: zero when nothing in it is container-conditional.
func (*Sheet) FontFaces ¶
FontFaces returns the sheet's @font-face rules in source order, for the widget layer to load and register by family.
func (*Sheet) Keyframes ¶
Keyframes returns the sheet's @keyframes rule of that name, nil when it declares none.
func (*Sheet) MediaQueries ¶
MediaQueries reports how many distinct @media conditions the sheet's rules carry: zero when nothing in it is media-conditional.
func (*Sheet) Sensitivity ¶
func (s *Sheet) Sensitivity() *Sensitivity
Sensitivity returns the sheet's selector summary.
type Sides ¶
type Sides struct {
Top, Right, Bottom, Left int
}
Sides is a per-side length set, in logical pixels, in CSS's top-right-bottom-left order.
type Sizing ¶
type Sizing struct {
Kind SizingKind
Len Length
}
Sizing is one computed sizing value: width, height, their min-* and max-* bounds, flex-basis, and the top/right/bottom/left insets (auto or a length there).
type SizingKind ¶
type SizingKind uint8
SizingKind is the form of a sizing value.
const ( SizingAuto SizingKind = iota SizingLength SizingMinContent SizingMaxContent SizingFitContent SizingContent )
Sizing kinds. Auto is the zero value: width/height/min-*/flex-basis auto, and max-* none. FitContent carries its limit in Len; the bare keyword is fit-content(100%), the available space.
type SnapAlign ¶
type SnapAlign struct {
Block, Inline SnapAlignK
}
SnapAlign is the computed scroll-snap-align: the block (vertical) and inline (horizontal) alignments of one scrolled child.
type SnapAlignK ¶
type SnapAlignK uint8
SnapAlignK is one scroll-snap-align edge.
const ( SnapNone SnapAlignK = iota SnapStart SnapEnd SnapCenter )
The scroll-snap-align edges.
type SnapAxis ¶
type SnapAxis uint8
SnapAxis is scroll-snap-type's axis half: which axes the container snaps. Block and Inline map onto the vertical and horizontal axes of lys-ui's horizontal-tb world.
type SnapType ¶
type SnapType struct {
Axis SnapAxis
// Mandatory is the mandatory strictness; proximity otherwise.
Mandatory bool
}
SnapType is the computed scroll-snap-type: the axes that snap and how strictly. The zero value snaps nothing.
func (SnapType) Horizontal ¶
Horizontal reports whether the x axis snaps.
type State ¶
type State uint16
State is a widget's interactive state the selector subset matches with: one bit per state pseudo-class.
const ( Hover State = 1 << iota Focus Active Disabled // FocusVisible is focus that arrived by keyboard traversal. FocusVisible // FocusWithin is set on the focused widget and all its ancestors. FocusWithin // Checked is a toggled-on control, or a menu button whose popup is // open (GTK's :checked). Checked // Selected is a selected row or item. Selected // Indeterminate is a check or progress in its mixed state. Indeterminate // Backdrop is a widget whose window is not the active one. Backdrop // ReadOnly is a text field the user cannot edit (:read-only). ReadOnly // PlaceholderShown is an empty field showing its placeholder // (:placeholder-shown). PlaceholderShown // Targeted is the widget the application marks as the navigation // target (:target): the widget tree has no URL fragment, so the // app names the target the way a fragment would. Targeted )
The state bits, in specificity-neutral order (each counts as one class-level step in a selector's rank).
type SystemColors ¶
type SystemColors struct {
Canvas, CanvasText, LinkText, VisitedText, GrayText render.Color
Highlight, HighlightText, Mark, MarkText render.Color
ButtonFace, ButtonText, ButtonBorder, Field, FieldText render.Color
}
SystemColors are the CSS system color keywords mapped to the active theme; SetSystemColors installs the mapping, so a theme swap re-derives every system color the way the theme layer re-derives the named colors.
type Target ¶
type Target struct {
Element string
ID string
Classes []string
State State
// Role is the node's semantic role name (a11y), the [role=...]
// selector's value.
Role string
// Attrs are the app-set data attributes (SetAttr), [name] and
// [name=value] selectors' subject.
Attrs []Attr
// HasText reports text content: a widget showing text has a text
// child in the DOM's terms, so :empty does not match it.
HasText bool
// Inline is the node's own declaration block (a widget-scoped style,
// GTK's per-widget provider), applied at InlinePriority. It is read
// only for the node being styled.
Inline *Block
InlinePriority int
}
Target is one node's selector-relevant facts, filled by the widget layer for the node being styled and for each node a combinator walk crosses.
type TextOverflowK ¶
type TextOverflowK uint8
TextOverflowK is the text-overflow keyword.
const ( TextOverflowClip TextOverflowK = iota TextOverflowEllipsis )
Text-overflow keywords.
type TextTransform ¶
type TextTransform uint8
TextTransform is the text-transform keyword.
const ( TransformNone TextTransform = iota TransformUppercase TransformLowercase TransformCapitalize )
Text transforms.
type Timing ¶
type Timing struct {
// Zeta and Omega are -lys-spring()'s damping ratio and angular
// frequency over the normalized duration (anim.BounceSpring).
Zeta, Omega float64
X1, Y1, X2, Y2 float64
// Steps is non-zero for steps(n); the bezier is then unused.
Steps int
// StepPos is steps' jump position.
StepPos anim.StepPos
// LinN is the number of live linear() points in Lin, which hold
// canonical positions (anim.CanonicalLinear).
LinN int
// Lin is the linear() point list, capped at MaxLinearPts.
Lin [MaxLinearPts]anim.LinearPt
}
Timing is a transition or animation timing function (CSS Easing 2): the named curves and cubic-bezier control points, steps() with its jump position, the linear() piecewise list, or lys-ui's -lys-spring(). Exactly one form is live: Zeta > 0 is the spring, else LinN > 0 is linear(), else Steps > 0 is steps(), else the bezier.
type TouchAction ¶
type TouchAction uint8
TouchAction is touch-action's pan permissions as an axis bitmask: TouchAuto allows both, the single-axis values one, TouchNone neither.
const ( TouchPanX TouchAction = 1 << iota TouchPanY )
Touch-action axis bits.
const ( TouchAuto = TouchPanX | TouchPanY TouchNone TouchAction = 0 )
TouchAuto allows every pan axis; TouchNone allows none.
type TrackBreadth ¶
TrackBreadth is one bound of a track sizing function: a <length-percentage> or fit-content()'s limit in Len, a flex factor in Fr, or a keyword.
type TrackKind ¶
type TrackKind uint8
TrackKind is the form of one bound of a track sizing function.
type TrackList ¶
type TrackList struct {
Subgrid bool
Head TrackRun
Repeat RepeatKind
Auto TrackRun
Tail TrackRun
}
TrackList is a computed grid-template-columns or grid-template-rows value other than none: the tracks before an auto-fill or auto-fit repetition (all of them without one), the repeated run, and the tracks after it. Integer repetitions expand at parse time. Subgrid marks `subgrid`, which carries no tracks (docs/css.md's grid deferrals).
func (*TrackList) Count ¶
Count is the number of tracks with the auto repetition repeated reps times.
func (*TrackList) LineNamed ¶
LineNamed reports whether line i (zero-based, before track i) of the list with reps repetitions carries the name name+suffix; the suffix spares a caller building an area's "<ident>-start" to look it up. A line where two runs meet carries both runs' names.
type TrackRun ¶
TrackRun is a run of tracks with the names of the lines around them: Names[i] names the line before Sizes[i], the last entry the line after the run.
type TrackSize ¶
type TrackSize struct{ Min, Max TrackBreadth }
TrackSize is one track's sizing function as minmax(Min, Max). A single breadth b computes to minmax(b, b), except a flex factor, which is minmax(auto, <flex>), and fit-content(L), minmax(auto, fit-content(L)).
type Transition ¶
type Transition struct {
Props []TransitionTarget
Durations []float64
Delays []float64
Timings []Timing
// Discrete is transition-behavior per entry: allow-discrete.
Discrete []bool
}
Transition is the computed transition-* group as its longhand lists (css-transitions-1 §2): the property list, and the durations, delays, timing functions and behaviors matched to it by index, a shorter list repeating. A nil list is the longhand's initial value: all, 0s, 0s, ease, normal.
func (*Transition) Active ¶
func (t *Transition) Active() bool
Active reports whether any entry can run: a positive duration somewhere in the list.
func (*Transition) Equal ¶
func (t *Transition) Equal(o *Transition) bool
Equal reports whether two transition groups hold the same lists.
func (*Transition) For ¶
func (t *Transition) For(p Prop) (TransitionTiming, bool)
For is the timing a change of p transitions with: the last entry of the property list naming p (or all), with a positive combined duration (css-transitions-1 §3). ok is false when p does not transition.
type TransitionTarget ¶
TransitionTarget is one transition-property entry: all, the longhands one property name covers, or nothing (none, or a name the engine does not know, which CSS keeps in the list).
type TransitionTiming ¶
TransitionTiming is how one longhand's change transitions.
type UnicodeBidi ¶
type UnicodeBidi uint8
UnicodeBidi is the unicode-bidi keyword.
const ( BidiNormal UnicodeBidi = iota BidiEmbed BidiIsolate BidiOverride BidiIsolateOverride BidiPlaintext )
unicode-bidi keywords.
type UnitReads ¶
type UnitReads struct {
Viewport, Container bool
}
UnitReads names the sizes a value depends on through its units: a viewport unit (vw and family) restyles on a viewport change, a container-query unit also on a query container's resize.
type UserSelect ¶
type UserSelect uint8
UserSelect is the user-select keyword.
const ( SelectAuto UserSelect = iota SelectText SelectNone SelectAll SelectContain )
User-select values. Auto's used value depends on the element and its parent (CSS UI 4 §7.1); contain selects like text, confined to the element.
type Values ¶
type Values struct {
Scalars
// Bg is the background-* longhands' layer lists.
Bg Background
// Clip is the computed clip-path; a zero Kind clips nothing.
Clip ClipShape
// Mask is the computed mask-image group (position, size, repeat,
// mode).
Mask Mask
// BorderImage is the border-image group; UsedBorderImage reads it
// with the undeclared longhands at their initial values.
BorderImage BorderImage
// Transform carries the transform property: the composed affine
// the widget paints its subtree through, with the primitive list
// the tweens interpolate. The identity means unset; the parser
// always writes the full Xform, so a declared `none` reads as it.
Transform Xform
// Transition is the transition-* longhands' lists.
Transition Transition
// Starting is the node's computed @starting-style block, nil when
// no matched rule carries one: the values a first style's
// transitions start from (the entry transition). Only the
// properties its rules declare are meaningful.
Starting *Values
// Anim is the animation-* longhands' lists as declared, and
// Animation the animations Compute zips from them (css-animations-1
// §3): one per name that names a @keyframes rule. Neither inherits.
Anim AnimLists
Animation []Animation
// IconXform is -gtk-icon-transform's composed transform; icons
// draw through it.
IconXform Xform
// Counters is the node's counter environment (counter-reset,
// counter-increment): nil when no sheet counts anything.
Counters *CounterScope
}
Values is the cascade result for one node: the winning declaration per longhand, computed (var() substituted, calc() evaluated, units resolved to pixels), with Set recording which longhands the stylesheet provided, directly or through inheritance. Consumers layer programmatic widget values above it and the theme under it. The comparable values sit in the embedded Scalars, so a restyle diffs most of a node's style with one ==; the list- and pointer-valued groups beside it compare through Equal.
func (*Values) EffBorder ¶
EffBorder returns the used border widths: a side whose style draws no line has zero width, the CSS computed-value rule.
func (*Values) EffOutline ¶
EffOutline returns the used outline width: zero unless the style draws a line.
func (*Values) Equal ¶
Equal reports whether two computed styles are the same: the comparable values with one ==, the groups beside them through their own comparisons. A restyle that leaves a node Equal changes nothing.
func (*Values) Origin ¶
Origin is the transform-origin pivot: fractions of the box plus pixel offsets per axis, the box's center when nothing declares it.
func (*Values) UsedBorderImage ¶
func (v *Values) UsedBorderImage() BorderImage
UsedBorderImage is v's border image with every longhand v does not set at its initial value.
type Vars ¶
type Vars struct {
// contains filtered or unexported fields
}
Vars is one node's custom-property environment: its own computed declarations, falling back to the parent's.
type VerticalAlignK ¶
type VerticalAlignK uint8
VerticalAlignK is the vertical-align alignment kind.
const ( VerticalAlignBaseline VerticalAlignK = iota VerticalAlignSub VerticalAlignSuper VerticalAlignTextTop VerticalAlignTextBottom VerticalAlignTop VerticalAlignMiddle VerticalAlignBottom VerticalAlignLength )
Vertical-align kinds. Length is VerticalAlignLength with the shift in Values.VerticalAlignPx.
type Visibility ¶
type Visibility uint8
Visibility is the visibility keyword.
const ( VisibilityVisible Visibility = iota VisibilityHidden VisibilityCollapse )
visibility keywords.
type WhiteSpace ¶
type WhiteSpace uint8
WhiteSpace is the white-space keyword.
const ( WhiteSpaceNormal WhiteSpace = iota WhiteSpacePre WhiteSpaceNowrap WhiteSpacePreWrap WhiteSpacePreLine WhiteSpaceBreakSpaces )
White-space keywords.
type WritingMode ¶
type WritingMode uint8
WritingMode is the writing-mode keyword.
const ( WritingHorizontalTB WritingMode = iota WritingVerticalRL WritingVerticalLR )
writing-mode keywords.
type Xform ¶
type Xform struct {
M render.Affine
P render.M3
// Backface reports the composed projective map with a negative
// determinant - the flat-pipeline reading of the element's back
// facing the viewer.
Backface bool
Parts []XformPart
// contains filtered or unexported fields
}
Xform is one computed transform: the composed affine, the projective composition (which carries the 3-D functions), whether the composed map shows the element's back, and the primitives that built it.
func LerpXform ¶
LerpXform walks two transforms: the primitive lists when they match (a spin turns), the affines' decompositions otherwise.
func (Xform) After ¶
After returns x composed with o after it: o's functions apply once x's have, the transform addition composite (u followed by b). The animation-composition add and accumulate modes both build it - matched-list accumulation needs the per-function lists two keyframes would have to share, and the channels here carry the composed map, so both modes compose.