css

package
v0.5.0-alpha.3 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ChunkCSS added in v0.4.0

func ChunkCSS(pages []string) (shared string, perPage []string)

ChunkCSS splits page stylesheets into a shared chunk (rules used on more than one page) and a per-page remainder. The shared chunk is sorted by canonical key for deterministic hashing; per-page remnants preserve original order so page-specific overrides still follow the shared rules.

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 in user CSS into the declarations those utilities produce, using the given theme. This is a v1 implementation: 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 left unexpanded 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 InlineImports

func InlineImports(css, basePath string) string

InlineImports resolves and inlines @import directives in CSS content. basePath is the directory containing the CSS file, used to resolve relative paths. All resolved imports must remain inside basePath (the project root) - traversal above it is treated as invalid and left un-inlined. It handles circular imports via a visited set and has a max depth of 10.

func MergeAtTheme added in v0.4.0

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

MergeAtTheme applies v4 `@theme` variables to a theme, generating the corresponding utilities: --color-*, --spacing-*, --radius-*, --shadow-*, --opacity-*, --leading-*, --breakpoint-*, --font-*.

func Minify

func Minify(cssText string) string

func ProcessModule

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

ProcessModule scopes a CSS Module. Local class selectors are rewritten to `<name>_<hash>` and recorded in `mapping`; `:global(...)` is emitted unscoped; `composes:` local names are mapped. Strings, comments, `url(...)` and attribute selectors are left untouched (a whole-content regex pass corrupted them). Keyframe/animation names are not scoped (they do not collide in practice because the whole module shares one hash namespace via classes).

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 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. 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 TailwindPreflight added in v0.4.0

func TailwindPreflight(theme TailwindTheme) string

TailwindPreflight returns Tailwind's Preflight base reset (opt-in via `tailwind.preflight`). It normalizes box-sizing, borders, margins, headings, lists, media, and form controls, and sets the default transform/space custom properties so composed utilities behave correctly.

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 TailwindConfig

type TailwindConfig struct {
	Theme    TailwindTheme `json:"theme"`
	DarkMode string        `json:"darkMode"`
}

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 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
}

TailwindGenerator converts class names to CSS rules.

func NewTailwindGenerator

func NewTailwindGenerator() *TailwindGenerator

NewTailwindGenerator creates a generator with default theme.

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) MergeConfig

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

MergeConfig merges a TailwindConfig into the generator's theme.

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 TailwindScanner

type TailwindScanner struct {
	Root string
}

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"`
}

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

func DefaultTailwindTheme

func DefaultTailwindTheme() TailwindTheme

DefaultTailwindTheme returns the default Tailwind theme configuration.

Jump to

Keyboard shortcuts

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