csspurge

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package csspurge provides CSS analysis and unused rule removal functionality.

Overview

The csspurge package scans HTML files to identify used CSS selectors and then removes unused CSS rules from stylesheets. This helps reduce CSS file sizes by eliminating rules that don't match any elements in the generated HTML.

Usage

The package is typically used through the css_purge plugin, but can be used directly for custom CSS optimization workflows:

// Scan HTML files to find used selectors
used := csspurge.NewUsedSelectors()
for _, htmlPath := range htmlFiles {
    if err := csspurge.ScanHTML(htmlPath, used); err != nil {
        log.Printf("warning: %v", err)
    }
}

// Purge unused rules from CSS
opts := csspurge.PurgeOptions{
    Preserve: []string{"js-*", "htmx-*"},
}
purged, stats := csspurge.PurgeCSS(cssContent, used, opts)

Preserved Patterns

Some CSS classes are dynamically added by JavaScript and won't appear in the static HTML. The package supports glob patterns to preserve these rules:

  • js-* - JavaScript-added classes
  • htmx-* - HTMX framework classes
  • pagefind-* - Pagefind search UI classes
  • glightbox* - GLightbox image viewer classes
  • active, hidden, loading - Common state classes
  • dark, light - Theme mode classes

CSS Parsing

The package uses a regex-based CSS parser that handles:

  • Standard rule blocks: selector { properties }
  • Media queries: @media (...) { rules }
  • Keyframes: @keyframes name { ... }
  • Font-faces: @font-face { ... }
  • Imports: @import ...

At-rules like @media queries are preserved if any of their nested rules are used. @keyframes and @font-face are always preserved.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultPreserveAttributes

func DefaultPreserveAttributes() []string

DefaultPreserveAttributes returns the default attribute name patterns to preserve. These are commonly used for runtime theming and should not be purged.

func DefaultPreservePatterns

func DefaultPreservePatterns() []string

DefaultPreservePatterns returns the default patterns for selectors to preserve. These are commonly used by JavaScript frameworks and should not be purged.

func ExtractAttributesFromSelector

func ExtractAttributesFromSelector(selector string) []string

ExtractAttributesFromSelector extracts attribute names from a selector. Attribute names are normalized to lowercase for case-insensitive matching.

func ExtractClassesFromSelector

func ExtractClassesFromSelector(selector string) []string

ExtractClassesFromSelector extracts class names from a selector.

func ExtractElementsFromSelector

func ExtractElementsFromSelector(selector string) []string

ExtractElementsFromSelector extracts unique element names from a selector. Element names are normalized to lowercase and deduplicated.

func ExtractIDsFromSelector

func ExtractIDsFromSelector(selector string) []string

ExtractIDsFromSelector extracts IDs from a selector.

func ExtractSelectorsFromRule

func ExtractSelectorsFromRule(selector string) []string

ExtractSelectorsFromRule extracts individual selectors from a selector list.

func ScanHTML

func ScanHTML(htmlPath string, used *UsedSelectors) error

ScanHTML parses an HTML file and extracts used selectors. Results are merged into the provided UsedSelectors struct.

func ScanHTMLContent

func ScanHTMLContent(html string, used *UsedSelectors) error

ScanHTMLContent parses HTML content from a string and extracts used selectors. This is useful for processing HTML that's already in memory.

Types

type CSSRule

type CSSRule struct {
	// Selector is the CSS selector (e.g., ".class", "#id", "div")
	Selector string
	// Content is the full rule including braces (e.g., ".class { color: red; }")
	Content string
	// IsAtRule indicates if this is an @-rule (@media, @keyframes, etc.)
	IsAtRule bool
	// AtRuleType is the type of @-rule (e.g., "media", "keyframes", "font-face")
	AtRuleType string
	// NestedRules contains rules nested inside @-rules like @media
	NestedRules []CSSRule
}

CSSRule represents a CSS rule with its selector and content.

func ParseCSS

func ParseCSS(content string) []CSSRule

ParseCSS parses CSS content into a slice of CSSRule structs. It handles nested @-rules like @media queries.

type PurgeOptions

type PurgeOptions struct {
	// Preserve is a list of glob patterns for selectors to keep.
	// Example: ["js-*", "htmx-*", "active", "hidden"]
	Preserve []string

	// PreserveAttributes is a list of attribute names to always preserve.
	// Selectors with these attributes (e.g., [data-theme]) will not be purged.
	// Example: ["data-theme", "data-palette"]
	PreserveAttributes []string

	// Verbose enables detailed logging.
	Verbose bool
}

PurgeOptions configures CSS purging behavior.

type PurgeStats

type PurgeStats struct {
	// TotalRules is the number of rules before purging.
	TotalRules int
	// KeptRules is the number of rules kept after purging.
	KeptRules int
	// RemovedRules is the number of rules removed.
	RemovedRules int
	// OriginalSize is the original CSS size in bytes.
	OriginalSize int
	// PurgedSize is the purged CSS size in bytes.
	PurgedSize int
}

PurgeStats tracks statistics about CSS purging.

func PurgeCSS

func PurgeCSS(css string, used *UsedSelectors, opts PurgeOptions) (string, PurgeStats)

PurgeCSS removes unused CSS rules based on used selectors. It returns the purged CSS content and statistics.

func (*PurgeStats) SavingsPercent

func (s *PurgeStats) SavingsPercent() float64

SavingsPercent returns the percentage of size reduction.

type UsedSelectors

type UsedSelectors struct {
	// Classes maps class names to true (for O(1) lookup)
	Classes map[string]bool
	// IDs maps ID names to true
	IDs map[string]bool
	// Elements maps element/tag names to true
	Elements map[string]bool
	// Attributes maps attribute names to true (for [attr] selectors)
	Attributes map[string]bool
}

UsedSelectors tracks CSS selectors found in HTML content.

func NewUsedSelectors

func NewUsedSelectors() *UsedSelectors

NewUsedSelectors creates an empty UsedSelectors struct.

func (*UsedSelectors) Merge

func (u *UsedSelectors) Merge(other *UsedSelectors)

Merge combines another UsedSelectors into this one.

Jump to

Keyboard shortcuts

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