Documentation
¶
Overview ¶
Package css has the parts of CSS that htmlcore uses to style the widgets of pages that do not depend on its widgets: parsing style sheets (Parse), compiling and indexing selectors (CompileSelector, SelectorIndex), the declarations of the cascade (Origin, ValidDeclaration), and the values of properties: lengths (LengthEnv), colors (ParseColor), filters, transitions, fonts, masks and others. The cascade itself, which applies the declarations to the elements of a page as it is read, is in htmlcore.
Index ¶
- Constants
- Variables
- func AlignValue(v string) styles.Aligns
- func Angle(v string) float32
- func AspectRatio(v string) float32
- func BackgroundColor(v string) string
- func CalcPx(v string) (float32, bool)
- func ChOf(sh shaped.Shaper, s *styles.Style, em float64) float64
- func ColorFunc(v string) func() image.Image
- func ColorFunction(v string) (color.RGBA, bool)
- func CustomLength(fn string, vals []Linear, pct units.Units) units.Value
- func CutTopLevel(s string, sep byte) (before, after string, found bool)
- func EmLength(v string) float64
- func EmSpaces(em float64) string
- func ExpandSides(vals []string) []string
- func FontFamily(v string) rich.Family
- func FontShorthandValid(v string) bool
- func FontSource(s string) (url, format string)
- func GridColumns(v string) int
- func ImportURL(prelude string) (url, media string)
- func IsFontData(data []byte) bool
- func IsNameChar(ch byte) bool
- func IsPositionWord(f string) bool
- func LegacyDisplay(v string) string
- func MaskOffset(v string) (x, y float32)
- func MaskPosition(v string) (x, y float32)
- func MaskSize(v string, box, intrinsic math32.Vector2, dp float32) math32.Vector2
- func MaskURL(v string) string
- func MediaRangeMatches(f string, width, height float32) bool
- func Parse(style string) *douceur.Stylesheet
- func ParseColor(v string) image.Image
- func ParseFlex(v string) (grow, shrink float32, basis string, ok bool)
- func PercentUnit(u units.Units) bool
- func PropertyName(p string) string
- func PseudoSelector(sel string) (base, kind string, ok bool)
- func RemoveStray(style string) string
- func ResolveMaskSize(env *LengthEnv, v string) string
- func RewriteSelector(sel string) string
- func Rotate(_, v string) float32
- func SelectNodes(root *html.Node, sel string) []*html.Node
- func SelectorKey(sel string) (byte, string)
- func SetBorderStyle(s *styles.Style, i int, v string)
- func SetFontWeight(s, ps *styles.Style, v string)
- func SetSide[T any](s *sides.Sides[T], i int, v T)
- func SetValueSide(s *sides.Values, i int, v units.Value)
- func SideDots(v *sides.Values, dots func(v *units.Value) float32) sides.Floats
- func SideIndex(prop string) int
- func Specificity(sel string) int
- func SplitColors(v string) []string
- func SplitSelectors(list string) []string
- func SplitTopLevel(s string, sep byte) []string
- func SplitTopLevelSpaces(v string) []string
- func SupportsMatches(cond string) bool
- func Translate(prop, v string) (x, y string, ok bool)
- func UnicodeRangeHas(urange string, r rune) bool
- func UnitlessCalc(v string) (float32, bool)
- func ValidDeclaration(prop, value string) bool
- func WebFontFamily(v string) string
- func ZeroAreaClip(prop, v string) bool
- func ZeroLength(v string) bool
- func ZeroScale(v string) bool
- type CompiledSelector
- type ContainerCond
- type Filter
- type KeyMask
- type LengthEnv
- type Linear
- type Origin
- type ScopeKind
- type SelectorIndex
- type Transition
Constants ¶
const ContainerMark = "--container:"
ContainerMark marks the prelude of an @supports rule that is an @container rule (see [containerRule]).
const HoverAttr = "data-htmlcore-hover"
HoverAttr is the attribute of the elements that are hovered while a page is read (see htmlcore.Context.Hovered), which no element of a document has.
const LineHeightNormal = 1.362
LineHeightNormal is the line height of the "normal" value, which is given by the metrics of the font in browsers; this is the value for the default Noto Sans font.
const ModalAttr = "data-htmlcore-modal"
ModalAttr is the attribute of the dialogs that are shown as modal (as by the showModal of scripts), which the :modal selector of CSS selects (and the style of browsers for them, in the top layer).
Variables ¶
var BorderStyleNames = map[string]bool{"none": true, "hidden": true, "solid": true, "dotted": true, "dashed": true, "double": true, "groove": true, "ridge": true, "inset": true, "outset": true}
var FontProperties = map[string]bool{ "font": true, "font-family": true, "font-size": true, "font-weight": true, "font-style": true, "line-height": true, }
FontProperties are the properties of fonts, which are compiled first (with line-height, which the font shorthand sets).
var FontSizeKeywords = map[string]float32{"xx-small": 9, "x-small": 10, "small": 13, "medium": 16,
"large": 18, "x-large": 24, "xx-large": 32, "xxx-large": 48}
FontSizeKeywords are the font sizes of the absolute size keywords, in px.
var FontSizes = map[string]float32{
"xx-small": 9, "x-small": 10, "small": 13, "medium": 16, "large": 18,
"x-large": 24, "xx-large": 32, "xxx-large": 48,
}
FontSizes are the absolute font size keywords, in px.
var InheritedProperties = map[string]bool{ "color": true, "font": true, "font-family": true, "font-size": true, "font-style": true, "font-weight": true, "font-variant": true, "line-height": true, "letter-spacing": true, "word-spacing": true, "text-align": true, "text-indent": true, "text-transform": true, "text-shadow": true, "white-space": true, "visibility": true, "cursor": true, "direction": true, "pointer-events": true, "list-style": true, "list-style-type": true, "list-style-position": true, "quotes": true, "word-break": true, "overflow-wrap": true, "hyphens": true, "tab-size": true, "border-collapse": true, "border-spacing": true, "caption-side": true, "empty-cells": true, }
InheritedProperties are the properties that are inherited in CSS, for which unset is inherit (and initial for the others).
var KeySeed = maphash.MakeSeed()
KeySeed is the seed of the hashes of the bits of keys.
var KeywordLonghands = map[string][]string{
"font": {"font-style", "font-weight", "font-size", "line-height", "font-family"},
"margin": {"margin-top", "margin-right", "margin-bottom", "margin-left"},
}
KeywordLonghands are the longhands of the shorthands, which their CSS-wide keywords (inherit, initial) apply to (the others are applied to the style whole, see styles.Style.FromProperty).
var LogicalProperties = map[string]string{
"inline-size": "width", "block-size": "height",
"min-inline-size": "min-width", "max-inline-size": "max-width",
"min-block-size": "min-height", "max-block-size": "max-height",
"margin-inline-start": "margin-left", "margin-inline-end": "margin-right",
"margin-block-start": "margin-top", "margin-block-end": "margin-bottom",
"padding-inline-start": "padding-left", "padding-inline-end": "padding-right",
"padding-block-start": "padding-top", "padding-block-end": "padding-bottom",
"border-inline-start": "border-left", "border-inline-end": "border-right",
"border-block-start": "border-top", "border-block-end": "border-bottom",
"border-inline-start-width": "border-left-width", "border-inline-end-width": "border-right-width",
"border-block-start-width": "border-top-width", "border-block-end-width": "border-bottom-width",
"border-inline-start-color": "border-left-color", "border-inline-end-color": "border-right-color",
"border-block-start-color": "border-top-color", "border-block-end-color": "border-bottom-color",
"inset-inline-start": "left", "inset-inline-end": "right",
"inset-block-start": "top", "inset-block-end": "bottom",
"border-start-start-radius": "border-top-left-radius", "border-start-end-radius": "border-top-right-radius",
"border-end-start-radius": "border-bottom-left-radius", "border-end-end-radius": "border-bottom-right-radius",
}
LogicalProperties are the physical properties for the logical properties of CSS, for horizontal, left to right text.
var URLPattern = regexp.MustCompile(`url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"\s]*))\s*\)`)
URLPattern matches the url() of CSS values, with its URL quoted or not.
var WebkitAliases = map[string]bool{ "transform": true, "transform-origin": true, "box-sizing": true, "box-shadow": true, "border-radius": true, "flex": true, "flex-direction": true, "flex-wrap": true, "flex-flow": true, "flex-grow": true, "flex-shrink": true, "flex-basis": true, "order": true, "align-items": true, "align-self": true, "justify-content": true, "user-select": true, "appearance": true, }
WebkitAliases are the properties whose -webkit- prefixed names are aliases of them in browsers, which pages may set only with the prefix.
Functions ¶
func AlignValue ¶
AlignValue returns the alignment for the given CSS value.
func AspectRatio ¶
cssTranslate returns the translation of the given value of the transform property (the sum of its translate functions; the other functions, as rotate and scale, are not supported), or of the translate property, as the lengths of x and y. It returns false if it is not valid. AspectRatio returns the ratio of width to height of the given value of the aspect-ratio property (as 16 / 9, 1.5, or auto 4/3), or 0 for none (auto).
func BackgroundColor ¶
BackgroundColor returns the color of the given background value.
func CalcPx ¶
CalcPx returns the value in px of the given length, which can be a calc() expression of lengths in px, em, and rem (of 16px), and numbers, with +, -, *, / and parentheses, as in media queries.
func ChOf ¶
ChOf returns the size of the ch unit of CSS in px for the font of the given style (whose font size is the given em, in px), measured with the given text shaper: the advance of its 0 glyph, as in browsers. It is 0 if it cannot be measured.
func ColorFunc ¶
ColorFunc returns a function that returns the given CSS color (or nil if it is not one). A uniform color is parsed once, and is shared by the styles; other colors (as gradients) are parsed for each style, so that each has its own.
func ColorFunction ¶
ColorFunction returns the color of the given CSS rgb(), rgba(), hsl() or hsla() function, with the syntax of CSS: components that are numbers or percentages, separated by commas or spaces, and an alpha (after a comma or a /) from 0 to 1 or a percentage.
func CustomLength ¶
CustomLength returns a custom length (see units.Value.Custom) of the given CSS math function (calc, min, max, or clamp) of the given linear lengths, with percentages of the given unit, which core computes with the size of the parent in the layout: a percentage and a length cannot be one unit (as the width of calc(100% - 256px) of the grids of github.com, which was taken to be 100%).
func CutTopLevel ¶
CutTopLevel cuts s around the first sep that is not in parentheses.
func EmLength ¶
EmLength returns the given CSS length in em, with px for 16px to the em (and rem as em), or 0 if it is not one of these.
func EmSpaces ¶
EmSpaces returns a string of space characters (which are not collapsed or trimmed) about as wide as the given number of em.
func ExpandSides ¶
ExpandSides expands the 1 to 4 values of a CSS shorthand for the sides of a box into the values for top, right, bottom, left.
func FontFamily ¶
FontFamily returns the font family for the given CSS font-family list, the first generic family in it, or one for a common font name.
func FontShorthandValid ¶
FontShorthandValid returns whether the given value of the font shorthand is valid: a size (as 14px or medium, after any style, variant and weight) and a family after it, or a CSS-wide keyword or system font.
func FontSource ¶
FontSource returns the URL and format of the given source of the src of an @font-face rule: url(...) format(...), or "" for local(...).
func GridColumns ¶
GridColumns returns the number of columns of a grid-template-columns value.
func ImportURL ¶
ImportURL returns the URL and the media query list of the given prelude of an @import rule (url("x") media, or "x" media).
func IsFontData ¶
IsFontData returns whether the given data is a font that the text shapers read: TrueType, OpenType (and collections of them), or WOFF.
func IsNameChar ¶
func IsPositionWord ¶
IsPositionWord returns whether the given word is one of a position (a keyword or a length), not a color.
func LegacyDisplay ¶
LegacyDisplay returns the display for the given value of the display property, which is that of the prefixed legacy values: -webkit-box (as with -webkit-line-clamp, in a column) is a block, and -webkit-flex flex; unset and initial are inline.
func MaskOffset ¶
MaskOffset returns the offsets in px of the given mask-position (or background-position) that are lengths (as the positions of the images in a sprite, as "0 -261px"), which are from the left and top.
func MaskPosition ¶
MaskPosition returns the fractions of the extra space of the box on each axis that are before the mask image, for the given mask-position (as "50% 50%", "center", or "left top").
func MaskSize ¶
MaskSize returns the size of the mask image in the given box, for the given mask-size (as "20px auto", "contain", "cover", or "50%"), and the intrinsic size of the image, in pixels, with the given dots per px.
func MaskURL ¶
MaskURL returns the URL of the url() of the given value of mask-image (or the mask shorthand), or "" if it has none (as none).
func MediaRangeMatches ¶
MediaRangeMatches returns whether the given media feature in the range syntax matches the given viewport width and height.
func Parse ¶
func Parse(style string) *douceur.Stylesheet
Parse parses the given style sheet. If it does not parse as a whole, as with constructs that the parser does not support, each of its top-level rules is parsed on its own, so that only the rules that do not parse are left out.
func ParseColor ¶
ParseColor returns the given CSS color, or nil if it is not one.
func ParseFlex ¶
ParseFlex returns the grow, shrink, and basis of the given value of the flex shorthand, as in CSS, where a number alone (as flex: 1) has a basis of 0, not of the width of the item.
func PercentUnit ¶
PercentUnit returns whether the given unit is a percentage of a size of the parent or the element, which is not definite for a replaced element.
func PropertyName ¶
PropertyName returns the name of the property of a declaration with the given name: in lower case, and the standard one of a legacy alias of it (see [legacyAliases]).
func PseudoSelector ¶
PseudoSelector returns the selector of the elements of the given selector of a ::before or ::after pseudo-element (also :before and :after), and which of them it is, or false if it is not one.
func RemoveStray ¶
RemoveStray returns the given style sheet without what cannot be a rule where rules are expected (at the top level and in the blocks of grouping at-rules such as @media): statements that end with a semicolon but are not at-rules (as "a;b{...}"), and blocks without a selector (as "{a:b}", which CSS-in-JS libraries can make). The parser does not end on these (it does not skip a semicolon in a selector).
func ResolveMaskSize ¶
ResolveMaskSize returns the given mask-size with its lengths (as em and calc()) resolved to px with the given length environment, as maskSize reads px, percentages, auto, contain, and cover.
func RewriteSelector ¶
RewriteSelector rewrites the parts of the given selector that the selector library does not support as ones that it does: :is(X) and :where(X) as :not(:not(X)), and :focus-within and :focus-visible as :focus (which selects nothing, as for :hover, in a static rendering).
func Rotate ¶
Rotate returns the sum of the angles of the rotate functions of the given transform, in degrees.
func SelectNodes ¶
SelectNodes returns the nodes under root that the given selector selects.
func SelectorKey ¶
SelectorKey returns a part of the last compound selector of the given selector that every node that it selects has (see compiledSelector.key): its id, else its first class, else its element name, or none if it has none of them outside of functions and attribute selectors (or has escapes, which are not decoded here).
func SetBorderStyle ¶
SetBorderStyle sets the style of the given side of the border.
func SetFontWeight ¶
SetFontWeight sets the font weight.
func SetValueSide ¶
SetValueSide sets the given side (top, right, bottom, left) of the given values.
func SideIndex ¶
SideIndex returns the index (top, right, bottom, left) of the side in the name of the given property, such as "margin-left".
func Specificity ¶
Specificity returns the specificity of the given selector, as ids*10000 + (classes, attributes, pseudo-classes)*100 + types.
func SplitColors ¶
SplitColors splits the given value into fields at spaces that are not inside of parentheses, as in rgb(...) and calc(...).
func SplitSelectors ¶
SplitSelectors splits the given selector list at the commas that are not in parentheses, brackets, or quotes.
func SplitTopLevel ¶
SplitTopLevel splits the given string at the given separator where it is not in parentheses or quotes (as a list of sources with url()s).
func SplitTopLevelSpaces ¶
SplitTopLevelSpaces splits the given value at the spaces that are not in parentheses (as "calc(1rem + 4px) auto").
func SupportsMatches ¶
SupportsMatches returns whether the given condition of an @supports rule is true in Chrome, which this follows: its features are supported, except the properties and values of other browsers (-moz-, -ms-, -o-) and of iOS, so that the fallbacks in @supports not (...) do not apply (as the widths of the sections of theguardian.com for browsers without display: grid, which made them narrow). The preludes of the other grouping rules that are parsed as @supports (as @layer name) are true.
func UnicodeRangeHas ¶
UnicodeRangeHas returns whether the given unicode-range includes the given rune.
func UnitlessCalc ¶
UnitlessCalc returns the value of the given calc() expression of numbers only (no lengths or percentages), and whether it is one.
func ValidDeclaration ¶
ValidDeclaration returns whether a declaration of the given property and value is valid, as in browsers, which drop the declarations that are not when they are parsed, so that the declarations before them of the same property apply (as height: 100vh before height: -webkit-fill-available, of the captcha frames of DataDome for Safari, which were of the height of no content). A size of -webkit-fill-available is invalid here too, as it is not laid out, and the declaration before it is meant as a fallback for it. Custom properties and values with variables are only known when they are used.
func WebFontFamily ¶
WebFontFamily returns the first of the families of the given value of font-family that is a web font that has been loaded, or "".
func ZeroAreaClip ¶
ZeroAreaClip returns whether the given value of clip (a rect) or of clip-path (an inset) clips the element to nothing, as in the visually hidden elements of pages (rect(0 0 0 0), rect(1px, 1px, 1px, 1px), inset(50%)).
func ZeroLength ¶
ZeroLength returns whether the given CSS length is zero (as 0, 0px, 0%).
Types ¶
type CompiledSelector ¶
type CompiledSelector struct {
Sel cascadia.Sel
Specificity int
// KeyKind and Key are a part of the last compound selector that every
// node that it selects has, for finding them in a [SelectorIndex]:
// an id ('#'), a class ('.'), or an element name ('t'), or none (0).
KeyKind byte
Key string
// Anc is the mask of the keys of the elements that the elements that
// it selects are in (see [AncestorKeys]).
Anc KeyMask
}
CompiledSelector is a compiled selector, with its specificity.
func CompileSelector ¶
func CompileSelector(sel string) *CompiledSelector
CompileSelector returns the compiled selector, or nil if it is not supported.
type ContainerCond ¶
type ContainerCond struct {
Name, Query string
Outer *ContainerCond
}
ContainerCond is the condition of an @container rule: the name of the container that it queries ("" for the nearest one), and its query (as (width <= 799px)), and that of an @container rule that it is in.
func ParseContainerCond ¶
func ParseContainerCond(prelude string, outer *ContainerCond) *ContainerCond
ParseContainerCond returns the condition of an @container rule of the given prelude (as "spotlight (width <= 799px)"), in the given one.
type Filter ¶
type Filter []filterFunc
Filter is the filter property of CSS for images: a list of the functions that transform the colors of their pixels, in order (as the white submenu wedges of pkg.go.dev, grey icons with a filter of brightness(0) saturate(1) invert(1)).
func ParseFilter ¶
ParseFilter returns the color functions of the given filter value, or nil if it has none (or none that is supported).
type KeyMask ¶
type KeyMask [2]uint64
KeyMask is a set of keys of elements (see AncestorKeys), as bits of a Bloom filter: a set that has a key has its bit, and a set may have the bit of a key that it does not have.
func AncestorKeys ¶
AncestorKeys returns the mask of the keys that the elements that an element that the given selector selects is in must have: those of its compound selectors that are followed by a combinator of descendants or children (whose elements are ones that it is in, also before a combinator of siblings, as the siblings of an element are in the same elements), outside of parentheses (as of :not), or none for a selector with escapes or namespaces.
func CompoundKeys ¶
CompoundKeys returns the mask of the keys that an element that the given compound selector selects has: its name, and its ids and classes outside of parentheses and brackets.
func OwnKeys ¶
OwnKeys returns the mask of the keys of the given element: its name, id, and classes.
type LengthEnv ¶
type LengthEnv struct {
Em, Vw, Vh float64
FixedVh bool
Rem float64
// VhUsed, if set, is set when a length uses vh (or vmin and vmax) of
// the viewport (see htmlcore.Context.ViewportHeightUsed).
VhUsed *atomic.Bool
// Cqw and Cqh are the container query units (1% of the width and the
// height of the container of the element; see container.go), which
// are those of the viewport (vw, vh) if they are not set.
Cqw, Cqh float64
// Ch, if set, returns the size of the ch unit of the element in px:
// the advance of the 0 glyph of its font, as in CSS.
Ch func() float64
}
LengthEnv has the sizes that relative lengths are resolved with, in px: the em (font size of the element), the rem (font size of the html element), and 1% of the viewport width and height. fixedVh is whether Vh is from htmlcore.Context.MediaHeight, to which all vh lengths are then relative (as dp); otherwise vh stays a unit of core, except in calc(). Each style pass of a widget has its own (see htmlcore.Context.browserStyler), and reading a page uses that of the page (see htmlcore.Context.readEnv).
func DefaultLengthEnv ¶
func DefaultLengthEnv() *LengthEnv
DefaultLengthEnv returns the length environment of a 16px font and an 800x600 viewport, for lengths that are absolute.
func (*LengthEnv) BorderWidth ¶
BorderWidth returns the given CSS border width.
func (*LengthEnv) Length ¶
Length parses the given CSS length, with px as dp (which is what px is in browsers), % as the given unit, and lengths without units, as in the attributes of HTML elements, as dp.
type Linear ¶
type Linear struct {
Pct, Px float64
}
Linear is a length that is a percentage plus an absolute length in px, the value of a calc() expression of CSS.
type Origin ¶
type Origin int
Origin is the origin of a CSS declaration, which orders the cascade.
const ( // OriginUserAgent is for the user agent (default) styles. OriginUserAgent Origin = iota // OriginHint is for the presentational attributes of // elements (width, bgcolor etc), which come before author styles. OriginHint // OriginAuthor is for the styles of the page. OriginAuthor // OriginInline is for the style attribute of an element. OriginInline )
type ScopeKind ¶
type ScopeKind int8
ScopeKind is the kind of the elements that a rule of a style sheet of a shadow tree selects (see htmlcore.Context.inScope).
const ( // ScopeAll is the elements of its tree (or, for a rule of the // document, the elements of the document). ScopeAll ScopeKind = iota // ScopeHost is the host of the shadow root (:host). ScopeHost // ScopeSlotted is the children of the host in the slots of the shadow // tree (::slotted()). ScopeSlotted // ScopeAny is all elements, of the document and of shadow trees, for // the rules of the user agent. ScopeAny )
func ScopedSelector ¶
ScopedSelector returns the given selector of a style sheet of a shadow tree as one of the elements of the composed tree, and the kind of the elements that it selects, or false if it can not be: :host (or :host(X)) alone selects the host (as X); :host before other compounds is the host (as X, or any element, which the host is of the elements of its tree); ::slotted(X) selects the children X of the slots (as slot > X); :host-context() and ::part() are not supported.
type SelectorIndex ¶
type SelectorIndex struct {
Root *html.Node
ByID, ByClass, ByTag map[string][]*html.Node
// contains filtered or unexported fields
}
SelectorIndex has the element nodes of a document by id, class, and element name, in document order, for selecting the nodes of style rules (see htmlcore.Context.selectNodes), so that each selector is only matched against the nodes that have its key, as in browsers.
func NewSelectorIndex ¶
func NewSelectorIndex(root *html.Node) *SelectorIndex
NewSelectorIndex returns the index of the element nodes under root.
type Transition ¶
type Transition struct {
// Node is the element.
Node *html.Node
// Property is the name of the property, as for the propertyName of
// its transitionend event.
Property string
// Delay is the time before the transition starts.
Delay time.Duration
// Duration is the time that the transition takes.
Duration time.Duration
}
Transition is a transition of a property of an element, which a change of its declarations starts (see htmlcore.Context.OnTransition). It is not rendered: the element has its new style at once, but the transitionend event is dispatched when it would end, as pages wait for it.
func TransitionsOf ¶
TransitionsOf returns the transitions of the given properties of the given element, which have changed, for its given declarations (with their transition, transition-property, transition-duration and transition-delay).