css

package
v0.5.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AbsolutizeSourcePaths

func AbsolutizeSourcePaths(cssText, dir string) string

AbsolutizeSourcePaths rewrites relative paths in `@source "..."` and `@import "tailwindcss" source("...")` to absolute paths under dir, so they still resolve once the sheet has been merged into another file.

func EscapeClass added in v0.4.0

func EscapeClass(s string) string

EscapeClass converts a Tailwind class name into a CSS-selector-safe identifier per the CSSOM `CSS.escape` algorithm, so selectors like `w-1/2`, `w-[100px]`, `bg-red-500/50`, `content-['a.b']` are valid. Rules (https://drafts.csswg.org/cssom/#serialize-an-identifier): - U+0000 -> U+FFFD - control chars (U+0001-U+001F, U+007F) -> \HEX - a leading digit -> \HEX - a digit in the second position when the first char is '-' -> \HEX - a lone "-" -> \-

  • '-' '_' and ASCII alphanumerics are safe elsewhere
  • everything else is backslash-escaped (with a trailing space when the escaped char is a hex digit, to disambiguate)

func ExpandApply added in v0.4.0

func ExpandApply(cssText string, theme TailwindTheme) (string, []string)

ExpandApply expands `@apply utility...;` directives anywhere in user CSS into the declarations those utilities produce, using the given theme. It supports plain utilities. Variant utilities (`hover:*`, `md:*`), descendant-selector utilities (`space-x-*`), and unknown classes cannot be represented as plain declarations, so they are dropped from the output and returned in `unresolved` for the caller to warn about.

func ExtractAtTheme added in v0.4.0

func ExtractAtTheme(cssText string) map[string]string

ExtractAtTheme returns the custom properties declared in `@theme` blocks, keyed without the leading `--` (e.g. "color-brand-500" -> "#f00").

func GenerateTailwind

func GenerateTailwind(root string, cfg *TailwindConfig) (string, error)

GenerateTailwind runs the full Tailwind pipeline: scan classes -> generate CSS.

func GenerateTailwindWithOptions added in v0.4.0

func GenerateTailwindWithOptions(root string, cfg *TailwindConfig, opts TailwindOptions) (string, error)

GenerateTailwindWithOptions is GenerateTailwind with explicit options.

func GenerateTailwindWithTheme added in v0.4.0

func GenerateTailwindWithTheme(root string, cfg *TailwindConfig, opts TailwindOptions, themeVars map[string]string) (string, error)

GenerateTailwindWithTheme is GenerateTailwindWithOptions with v4 `@theme` variables merged into the theme before generation.

func HoistImports

func HoistImports(css string) string

HoistImports moves @charset and @import statements that appear after other rules to the top of the sheet, where browsers honour them. Leading @layer statements keep their position ahead of the hoisted imports.

func InlineImports

func InlineImports(css, basePath string) string

InlineImports resolves and inlines @import directives in CSS content. Paths resolve relative to basePath, which is also the containment root. External imports are hoisted to the top, unresolved ones are left in place.

func InlineImportsWith

func InlineImportsWith(css, baseDir string, opts ImportOptions) string

InlineImportsWith inlines @import directives found at the top level of css. baseDir is the directory of the sheet that css came from.

func MergeAtTheme added in v0.4.0

func MergeAtTheme(theme *TailwindTheme, vars map[string]string)

MergeAtTheme applies v4 `@theme` variables to a theme (see AtTheme.Apply). Variables are applied in name order.

func Minify

func Minify(cssText string) string

Minify compacts a stylesheet. Value-level transforms (hex shortening, rgb to hex, zero units, calc folding) run only on declaration values; selectors, at-rule preludes, names and custom property values are never rewritten.

func ProcessModule

func ProcessModule(path, content string) (scopedCSS string, mapping map[string]string, err error)

ProcessModule scopes a CSS Module without resolving cross-file composes. See ProcessModuleWith.

func RemoveAtRuleBlock added in v0.4.0

func RemoveAtRuleBlock(s, prefix string) string

RemoveAtRuleBlock removes every `prefix ... }` block (prefix ends just after the opening brace and sentinel) from s, brace-balanced and string/comment-aware.

func RemoveDuplicateDeclarations added in v0.4.0

func RemoveDuplicateDeclarations(css string) string

RemoveDuplicateDeclarations folds duplicate declarations within each rule, keeping the last value, while preserving the original formatting (whitespace, newlines, comments). Unlike css.Minify it performs no whitespace or value optimization, so it is safe to apply when minification is disabled.

func RewriteURLs

func RewriteURLs(css string, fn func(ref string) (string, bool)) string

RewriteURLs calls fn for every `url(...)` reference in css (quoted or bare, any case) and replaces the reference with fn's result when ok is true. Comments, other strings and `@import` statements are left untouched.

func ScanAtTheme added in v0.4.0

func ScanAtTheme(root string, opts TailwindOptions) map[string]string

ScanAtTheme walks the Tailwind scan directories and merges every `@theme` block found in `.css` files into a single variable map.

func SplitCSSRules added in v0.4.0

func SplitCSSRules(cssText string) []string

SplitCSSRules splits a stylesheet into top-level rule units (used by the build to prune unused CSS-module rules). Nested at-rules (`@media`, `@supports`, `@keyframes`) are kept whole; strings and comments are honoured so braces inside them do not split a rule.

func StripAtTailwind added in v0.4.0

func StripAtTailwind(css string) string

StripAtTailwind removes `@tailwind base|components|utilities;` directives. Krate generates Tailwind output itself, so a leftover directive would ship as an invalid at-rule.

func StripTailwindDirectives

func StripTailwindDirectives(cssText string) string

StripTailwindDirectives removes the CSS-first directives (and the legacy `@tailwind` ones) from shipped CSS, so no at-rule reaches the browser that it would ignore or fetch (`@import "tailwindcss"` would 404).

func TailwindPreflight added in v0.4.0

func TailwindPreflight(theme TailwindTheme) string

TailwindPreflight returns Tailwind v4's Preflight base reset (opt-in via `tailwind.preflight`). The --tw-* composition variables are not set here: utilities carry inline fallbacks and KeyframesCSS registers them.

func UnwrapAtRuleBlock added in v0.4.0

func UnwrapAtRuleBlock(s, prefix string) string

UnwrapAtRuleBlock replaces every `prefix ... }` block with its inner content.

Types

type Asset

type Asset struct {
	Path     string
	Content  string
	IsModule bool
}

func Collect

func Collect(dir string) ([]*Asset, error)

type AtTheme

type AtTheme struct {
	Vars []ThemeVar
	// Keyframes maps a name to its block body (without the @keyframes wrapper).
	Keyframes map[string]string
	// Warnings are unsupported constructs found while parsing.
	Warnings []string
}

AtTheme is the parsed content of all `@theme` blocks (Tailwind v4 CSS-first configuration), in source order.

func ParseAtTheme

func ParseAtTheme(cssText string) *AtTheme

ParseAtTheme parses every top-level `@theme` block in cssText with real brace matching (nested @keyframes and values containing "}" are handled).

func (*AtTheme) Apply

func (at *AtTheme) Apply(theme *TailwindTheme)

Apply merges the variables into theme, generating utilities for the supported namespaces: --color-*, --spacing, --spacing-*, --radius-*, --shadow-*, --opacity-*, --leading-*, --tracking-*, --breakpoint-*, --container-*, --font-*, --font-weight-*, --text-*(--line-height), --animate-*, plus `--ns-*: initial` and `--*: initial` resets.

func (*AtTheme) Merge

func (at *AtTheme) Merge(o *AtTheme)

Merge appends the other theme's variables and keyframes.

type ImportOptions

type ImportOptions struct {
	// Root is the containment root: resolved local files must stay inside it
	// (files found through Resolve inside a node_modules directory are also
	// allowed). Empty means the base directory passed to InlineImportsWith.
	Root string
	// Resolve maps a specifier that is not a file relative to the importing
	// file (for example a package path) to an absolute file, or "".
	Resolve func(spec, fromDir string) string
	// RewriteURLs is applied to the text of every imported file (not the entry
	// sheet) before its own imports are expanded. dir is the imported file's
	// directory.
	RewriteURLs func(css, dir string) string
	// OnRead is called with every file that was read.
	OnRead func(path string)
	// Warn receives a message for every import that could not be honoured.
	Warn func(msg string)
	// Tailwind says how `@import "tailwindcss"` and `tailwindcss/*` are
	// treated: TailwindResolve (default) resolves them like any package,
	// TailwindKeep leaves them for the Tailwind directive pass, and
	// TailwindOff leaves them and warns that Tailwind is not enabled.
	Tailwind TailwindImportMode
}

ImportOptions configures InlineImportsWith.

type ModuleOptions

type ModuleOptions struct {
	// Composed returns the class mapping of the module named by
	// `composes: x from "spec"`. The caller is responsible for making that
	// module's CSS part of the bundle.
	Composed func(spec string) (map[string]string, error)
}

ModuleOptions configures ProcessModuleWith.

type ModuleResult

type ModuleResult struct {
	CSS     string
	Mapping map[string]string
	// ComposesFrom lists every `from "spec"` file named by a composes
	// declaration, in source order and without duplicates.
	ComposesFrom []string
	// Warnings describe constructs that could not be honoured.
	Warnings []string
}

ModuleResult is the outcome of scoping a CSS Module.

func ProcessModuleWith

func ProcessModuleWith(path, content string, opts ModuleOptions) *ModuleResult

ProcessModuleWith scopes a CSS Module. Local class selectors are rewritten to `<name>_<hash>`; `:global(...)`, bare `:global` and `:local` switch scoping; local @keyframes names (and their references in animation and animation-name) are scoped; `composes:` declarations are removed and merged into the class mapping. Strings, comments, `url(...)` and attribute selectors are left untouched. The mapping also carries camelCase aliases of dashed class names and the scoped keyframes names.

type TailwindConfig

type TailwindConfig struct {
	Theme    TailwindTheme `json:"theme"`
	DarkMode string        `json:"darkMode"`
	// Warnings lists config constructs Krate cannot honour (unsupported keys,
	// values the static parser cannot evaluate). The caller prints them.
	Warnings []string `json:"warnings"`
	// Extend holds theme.extend values from the evaluated config; they merge
	// onto the built-in scales instead of replacing them.
	Extend TailwindTheme `json:"extend"`
}

TailwindConfig represents the tailwind.config.ts/js parsed values.

func LoadTailwindConfig

func LoadTailwindConfig(root string) *TailwindConfig

LoadTailwindConfig loads a tailwind.config file. It prefers a static parse (no JS runtime required); when `execute` is true or the static parse yields no theme, it evaluates the config in-process (esbuild + QuickJS). On any failure it returns defaults (a diagnostic is surfaced by the caller).

func LoadTailwindConfigWithOptions added in v0.4.0

func LoadTailwindConfigWithOptions(root string, opts TailwindOptions) *TailwindConfig

LoadTailwindConfigWithOptions is LoadTailwindConfig with explicit options.

func ParseTailwindConfigStatic added in v0.4.0

func ParseTailwindConfigStatic(path string) (*TailwindConfig, bool)

ParseTailwindConfigStatic parses a tailwind.config.{ts,js,mjs} file without executing it, extracting the common `theme` / `extend` / `darkMode` shapes. It deliberately handles a useful subset (object/array/string literals) so the Go-native build needs no Node; anything it cannot parse returns ok=false and the caller may fall back to in-process evaluation.

type TailwindDirectives

type TailwindDirectives struct {
	Root  string
	Theme AtTheme
	// Utilities maps a static @utility name to its declaration block.
	Utilities map[string]string
	// Variants maps @custom-variant names to a selector template or at-rule.
	Variants map[string]string
	// Sources are extra directories to scan (absolute); Excludes are skipped.
	Sources  []string
	Excludes []string
	// Inline are classes forced by @source inline(...).
	Inline []string
	// NoAutoSource is set by @import "tailwindcss" source(none).
	NoAutoSource bool
	Prefix       string
	Important    bool
	// Imported is true when an @import "tailwindcss" was seen.
	Imported bool
	// VarRefs are theme variables referenced via var(--name) in project CSS.
	VarRefs map[string]bool
	// contains filtered or unexported fields
}

TailwindDirectives accumulates the Tailwind v4 CSS-first directives found in project CSS: @import "tailwindcss", @theme, @source, @utility, @custom-variant, plus the unsupported @config/@plugin (reported).

func NewTailwindDirectives

func NewTailwindDirectives(root string) *TailwindDirectives

NewTailwindDirectives creates an empty collection rooted at root.

func ScanTailwindDirectives

func ScanTailwindDirectives(root string, opts TailwindOptions) *TailwindDirectives

ScanTailwindDirectives collects the Tailwind CSS-first directives from the project's .css files under the scan directories.

func (*TailwindDirectives) Add

func (d *TailwindDirectives) Add(cssText, baseDir string)

Add parses one CSS text. baseDir resolves relative @source paths.

func (*TailwindDirectives) ApplyTo

func (d *TailwindDirectives) ApplyTo(theme *TailwindTheme)

ApplyTo folds the directive content into a generator's theme.

func (*TailwindDirectives) MergeFrom

func (d *TailwindDirectives) MergeFrom(o *TailwindDirectives)

MergeFrom folds o into d; o's values win on conflicts.

func (*TailwindDirectives) Warnings

func (d *TailwindDirectives) Warnings() []string

Warnings returns the deduplicated warnings, sorted.

type TailwindGenerator

type TailwindGenerator struct {
	Theme TailwindTheme
	// Strict, when true, collects classes that produced no rule.
	Strict bool
	// Unknown collects class names that yielded no rule (populated when Strict).
	Unknown []string
	// contains filtered or unexported fields
}

TailwindGenerator converts class names to CSS rules.

func NewTailwindGenerator

func NewTailwindGenerator() *TailwindGenerator

NewTailwindGenerator creates a generator with default theme.

func (*TailwindGenerator) ExpandApply

func (g *TailwindGenerator) ExpandApply(cssText string) (string, []string)

ExpandApply is the package-level ExpandApply running through this generator, so animations applied this way are recorded for KeyframesCSS.

func (*TailwindGenerator) Generate

func (g *TailwindGenerator) Generate(classes map[string]bool) string

Generate produces CSS for the given set of class names. Output is deterministic: rules are sorted by a stable key so identical inputs always produce byte-identical stylesheets (stable content hashing).

func (*TailwindGenerator) KeyframesCSS

func (g *TailwindGenerator) KeyframesCSS() string

KeyframesCSS returns the at-rules that must accompany the last Generate output but live outside the utilities layer: an @keyframes block for every keyframes name referenced by an emitted animation, then an @property registration for every --tw-* composition variable the utilities use. Order is deterministic and each at-rule appears once. It is empty when nothing needs them.

func (*TailwindGenerator) MergeConfig

func (g *TailwindGenerator) MergeConfig(cfg *TailwindConfig)

MergeConfig merges a TailwindConfig into the generator's theme.

type TailwindImportMode

type TailwindImportMode int

TailwindImportMode selects the handling of Tailwind package imports.

const (
	TailwindResolve TailwindImportMode = iota
	TailwindKeep
	TailwindOff
)

type TailwindOptions added in v0.4.0

type TailwindOptions struct {
	// ScanDirs are directories (relative to root) to scan for classes.
	ScanDirs []string
	// ContentOverrides, when non-empty, replaces ScanDirs (Tailwind `content`).
	ContentOverrides []string
	// Preflight enables the base reset.
	Preflight bool
	// Strict collects unrecognized classes.
	Strict bool
	// DarkMode overrides the config's dark-mode strategy.
	DarkMode string
	// ExecuteConfig forces in-process config evaluation (esbuild + QuickJS)
	// instead of the static parser.
	ExecuteConfig bool
}

TailwindOptions carries site config that influences generation (scan roots, preflight, strict diagnostics).

type TailwindResult

type TailwindResult struct {
	// CSS is the layered stylesheet (empty when nothing was generated).
	CSS string
	// Unknown lists scanned candidates that produced no rule (strict only).
	Unknown []string
	// Warnings lists unsupported config or directive constructs.
	Warnings []string
}

TailwindResult is the output of a Tailwind generation run.

func GenerateTailwindDirectives

func GenerateTailwindDirectives(root string, cfg *TailwindConfig, opts TailwindOptions, d *TailwindDirectives) (TailwindResult, error)

GenerateTailwindDirectives scans the project, applies the config and the CSS-first directives (d may be nil), and returns the layered stylesheet: `@layer theme, base, components, utilities;` then theme variables, the preflight and the utilities each in their own layer, then @keyframes. User CSS that is unlayered therefore beats preflight and utilities alike.

type TailwindScanner

type TailwindScanner struct {
	Root string
	// Exclude lists absolute directories skipped during the scan (@source not).
	Exclude []string
	// VarRefs collects the custom properties referenced via var(--name) in the
	// scanned files, so referenced theme variables can be emitted.
	VarRefs map[string]bool
}

TailwindScanner extracts Tailwind utility class names from source files.

func NewTailwindScanner

func NewTailwindScanner(root string) *TailwindScanner

NewTailwindScanner creates a scanner for the given project root.

func (*TailwindScanner) ScanClasses

func (s *TailwindScanner) ScanClasses(dirs []string) map[string]bool

ScanClasses walks the project and extracts every Tailwind class candidate used in the scanned files. It is a broad candidate extractor (matching real Tailwind's approach): every string and template literal is scanned and its tokens filtered by shape, so classes inside `class={cond ? "a" : "b"}`, `clsx()/cn()/cva()` arguments, and arrays are all found.

type TailwindTheme

type TailwindTheme struct {
	Spacing     map[string]string            `json:"spacing"`
	Sizing      map[string]string            `json:"sizing"`
	MaxWidth    map[string]string            `json:"maxWidth"`
	MinWidth    map[string]string            `json:"minWidth"`
	LineHeight  map[string]string            `json:"lineHeight"`
	Opacity     map[string]string            `json:"opacity"`
	Screens     map[string]string            `json:"screens"`
	Colors      map[string]map[string]string `json:"colors"`
	TextSizes   map[string]string            `json:"textSizes"`
	FontWeights map[string]string            `json:"fontWeights"`
	FontFamily  map[string]string            `json:"fontFamily"`
	Radii       map[string]string            `json:"radii"`
	Shadows     map[string]string            `json:"shadows"`
	BgColors    map[string]string            `json:"bgColors"`
	// DarkMode is "media" (default), "class", or "selector".
	DarkMode string `json:"darkMode"`
	// DarkSelector is the selector of class/selector dark mode
	// (default ".dark"), e.g. "[data-mode=dark]".
	DarkSelector string `json:"darkSelector"`

	// Animation maps an animate-<name> utility to its animation value
	// (theme.animation, @theme --animate-*).
	Animation map[string]string `json:"animation"`
	// Keyframes maps a keyframes name to its block body without the
	// @keyframes wrapper, e.g. "to{transform:rotate(360deg)}".
	Keyframes map[string]string `json:"keyframes"`
	// Tracking maps tracking-<name> to a letter-spacing value.
	Tracking map[string]string `json:"tracking"`
	// Containers maps a container size name (@sm, max-w-sm in v4) to a width.
	Containers map[string]string `json:"containers"`
	// SpacingUnit is the v4 --spacing base unit (default 0.25rem) used for
	// numeric spacing multiples.
	SpacingUnit string `json:"spacingUnit"`
	// Prefix is the configured class prefix (v4 "tw" -> tw:flex), or "".
	Prefix string `json:"prefix"`
	// Important makes every utility !important when "true"; any other
	// non-empty value is a selector utilities are scoped under.
	Important string `json:"important"`
	// CustomUtilities maps a static `@utility name { ... }` to its declarations.
	CustomUtilities map[string]string `json:"customUtilities"`
	// CustomVariants maps `@custom-variant name (...)` to a selector template
	// containing "&" (e.g. "&:where([data-t=x] *)") or an at-rule such as
	// "@media (print)".
	CustomVariants map[string]string `json:"customVariants"`
}

TailwindTheme holds user-customizable theme values for the Tailwind generator.

func DefaultTailwindTheme

func DefaultTailwindTheme() TailwindTheme

DefaultTailwindTheme returns the default Tailwind theme configuration.

type ThemeVar

type ThemeVar struct {
	Name  string // without the leading "--"
	Value string
	// Reference vars are visible to utilities but never emitted (@theme reference).
	Reference bool
}

ThemeVar is one `--name: value` declaration from an @theme block.

Jump to

Keyboard shortcuts

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