css

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyTextTransform

func ApplyTextTransform(text, transform string) string

ApplyTextTransform returns text with the CSS text-transform applied. Supported values: "none", "uppercase", "lowercase", "capitalize". Unknown values pass through unchanged. Capitalize is English-centric (per the CSS spec it's locale-dependent; this implementation uppercases the first rune of each whitespace-delimited word).

func ExpandShorthands

func ExpandShorthands(decls map[string]string) map[string]string

ExpandShorthands takes a map of CSS property→value declarations and returns a new map with shorthand properties expanded to their longhand equivalents. Unrecognised properties are passed through unchanged.

func ParseCSSURL

func ParseCSSURL(value string) (string, bool)

func ParseLength

func ParseLength(value string, parentFontSize float64) float64

ParseLength converts a CSS length string to mm. parentFontSize (mm) is used to resolve em units. Returns 0 for unparseable values.

For calc() expressions, dispatches to the calc evaluator (without a width context; use ParseLengthCtx for % resolution inside calc()).

func ParseLengthCtx

func ParseLengthCtx(value string, parentFontSize, contextWidthMM float64) float64

ParseLengthCtx is a context-aware variant of ParseLength that resolves CSS percentage values against contextWidthMM (the parent's content width in mm) and dispatches calc(...) to the small expression evaluator below. parentFontSize is used for em/rem unit resolution.

When contextWidthMM is 0, percentages inside calc() resolve to 0.

func ParsePercentage

func ParsePercentage(val string) (float64, bool)

ParsePercentage parses a CSS percentage value (e.g. "25%") and returns the fractional equivalent (0.25 for "25%"). Returns (0, false) if val is not a valid percentage string.

func ResolveVars

func ResolveVars(value string, scope map[string]string) string

ResolveVars resolves CSS var(--name [, fallback]) references in value against the given scope map. Returns the string with all var() references resolved; nested references are followed using a visited set to detect cycles. On a cycle, that var() resolves to its fallback (or empty).

scope keys must include the leading "--" prefix (e.g. "--accent"). scope may be nil; in that case, var() with no fallback resolves to "" and var(name, fb) resolves to fb.

func Specificity

func Specificity(a, b, c, d int) int

Specificity returns an integer encoding the CSS a-b-c-d specificity. a=inline, b=#id count, c=class/attr/pseudo-class count, d=element/pseudo-element count. Higher = more specific.

Types

type ComputedStyle

type ComputedStyle struct {
	// Font
	FontFamily string
	FontSize   float64 // mm
	FontWeight string  // "normal" | "bold"
	FontStyle  string  // "normal" | "italic"

	// Text
	Color          *RGBColor
	TextAlign      string // "left" | "center" | "right" | "justify"
	TextDecoration string // "none" | "underline" | "line-through"
	LineHeight     float64

	// Box model (mm)
	PaddingTop    float64
	PaddingRight  float64
	PaddingBottom float64
	PaddingLeft   float64

	MarginTop    float64
	MarginRight  float64
	MarginBottom float64
	MarginLeft   float64

	// Border (mm / style / color)
	BorderTopWidth    float64
	BorderRightWidth  float64
	BorderBottomWidth float64
	BorderLeftWidth   float64

	BorderTopStyle    string
	BorderRightStyle  string
	BorderBottomStyle string
	BorderLeftStyle   string

	BorderTopColor    *RGBColor
	BorderRightColor  *RGBColor
	BorderBottomColor *RGBColor
	BorderLeftColor   *RGBColor

	// Background
	BackgroundColor    *RGBColor
	BackgroundGradient *Gradient // set when background-image is a gradient
	BackgroundImageURL string    // set when background-image is url(...)
	BackgroundSize     string
	BackgroundPosition string
	BackgroundRepeat   string
	BoxShadow          []Shadow // parsed box-shadow value (up to 4)
	TextShadow         *Shadow  // text-shadow compatibility field; points at first TextShadows entry
	TextShadows        []Shadow // parsed text-shadow value (up to 4)

	// Outline (mm / style / color / offset) — drawn outside the cell box.
	OutlineWidth  float64
	OutlineStyle  string // "solid" | "dashed" | "dotted"
	OutlineColor  *RGBColor
	OutlineOffset float64 // mm; positive pushes outline further out

	// Border radius (mm). BorderRadius is the uniform fallback; per-corner overrides it.
	BorderRadius            float64
	BorderRadiusTopLeft     float64
	BorderRadiusTopRight    float64
	BorderRadiusBottomLeft  float64
	BorderRadiusBottomRight float64

	// Layout
	Display        string // "block" | "inline" | "inline-block" | "none" | "flex" | "table" | ...
	Visibility     string // "visible" | "hidden" | "collapse"
	Width          float64
	Height         float64
	MinWidth       float64
	MaxWidth       float64
	MinHeight      float64
	MaxHeight      float64
	ObjectFit      string
	ObjectPosition string

	// Flex container properties
	FlexDirection  string // "row" | "column" | "row-reverse" | "column-reverse"
	FlexWrap       string // "nowrap" | "wrap" | "wrap-reverse"
	JustifyContent string // "flex-start" | "center" | "flex-end" | "space-between" | "space-around"
	AlignItems     string // "flex-start" | "center" | "flex-end" | "stretch"

	// Flex item properties (cross-axis)
	AlignSelf string  // "auto" | "flex-start" | "flex-end" | "center" | "stretch"
	RowGap    float64 // mm
	ColumnGap float64 // mm

	// Flex item properties
	FlexGrow      float64 // default 0; used as proportional weight in layout
	FlexShrink    float64 // parsed/stored; no independent layout effect (quantizer prevents overflow)
	FlexBasis     float64 // mm; 0 means auto unless FlexBasisAuto or FlexBasisPct set
	FlexBasisAuto bool    // true when flex-basis:auto was explicitly set
	FlexBasisPct  float64 // >0 when flex-basis was a percentage (0–100 scale)
	Order         int     // CSS order property; lower = earlier; 0 is default

	// List marker style (for ul/ol). Supports standard CSS values plus the
	// "decimal-circle" extension that renders numbers inside filled discs.
	ListStyleType string

	// Opacity multiplies into all descendant color alpha values (0 = invisible, 1 = opaque).
	Opacity float64

	// Typography
	LetterSpacing    float64 // mm; applied via SetCharSpacing
	TextTransform    string  // "none" | "uppercase" | "lowercase" | "capitalize"
	TextIndent       float64 // mm; first-line indent
	WhiteSpace       string  // "normal" | "nowrap" | "pre" | "pre-wrap" | "pre-line"
	VerticalAlign    string  // "baseline" | "sub" | "super" | "sup"
	Content          string  // generated content for ::before/::after
	CounterReset     string  // raw counter-reset value, evaluated by the translator
	CounterIncrement string  // raw counter-increment value, evaluated by the translator
	Quotes           string  // raw quotes value, evaluated by generated content

	// Page break hints.
	PageBreakBefore string // "always" | "avoid" | "auto"
	PageBreakAfter  string // "always" | "avoid" | "auto"
	BreakInside     string // "avoid" | "auto"

	// CSS custom properties (--name: value). Stored as a flat map per element;
	// cascade inheritance is handled by callers (computeNodeStyle) which copy
	// from the parent's Vars map before applying child rules.
	Vars map[string]string
	// contains filtered or unexported fields
}

ComputedStyle holds the resolved CSS property values for a DOM element.

func NewComputedStyle

func NewComputedStyle() *ComputedStyle

NewComputedStyle returns a ComputedStyle with sensible zero-value defaults. Display defaults to "" (unset) — callers should treat "" the same as "block".

func (*ComputedStyle) Apply

func (s *ComputedStyle) Apply(prop, val string, parent *ComputedStyle)

Apply sets a single CSS property. Parent is used for em resolution. CSS custom properties (--*) are stored on s.Vars; standard properties get var(...) references resolved against s.Vars (inheriting parent's vars implicitly via computeNodeStyle's pre-population). Apply resolves val for prop and stores the result. Callers that know the parent content width should use ApplyCtx so that calc() and % resolve correctly against the context width.

func (*ComputedStyle) ApplyCtx

func (s *ComputedStyle) ApplyCtx(prop, val string, parent *ComputedStyle, ctxWidth float64)

ApplyCtx is Apply with an explicit context width (parent content width in mm). Width-relative properties (width, padding, margin, text-indent) resolve percentages and calc(…%) against ctxWidth.

func (*ComputedStyle) SetUnsupportedHandler

func (s *ComputedStyle) SetUnsupportedHandler(fn func(prop, val string))

SetUnsupportedHandler registers a callback invoked for unrecognised CSS properties.

type ConicGradient

type ConicGradient struct {
	FromDeg float64
	CX, CY  float64 // centre as fraction of width/height (0.5 = center)
	Stops   []GradientStop
}

ConicGradient holds a parsed conic-gradient().

func ParseConicGradient

func ParseConicGradient(s string) (*ConicGradient, error)

ParseConicGradient parses a CSS conic-gradient(...) function string.

type Gradient

type Gradient struct {
	Kind   GradientKind
	Linear *LinearGradient
	Radial *RadialGradient
	Conic  *ConicGradient
}

Gradient is a union of LinearGradient and RadialGradient. Only the field corresponding to Kind is populated.

type GradientKind

type GradientKind int

GradientKind identifies the type of gradient.

const (
	GradientLinear GradientKind = iota
	GradientRadial
	GradientConic
)

type GradientStop

type GradientStop struct {
	Color    RGBColor
	Position float64 // 0.0–1.0; -1 means "auto" (evenly distributed)
}

GradientStop is a single color+position stop in a gradient.

type LinearGradient

type LinearGradient struct {
	AngleDeg float64
	Stops    []GradientStop
}

LinearGradient holds a parsed linear-gradient().

func ParseLinearGradient

func ParseLinearGradient(s string) (*LinearGradient, error)

ParseLinearGradient parses a CSS linear-gradient(...) function string, including the "linear-gradient(" prefix and closing ")".

type RGBColor

type RGBColor struct {
	R, G, B int
	A       float64 // 0 = transparent, 1 = opaque; default is 1.0
}

RGBColor holds a parsed CSS color with optional alpha. A is in the range [0, 1] where 0 = transparent and 1 = opaque. Colors created by NewRGBColor or ParseColor always have A = 1.0 unless an alpha channel was explicitly specified.

func NewRGBColor

func NewRGBColor(r, g, b int) RGBColor

NewRGBColor constructs an opaque RGBColor.

func ParseColor

func ParseColor(val string) *RGBColor

ParseColor parses common CSS color formats:

  • Named colors (full CSS Color Level 4 set, ~147 entries)
  • #rgb, #rrggbb, #rgba (4-digit), #rrggbbaa (8-digit)
  • rgb(), rgba() — integer or percentage channels
  • hsl(), hsla()
  • "transparent" → {0,0,0,0}

Returns nil for unrecognised or invalid input.

type RadialGradient

type RadialGradient struct {
	Circle bool
	CX, CY float64 // centre as fraction of width/height (0.5 = center)
	Stops  []GradientStop
}

RadialGradient holds a parsed radial-gradient().

func ParseRadialGradient

func ParseRadialGradient(s string) (*RadialGradient, error)

ParseRadialGradient parses a CSS radial-gradient(...) function string.

type Shadow

type Shadow struct {
	OffsetX    float64   // mm
	OffsetY    float64   // mm
	BlurRadius float64   // mm; 0 when omitted
	Spread     float64   // mm; 0 when omitted (box-shadow only)
	Color      *RGBColor // nil when no color specified
	Inset      bool      // true when "inset" keyword is present
}

Shadow holds the parsed values of a single CSS shadow entry (box-shadow or text-shadow).

func ParseFilterDropShadow

func ParseFilterDropShadow(val string) ([]Shadow, error)

ParseFilterDropShadow extracts CSS filter drop-shadow(...) functions and parses them into ordinary shadows for the PDF cell shadow renderer.

func ParseShadow

func ParseShadow(val string) ([]Shadow, error)

ParseShadow parses a CSS shadow value string (box-shadow or text-shadow format). It supports multi-shadow comma-separated lists (up to 4 entries). Returns an error when the value is empty or unparseable.

Jump to

Keyboard shortcuts

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