theme

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package theme provides a comprehensive theming system with color tokens, dark mode support, and CSS generation following shadcn/ui design patterns.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DarkModeScript

func DarkModeScript() g.Node

DarkModeScript returns an inline script that prevents flash of unstyled content (FOUC) by reading the theme preference from localStorage before the page renders.

This script should be placed at the beginning of the <body> tag to execute immediately. It will:

  1. Check localStorage for a saved theme preference
  2. Fall back to system preference (prefers-color-scheme)
  3. Apply the 'dark' class to <html> element if needed

func DarkModeScriptWithDefault

func DarkModeScriptWithDefault(defaultTheme string) g.Node

DarkModeScriptWithDefault returns a dark mode script with a specified default theme. If no preference is stored and system preference is unavailable, use the default.

func DropdownToggle(opts ...ToggleOption) g.Node

DropdownToggle creates a dropdown-style theme selector. This provides a more compact interface with a popover menu.

Usage:

DropdownToggle()
DropdownToggle(WithStorageKey("my-theme"))
func FontLink(fonts ...Font) g.Node

FontLink returns a <link> tag for loading fonts. It automatically uses Google Fonts for standard fonts or custom URLs.

func FontStyleTag

func FontStyleTag(config FontConfig) g.Node

FontStyleTag returns a <style> tag with font configuration CSS.

func GenerateCSS

func GenerateCSS(lightTheme, darkTheme Theme) string

GenerateCSS generates CSS custom properties for the given theme. It creates both :root variables for light mode and .dark variables for dark mode. The generated CSS can be injected into a <style> tag.

func GenerateFontCSS

func GenerateFontCSS(config FontConfig) string

GenerateFontCSS generates CSS for font configuration. This includes CSS custom properties for font families.

func GenerateFontFaceCSS

func GenerateFontFaceCSS(font Font) string

GenerateFontFaceCSS generates @font-face CSS rules for custom fonts. This is useful for self-hosted fonts.

Example:

font := Font{
    Family: "CustomFont",
    URL:    "/fonts/custom-font.woff2",
    Weights: []int{400, 700},
    Display: "swap",
}
css := GenerateFontFaceCSS(font)

func GenerateGoogleFontsURL

func GenerateGoogleFontsURL(fonts []Font) string

GenerateGoogleFontsURL generates a Google Fonts URL for the given fonts.

Example:

fonts := []Font{
    {Family: "Inter", Weights: []int{400, 600, 700}},
    {Family: "JetBrains Mono", Weights: []int{400, 500}},
}
url := GenerateGoogleFontsURL(fonts)
// Returns: https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=JetBrains+Mono:wght@400;500&display=swap

func GenerateLightCSS

func GenerateLightCSS(theme Theme) string

GenerateLightCSS generates CSS custom properties for a light theme only. Useful when you don't need dark mode support.

func GenerateTailwindConfig

func GenerateTailwindConfig() string

GenerateTailwindConfig generates a Tailwind CSS configuration object that extends the default theme with custom properties using OKLCH color format. This is useful for integrating with Tailwind CSS configuration files.

func HTMLWrapper

func HTMLWrapper(lightTheme, darkTheme Theme, children ...g.Node) g.Node

HTMLWrapper wraps the entire HTML document with proper theme attributes. This is useful for server-rendered applications.

Usage:

HTMLWrapper(
    theme.DefaultLight(),
    theme.DefaultDark(),
    html.Head(...),
    html.Body(...),
)

func HeadContent

func HeadContent(lightTheme, darkTheme Theme) g.Node

HeadContent returns common <head> content for theme support. Include this in your page's <head> section.

It includes:

  • Theme color meta tag (adapts to theme)
  • Color scheme meta tag
  • Viewport meta tag

func PersistentToggle

func PersistentToggle(storageKey string) g.Node

PersistentToggle creates a theme toggle with full persistence support. This is a convenience function that enables all persistence features.

func Provider

func Provider(children ...g.Node) g.Node

Provider wraps the application with theme support. It injects CSS custom properties and dark mode script into the page.

Usage:

Provider(children...)                           // Uses default light/dark themes
Provider(children..., WithDefaultTheme("dark")) // Starts with dark theme

func ProviderWithOptions

func ProviderWithOptions(children []g.Node, opts ...ProviderOption) g.Node

ProviderWithOptions provides fine-grained control over theme configuration.

Usage:

ProviderWithOptions(
    children,
    WithDefaultTheme("dark"),
    WithStorageKey("app-theme"),
)

func ProviderWithThemes

func ProviderWithThemes(lightTheme, darkTheme Theme, children ...g.Node) g.Node

ProviderWithThemes wraps the application with custom light and dark themes.

Usage:

ProviderWithThemes(theme.BlueLight(), theme.BlueDark(), children...)

func SimpleToggle

func SimpleToggle() g.Node

SimpleToggle creates a minimal icon-only theme toggle with persistence. This is a convenience function for the most common use case.

func StyleTag

func StyleTag(lightTheme, darkTheme Theme) g.Node

StyleTag returns just the theme CSS as a style tag. Useful if you want to manually place the theme CSS.

func TailwindConfigScript

func TailwindConfigScript() g.Node

TailwindConfigScript returns an inline script that configures Tailwind CSS to use OKLCH color format with CSS variables. This is needed when using the Tailwind Play CDN, as it doesn't natively understand that CSS variables contain OKLCH values that need to be wrapped with the oklch() function.

Usage:

html.Head(
    html.Script(html.Src("https://cdn.tailwindcss.com")),
    theme.TailwindConfigScript(), // Add after Tailwind CDN
    theme.StyleTag(lightTheme, darkTheme),
)

func ThemeScript

func ThemeScript() g.Node

ThemeScript returns a complete theme management script with Alpine.js integration. This provides functions to get, set, and sync theme across tabs.

The script exposes:

  • getTheme(): Returns current theme ('light' or 'dark')
  • setTheme(theme): Sets theme and persists to localStorage
  • toggleTheme(): Toggles between light and dark

func ThemeStyleCloak

func ThemeStyleCloak() g.Node

ThemeStyleCloak returns CSS to hide elements with x-cloak attribute. This prevents flashing of theme-dependent elements during initialization.

func ThemeTransitionCSS

func ThemeTransitionCSS() g.Node

ThemeTransitionCSS returns CSS for smooth theme transitions. Add this to your page to enable animated theme changes.

func Toggle

func Toggle(opts ...ToggleOption) g.Node

Toggle creates a theme switcher button that toggles between light and dark modes. It uses Alpine.js for interactivity and persists the preference to browser storage.

Features:

  • Persists theme preference to localStorage (default) or sessionStorage
  • Syncs theme changes across browser tabs
  • Respects system color scheme preference
  • Prevents flash of wrong theme on page load

Usage:

Toggle()                                    // Icon-only toggle with localStorage
Toggle(WithLabel(true))                     // With label
Toggle(WithStorageKey("my-app-theme"))      // Custom storage key
Toggle(WithStorageType(SessionStorage))     // Use sessionStorage
Toggle(WithTabSync(false))                  // Disable cross-tab sync

func ToggleWithSystemOption

func ToggleWithSystemOption(opts ...ToggleOption) g.Node

ToggleWithSystemOption creates a theme toggle with three options: light, dark, and system. This provides more granular control over theme preferences with full persistence support.

Features:

  • Three-way toggle: Light, Dark, System
  • System option respects OS color scheme preference
  • Persists preference to browser storage
  • Syncs across browser tabs

Usage:

ToggleWithSystemOption()                        // Default three-way toggle
ToggleWithSystemOption(WithStorageKey("pref")) // Custom storage key
ToggleWithSystemOption(IconOnly())              // Icons only, no labels

Types

type ColorTokens

type ColorTokens struct {
	Background            string // Background color for the app
	Foreground            string // Foreground color for text
	Card                  string // Card background
	CardForeground        string // Card text color
	Popover               string // Popover background
	PopoverForeground     string // Popover text color
	Primary               string // Primary brand color
	PrimaryForeground     string // Text on primary color
	Secondary             string // Secondary color
	SecondaryForeground   string // Text on secondary color
	Muted                 string // Muted background
	MutedForeground       string // Muted text color
	Accent                string // Accent background
	AccentForeground      string // Text on accent color
	Destructive           string // Destructive/danger color
	DestructiveForeground string // Text on destructive color
	Success               string // Success/positive color
	Border                string // Border color
	Input                 string // Input border color
	Ring                  string // Focus ring color

	// Chart colors for data visualization
	Chart1  string // Chart color 1
	Chart2  string // Chart color 2
	Chart3  string // Chart color 3
	Chart4  string // Chart color 4
	Chart5  string // Chart color 5
	Chart6  string // Chart color 6
	Chart7  string // Chart color 7
	Chart8  string // Chart color 8
	Chart9  string // Chart color 9
	Chart10 string // Chart color 10
	Chart11 string // Chart color 11
	Chart12 string // Chart color 12

	// Sidebar-specific colors for independent theming
	Sidebar                  string // Sidebar background
	SidebarForeground        string // Sidebar text color
	SidebarPrimary           string // Sidebar primary color
	SidebarPrimaryForeground string // Text on sidebar primary
	SidebarAccent            string // Sidebar accent background
	SidebarAccentForeground  string // Text on sidebar accent
	SidebarBorder            string // Sidebar border color
	SidebarRing              string // Sidebar focus ring color
}

ColorTokens defines all color variables following shadcn/ui naming conventions. Colors are stored in OKLCH format without the "oklch()" wrapper for compatibility with Tailwind CSS custom properties. OKLCH provides better perceptual uniformity and more predictable color interpolation compared to HSL.

type Font

type Font struct {
	Family   string   // Font family name (e.g., "Inter", "Roboto")
	Weights  []int    // Font weights to load (e.g., 400, 500, 600, 700)
	Styles   []string // Font styles (e.g., "normal", "italic")
	URL      string   // Custom font URL (if not using Google Fonts)
	Display  string   // font-display strategy (swap, block, fallback, optional)
	Fallback []string // Fallback font stack
}

Font defines a font family with its properties.

type FontConfig

type FontConfig struct {
	Sans         Font   // Sans-serif font
	Serif        Font   // Serif font
	Mono         Font   // Monospace font
	Body         string // Body font family
	Heading      string // Heading font family
	Code         string // Code font family
	BaseFontSize string // Base font size (e.g., "16px")
}

FontConfig defines typography configuration for the theme.

func DefaultFontConfig

func DefaultFontConfig() FontConfig

DefaultFontConfig returns a default font configuration using system fonts.

func InterFontConfig

func InterFontConfig() FontConfig

InterFontConfig returns a font configuration using Inter from Google Fonts. Inter is a popular choice for modern web applications.

type FontSizeTokens

type FontSizeTokens struct {
	XS   string // Extra small text
	SM   string // Small text
	Base string // Base font size
	LG   string // Large text
	XL   string // Extra large text
	XXL  string // 2X large text
	XXXL string // 3X large text
}

FontSizeTokens defines the typography scale.

type ProviderOption

type ProviderOption func(*ProviderProps)

ProviderOption is a functional option for configuring the Provider.

func DisableSystemSync

func DisableSystemSync() ProviderOption

DisableSystemSync disables automatic syncing with system theme preference.

func WithDefaultTheme

func WithDefaultTheme(theme string) ProviderOption

WithDefaultTheme sets the default theme when no preference is stored.

func WithStorageKey

func WithStorageKey(key string) ProviderOption

WithStorageKey sets a custom localStorage key for theme persistence.

type ProviderProps

type ProviderProps struct {
	LightTheme       Theme  // Light theme (required)
	DarkTheme        Theme  // Dark theme (required)
	DefaultTheme     string // Default theme if no preference ("light" or "dark")
	EnableSystemSync bool   // Sync with system preference
	StorageKey       string // localStorage key for theme preference
}

ProviderProps defines configuration for the theme provider.

type RadiusTokens

type RadiusTokens struct {
	SM   string // Small radius (e.g., "0.25rem")
	MD   string // Medium radius (e.g., "0.375rem")
	LG   string // Large radius (e.g., "0.5rem")
	XL   string // Extra large radius (e.g., "0.75rem")
	Full string // Full radius for circles (e.g., "9999px")
}

RadiusTokens defines border radius values for consistent rounded corners.

type ShadowTokens

type ShadowTokens struct {
	SM string // Small shadow
	MD string // Medium shadow
	LG string // Large shadow
	XL string // Extra large shadow
}

ShadowTokens defines elevation shadows for depth perception.

type SpacingTokens

type SpacingTokens struct {
	XS  string // Extra small spacing
	SM  string // Small spacing
	MD  string // Medium spacing
	LG  string // Large spacing
	XL  string // Extra large spacing
	XXL string // 2X large spacing
}

SpacingTokens defines consistent spacing values throughout the UI.

type StorageType

type StorageType string

StorageType defines the storage mechanism for theme persistence.

const (
	// LocalStorage persists theme preference across sessions.
	LocalStorage StorageType = "localStorage"
	// SessionStorage persists theme only for the current session.
	SessionStorage StorageType = "sessionStorage"
	// NoStorage disables persistence (in-memory only).
	NoStorage StorageType = "none"
)

type Theme

type Theme struct {
	Colors   ColorTokens
	Radius   RadiusTokens
	Spacing  SpacingTokens
	FontSize FontSizeTokens
	Shadow   ShadowTokens
}

Theme holds all design tokens for the UI system. It provides a complete set of color, spacing, typography, and shadow tokens that can be converted to CSS custom properties.

func BlueDark

func BlueDark() Theme

BlueDark returns a blue-toned dark theme in OKLCH format. Suitable for professional, corporate, or tech-focused applications.

func BlueLight

func BlueLight() Theme

BlueLight returns a blue-toned light theme in OKLCH format. Suitable for professional, corporate, or tech-focused applications.

func DefaultDark

func DefaultDark() Theme

DefaultDark returns the default dark theme following shadcn/ui design patterns. This uses neutral colors in OKLCH format suitable for dark mode.

func DefaultLight

func DefaultLight() Theme

DefaultLight returns the default light theme following shadcn/ui design patterns. This uses neutral colors in OKLCH format suitable for most applications.

func GreenDark

func GreenDark() Theme

GreenDark returns a green-toned dark theme in OKLCH format. Suitable for eco-friendly, health, or nature-focused applications.

func GreenLight

func GreenLight() Theme

GreenLight returns a green-toned light theme in OKLCH format. Suitable for eco-friendly, health, or nature-focused applications.

func NeutralDark

func NeutralDark() Theme

NeutralDark returns a neutral-toned dark theme. Alias for DefaultDark for semantic clarity.

func NeutralLight

func NeutralLight() Theme

NeutralLight returns a neutral-toned light theme. Alias for DefaultLight for semantic clarity.

func New

func New() Theme

New creates a new Theme with default values if not provided. This is useful for creating custom themes that inherit defaults.

func OrangeDark

func OrangeDark() Theme

OrangeDark returns an orange-toned dark theme in OKLCH format. Suitable for energetic, creative, or fun applications.

func OrangeLight

func OrangeLight() Theme

OrangeLight returns an orange-toned light theme in OKLCH format. Suitable for energetic, creative, or fun applications.

func RoseDark

func RoseDark() Theme

RoseDark returns a rose/pink-toned dark theme in OKLCH format. Suitable for applications targeting feminine or creative aesthetics.

func RoseLight

func RoseLight() Theme

RoseLight returns a rose/pink-toned light theme in OKLCH format. Suitable for applications targeting feminine or creative aesthetics.

type ToggleOption

type ToggleOption func(*ToggleProps)

ToggleOption is a functional option for configuring the Toggle.

func IconOnly

func IconOnly() ToggleOption

IconOnly makes the toggle button icon-only.

func WithAllLabels

func WithAllLabels(light, dark, system string) ToggleOption

WithAllLabels sets custom labels for light, dark, and system modes.

func WithLabel

func WithLabel(show bool) ToggleOption

WithLabel enables the text label.

func WithLabels

func WithLabels(light, dark string) ToggleOption

WithLabels sets custom labels for light and dark modes.

func WithStorageType

func WithStorageType(storageType StorageType) ToggleOption

WithStorageType sets the storage mechanism for persistence.

func WithSystemPreference

func WithSystemPreference(enabled bool) ToggleOption

WithSystemPreference enables respecting system color scheme preference.

func WithTabSync

func WithTabSync(enabled bool) ToggleOption

WithTabSync enables synchronization of theme changes across browser tabs.

func WithToggleClass

func WithToggleClass(class string) ToggleOption

WithToggleClass adds custom CSS classes.

func WithToggleDefaultTheme

func WithToggleDefaultTheme(theme string) ToggleOption

WithToggleDefaultTheme sets the default theme when no preference is stored.

func WithToggleSize

func WithToggleSize(size string) ToggleOption

WithToggleSize sets the button size.

func WithToggleStorageKey

func WithToggleStorageKey(key string) ToggleOption

WithToggleStorageKey sets a custom storage key for theme persistence.

func WithTransition

func WithTransition(enabled bool) ToggleOption

WithTransition enables smooth theme transition animation.

type ToggleProps

type ToggleProps struct {
	ShowLabel         bool        // Show text label alongside icon
	LightLabel        string      // Label for light mode
	DarkLabel         string      // Label for dark mode
	SystemLabel       string      // Label for system mode
	Position          string      // Button position (if floating)
	Size              string      // Button size (sm, md, lg)
	CustomClass       string      // Additional CSS classes
	IconOnly          bool        // Show only icon, no label
	StorageKey        string      // Key used for storage (default: "theme")
	StorageType       StorageType // Storage mechanism (localStorage, sessionStorage, none)
	SyncAcrossTabs    bool        // Sync theme changes across browser tabs
	RespectSystem     bool        // Respect system preference when no stored value
	DefaultTheme      string      // Default theme when no preference (light, dark, system)
	AnimateTransition bool        // Enable smooth transition animation
}

ToggleProps defines configuration for the theme toggle button.

Jump to

Keyboard shortcuts

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