forgeui

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 12 Imported by: 0

README

ForgeUI

ForgeUI is a comprehensive SSR-first UI framework for Go, built on templ with templui components, Tailwind CSS styling, and shadcn-inspired design patterns. It provides everything you need to build modern, interactive web applications entirely in Go.

Features

Core Framework
  • SSR-First: Pure Go component rendering with zero client-side dependencies required
  • Type-Safe: Full Go type safety with templ templates
  • templui Components: shadcn-inspired component library via templui
  • Tailwind CSS: Utility-first CSS styling with built-in processing
  • 35+ Components: Production-ready UI components
Frontend Integration
  • Alpine.js Integration: Directives, stores, magic helpers, and plugins
  • Client-Side Routing: Pinecone Router integration for SPA navigation
  • HTMX Support: Complete HTMX attribute helpers and server-side utilities
  • Icons: 1600+ Lucide icons with customization options
  • Animation System: Tailwind animations, transitions, and keyframes
Backend Features
  • Router: Production-ready HTTP routing with middleware support
  • Bridge: Go-JavaScript RPC bridge for calling Go functions from client-side
  • Plugin System: Extensible plugin architecture with dependency management
  • Theme System: Customizable themes with CSS variables and color tokens
Developer Tools
  • Assets Pipeline: Built-in esbuild, Tailwind CSS, and file fingerprinting
  • Dev Server: Hot-reload development server with file watching
  • CLI: Command-line tools for project scaffolding and management
  • Layout Helpers: Page builder with meta tags, scripts, and structured layouts

Why ForgeUI?

  • 🚀 Go All The Way: Write your entire frontend in Go with templ templates
  • 🎯 Type Safety: Catch errors at compile time, not runtime
  • SSR Performance: Server-rendered HTML with optional progressive enhancement
  • 🎨 Beautiful by Default: shadcn-inspired design that looks great out of the box
  • 🔧 Full Stack: Router, RPC, assets, themes - everything you need
  • 📦 Zero Config: Works out of the box with sensible defaults
  • 🔌 Extensible: Plugin system for adding custom functionality
  • 🎭 Progressive: Start with pure SSR, add Alpine.js/HTMX as needed

Installation

go get github.com/xraph/forgeui

Quick Start

1. Create Your First Application

main.go:

package main

import (
    "log"
    "net/http"

    "github.com/a-h/templ"
    "github.com/xraph/forgeui"
    "github.com/xraph/forgeui/router"
)

func main() {
    // Create ForgeUI app
    app := forgeui.New(
        forgeui.WithDebug(true),
        forgeui.WithThemeName("default"),
    )

    // Register routes
    app.Get("/", HomePage)

    // Start server
    log.Println("Server running on http://localhost:8080")
    http.ListenAndServe(":8080", app.Handler())
}

func HomePage(ctx *router.PageContext) (templ.Component, error) {
    return HomePageView(), nil
}

home.templ:

package main

templ HomePageView() {
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8"/>
            <title>ForgeUI App</title>
        </head>
        <body>
            <div class="container mx-auto p-8">
                <h1 class="text-4xl font-bold">Welcome to ForgeUI</h1>
                <p>Build beautiful UIs with Go and templ.</p>
                <a href="/about" class="btn btn-primary">Get Started</a>
            </div>
        </body>
    </html>
}
2. Run Your Application
go run main.go

Visit http://localhost:8080 to see your app!

3. Add Interactivity (Optional)

Add Alpine.js for client-side interactivity in your .templ files:

package main

import "github.com/xraph/forgeui/alpine"

templ InteractivePage() {
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>Interactive App</title>
            @alpine.Scripts()
        </head>
        <body>
            <div x-data="{ count: 0 }">
                <button @click="count++">Increment</button>
                <span x-text="count"></span>
            </div>
        </body>
    </html>
}

Components

Layout Primitives
  • Box - Polymorphic container with responsive props
  • Flex - Flexbox layout with direction and alignment
  • Grid - CSS Grid layout with responsive columns
  • Stack - VStack/HStack for vertical/horizontal layouts
  • Center - Centered container with responsive centering
  • Container - Responsive container with max-width
  • Text - Typography primitive with semantic HTML
  • Spacer - Flexible spacer for layouts
Buttons & Actions
  • Button - All variants (Primary, Secondary, Destructive, Outline, Ghost, Link)
  • Button Group - Grouped buttons with gap control
  • Icon Button - Compact icon-only buttons
Content Display
  • Card - Compound component (Header, Title, Description, Content, Footer)
  • Badge - Status indicators and labels
  • Avatar - User avatars with image and fallback
  • Alert - Alert messages with variants (Info, Success, Warning, Error)
  • Separator - Horizontal/vertical dividers
  • Empty State - Empty state placeholders
  • List - List containers with list items
Navigation
  • Navbar - Navigation bar component
  • Breadcrumb - Breadcrumb navigation
  • Tabs - Tabbed navigation and content
  • Menu - Menu and menu items
  • Sidebar - Collapsible sidebar navigation
  • Pagination - Page navigation controls
Forms
  • Form - Form wrapper with validation helpers
  • Label - Accessible form labels
  • Input - Text inputs with variants and validation states
  • Input Group - Input with icons and addons
  • Textarea - Multi-line text input
  • Checkbox - Checkbox inputs with labels
  • Radio - Radio buttons with radio groups
  • Switch - Toggle switches
  • Select - Native select dropdowns
  • Slider - Range sliders
Overlays
  • Modal - Modal dialogs
  • Dialog - Dialog component
  • Alert Dialog - Confirmation dialogs
  • Drawer - Slide-out panels
  • Sheet - Bottom/side sheets
  • Dropdown - Dropdown menus
  • Context Menu - Right-click context menus
  • Popover - Floating popovers
  • Tooltip - Hover tooltips
  • Toast - Toast notifications with toaster
Feedback
  • Spinner - Loading spinners
  • Skeleton - Loading placeholders
  • Progress - Progress bars
Data Display
  • Table - Data tables with header, body, rows, and cells
  • DataTable - Advanced tables with sorting, filtering, and pagination

Usage Examples

Button (templui)
import "github.com/xraph/forgeui/components/button"

// Primary button
@button.Button(button.Props{Variant: button.VariantDefault}) {
    Save
}

// Destructive button
@button.Button(button.Props{Variant: button.VariantDestructive, Size: button.SizeLg}) {
    Delete
}
Card (templui)
import "github.com/xraph/forgeui/components/card"

@card.Card(card.Props{}) {
    @card.Header() {
        @card.Title() { Settings }
        @card.Description() { Manage your account settings }
    }
    @card.Content() {
        // Your content here
    }
    @card.Footer() {
        @button.Button(button.Props{}) { Save Changes }
    }
}
Layout with Primitives
import "github.com/xraph/forgeui/primitives"

@primitives.Container(primitives.ContainerProps{}) {
    @primitives.Stack(primitives.StackProps{Direction: "vertical", Gap: "8"}) {
        @primitives.Text(primitives.TextProps{As: "h1", Size: "text-4xl", Weight: "font-bold"}) {
            Dashboard
        }
        @primitives.Grid(primitives.GridProps{Cols: 1, ColsMD: 2, ColsLG: 3, Gap: "6"}) {
            // Grid items here
        }
    }
}

Router

Production-ready HTTP routing with pattern matching and middleware:

app := forgeui.New()

// Static routes
app.Get("/", HomePage)
app.Get("/about", AboutPage)

// Path parameters
app.Get("/users/:id", UserProfile)
app.Get("/users/:userId/posts/:postId", PostDetail)

// Wildcards
app.Get("/files/*filepath", ServeFile)

// Middleware
app.Use(router.Logger())
app.Use(router.Recovery())
app.Use(router.CORS("*"))

// Route-specific middleware
route := app.Get("/admin", AdminDashboard)
route.WithMiddleware(AuthMiddleware)

// Named routes for URL generation
app.Router().Name("user.post", route)
url := app.Router().URL("user.post", userID, postID)
PageContext

Access request data with rich context utilities:

func UserProfile(ctx *router.PageContext) (templ.Component, error) {
    // Path parameters
    id := ctx.Param("id")
    userID, _ := ctx.ParamInt("id")

    // Query parameters
    query := ctx.Query("q")
    page, _ := ctx.QueryInt("page")

    // Headers and cookies
    auth := ctx.Header("Authorization")
    cookie, _ := ctx.Cookie("session")

    // Context values (set by middleware)
    uid := ctx.GetInt("user_id")

    return UserProfileView(id), nil
}

See router/README.md for complete documentation.

Bridge - Go to JavaScript RPC

Call Go functions directly from JavaScript using JSON-RPC 2.0:

Server Side
b := bridge.New()

// Register Go functions
b.Register("createUser", func(ctx bridge.Context, input struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}) (struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}, error) {
    user := createUserInDB(input.Name, input.Email)
    return struct {
        ID   int    `json:"id"`
        Name string `json:"name"`
    }{ID: user.ID, Name: user.Name}, nil
})

// Function options
b.Register("adminAction", handler,
    bridge.RequireAuth(),
    bridge.RequireRoles("admin"),
    bridge.WithRateLimit(10),
    bridge.WithTimeout(10*time.Second),
)

// Enable bridge on router
bridge.EnableBridge(app.Router(), b)
Client Side
// Include bridge scripts in your layout
@bridge.BridgeScripts(bridge.ScriptConfig{
    Endpoint: "/api/bridge",
    CSRFToken: csrfToken,
    IncludeAlpine: true,
})

// Alpine.js integration
<button @click="result = await $bridge.call('createUser', {name, email})">
    Create User
</button>

Features:

  • HTTP (JSON-RPC 2.0), WebSocket, and SSE transports
  • Built-in authentication, authorization, and rate limiting
  • Automatic parameter validation
  • CSRF protection
  • Caching support
  • Alpine.js magic helpers

See bridge/README.md for complete documentation.

HTMX Integration

Complete HTMX support with type-safe attribute helpers:

// In your layout templ file
@htmx.Scripts()

// HTMX attributes on elements
<button { htmx.HxGet("/api/users")... } { htmx.HxTarget("#user-list")... } { htmx.HxSwap("innerHTML")... }>
    Load Users
</button>

// Advanced triggers
<input { htmx.HxTriggerDebounce("keyup", "500ms")... } { htmx.HxGet("/search")... }/>

Server-side detection and response headers work the same:

func handler(w http.ResponseWriter, r *http.Request) {
    if htmx.IsHTMX(r) {
        renderPartial(w)
    } else {
        renderFullPage(w)
    }
}

htmx.TriggerEvent(w, "refresh")
htmx.SetHTMXRedirect(w, "/login")

See htmx/README.md for complete documentation.

Alpine.js Integration

Seamless Alpine.js integration with directives, stores, and plugins:

// Include Alpine.js in your layout
@alpine.Scripts()

// Alpine directives on elements
<div x-data="{ count: 0 }">
    <button @click="count++">Increment</button>
    <span x-text="count"></span>
</div>

// Or use the helper functions for programmatic attributes
<div { alpine.XShow("isVisible")... } { alpine.XTransitionSimple()... }>
    Content
</div>

Alpine stores and custom directives in Go:

alpine.Store("app", map[string]any{
    "user": nil,
    "isLoggedIn": false,
})

alpine.Directive("click-outside", `(el, {expression}, {evaluate}) => {
    // directive implementation
}`)

Icons

1600+ Lucide icons with full customization:

// Basic usage in templ files
@icons.Check()
@icons.Search()
@icons.User()

// Customization
@icons.Check(icons.WithSize(24), icons.WithColor("green"), icons.WithClass("text-green-500"))

// In buttons
@button.Button(button.Props{}) {
    @icons.Plus(icons.WithSize(16))
    Add Item
}

// Loading spinner
@icons.Loader(icons.WithSize(20), icons.WithClass("animate-spin"))

See icons/README.md for complete documentation.

Plugin System

Extensible plugin architecture with dependency management:

// Create a plugin
type MyPlugin struct {
    *plugin.PluginBase
}

func New() *MyPlugin {
    return &MyPlugin{
        PluginBase: plugin.NewPluginBase(plugin.PluginInfo{
            Name:    "my-plugin",
            Version: "1.0.0",
            Dependencies: []plugin.Dependency{
                {Name: "other-plugin", Version: ">=1.0.0"},
            },
        }),
    }
}

func (p *MyPlugin) Init(ctx context.Context, r *plugin.Registry) error {
    // Initialize plugin
    return nil
}

// Use plugins
registry := plugin.NewRegistry()
registry.Use(
    myplugin.New(),
    otherplugin.New(),
)
registry.Initialize(ctx)
defer registry.Shutdown(ctx)

Plugin Types:

  • Component plugins (extend UI components)
  • Alpine plugins (scripts, directives, stores)
  • Theme plugins (custom themes and fonts)
  • Middleware plugins (HTTP middleware)

See plugin/README.md for complete documentation.

Assets Pipeline

Built-in asset management with Tailwind CSS, esbuild, and fingerprinting:

app := forgeui.New()

// Configure assets
app.WithAssets(assets.Config{
    Enabled:      true,
    OutputDir:    "./dist",
    Minify:       true,
    Fingerprint:  true,
    Tailwind: assets.TailwindConfig{
        Input:     "./styles/input.css",
        Output:    "./dist/styles.css",
        ConfigFile: "./tailwind.config.js",
    },
    ESBuild: assets.ESBuildConfig{
        EntryPoints: []string{"./js/app.js"},
        Outdir:     "./dist/js",
    },
})

// Development server with hot-reload
if err := app.StartDevServer(":3000"); err != nil {
    log.Fatal(err)
}

Features:

  • Tailwind CSS compilation
  • JavaScript bundling with esbuild
  • File fingerprinting for cache busting
  • Hot-reload development server
  • Asset manifest generation

See assets/README.md for complete documentation.

Theme System

Customizable themes with CSS variables:

// Use built-in theme
app := forgeui.New(
    forgeui.WithThemeName("default"),
)

// Create custom theme
customTheme := theme.Theme{
    Colors: theme.ColorTokens{
        Primary:   "#3b82f6",
        Secondary: "#64748b",
        Background: "#ffffff",
        Foreground: "#0f172a",
    },
    Radius: theme.RadiusTokens{
        Default: "0.5rem",
        Button:  "0.375rem",
        Card:    "0.75rem",
    },
}

app.RegisterTheme("custom", customTheme)

CLI Tools

Command-line tools for project management:

# Create new project
forgeui new myproject

# Create new component
forgeui create component MyComponent

# Create new page
forgeui create page HomePage

# Run development server
forgeui dev

# Build for production
forgeui build

Architecture

ForgeUI follows a layered architecture designed for scalability and maintainability:

┌─────────────────────────────────────┐
│  Application Layer                  │
│  (Your App, Examples, CLI)          │
└──────────────┬──────────────────────┘
               │
┌──────────────▼──────────────────────┐
│  Integration Layer                  │
│  (Router, Bridge, HTMX, Alpine)     │
└──────────────┬──────────────────────┘
               │
┌──────────────▼──────────────────────┐
│  Components Layer                   │
│  (UI Components, Icons, Layouts)    │
└──────────────┬──────────────────────┘
               │
┌──────────────▼──────────────────────┐
│  Foundation Layer                   │
│  (Primitives, CVA, Theme, Assets)   │
└─────────────────────────────────────┘
Design Principles
  • Composability: All components are composable templ components
  • Type Safety: Full Go type checking at compile time
  • Minimal Dependencies: Core components have zero client-side dependencies
  • Progressive Enhancement: Add interactivity with Alpine.js and HTMX
  • Unidirectional Flow: Higher layers depend on lower layers, never the reverse

Testing

ForgeUI includes comprehensive test coverage across all packages:

# Run all tests
go test ./...

# Run with coverage
go test -cover ./...

# Run with race detection
go test -race ./...

# Run specific package tests
go test ./components/button/...
go test ./router/...

# Generate coverage report
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
Test Structure

Components and features include:

  • Unit tests: Testing individual functions and components
  • Integration tests: Testing component interactions
  • HTTP tests: Using httptest for router and bridge testing
  • Golden files: Snapshot testing for component output

Configuration

Application Configuration
app := forgeui.New(
    // Core options
    forgeui.WithDebug(true),
    forgeui.WithThemeName("default"),
    forgeui.WithStaticPath("/static"),
    forgeui.WithDefaultSize(forgeui.SizeMD),
    forgeui.WithDefaultVariant(forgeui.VariantDefault),
    forgeui.WithDefaultRadius(forgeui.RadiusMD),
    
    // Assets configuration
    forgeui.WithAssets(assets.Config{
        Enabled:     true,
        OutputDir:   "./dist",
        Minify:      true,
        Fingerprint: true,
    }),
)

// Initialize the application
if err := app.Initialize(context.Background()); err != nil {
    log.Fatal(err)
}

// Start HTTP server
http.ListenAndServe(":8080", app.Router())
Environment-Specific Config
var cfg forgeui.Config

if os.Getenv("ENV") == "production" {
    cfg = forgeui.Config{
        Debug:      false,
        StaticPath: "/static",
        Assets: assets.Config{
            Enabled:     true,
            Minify:      true,
            Fingerprint: true,
        },
    }
} else {
    cfg = forgeui.Config{
        Debug:      true,
        StaticPath: "/static",
        Assets: assets.Config{
            Enabled:    true,
            Minify:     false,
            Fingerprint: false,
        },
    }
}

app := forgeui.NewWithConfig(cfg)

Examples

The example/ directory contains complete working examples:

cd example
go run main.go

Visit http://localhost:8080 to see:

  • Component Showcase: All UI components with variations
  • Dashboard Demo: Real-world dashboard layout
  • Interactive Examples: Alpine.js and HTMX integration
  • Router Demo: Client-side routing with Pinecone Router
  • Bridge Demo: Go-JavaScript RPC examples
  • Assets Demo: Asset pipeline in action

Documentation

Each package includes comprehensive documentation:

Project Structure

forgeui/
├── alpine/           # Alpine.js integration
├── animation/        # Animation and transition utilities
├── assets/          # Asset pipeline (CSS, JS, Tailwind)
├── bridge/          # Go-JavaScript RPC bridge
├── cli/             # Command-line tools
├── components/      # UI components
│   ├── button/
│   ├── card/
│   ├── form/
│   └── ...
├── example/         # Example applications
├── htmx/           # HTMX integration
├── icons/          # Icon system (Lucide)
├── htmx/           # HTMX integration
├── plugin/         # Plugin system
├── primitives/     # Layout primitives
├── router/         # HTTP router
├── theme/          # Theme system
└── ...

Contributing

ForgeUI welcomes contributions! Follow these guidelines:

Code Style
  1. Follow Go conventions: Use gofmt, golangci-lint
  2. Use templ templates: Write UI in .templ files with Props structs
  3. Use templui components: Leverage templui as the base component library
  4. Documentation: Document all exported functions with examples
  5. Type safety: Leverage Go's type system
Component Development
  1. Respect architecture layers: Components should only import from lower layers
  2. Test thoroughly: Aim for 80%+ coverage
  3. Include examples: Add examples to component documentation
  4. Accessibility: Follow ARIA guidelines
  5. Mobile-first: Ensure responsive design
Running Tests
# Run tests
go test ./...

# Run with coverage
go test -cover ./...

# Run linter
golangci-lint run
Pull Request Process
  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Write tests for your changes
  4. Ensure all tests pass
  5. Update documentation
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

Best Practices

Component Composition
// ✅ Good: Compose templ components
@button.Button(button.Props{}) {
    @icons.Plus(icons.WithSize(16))
    Add Item
}
Error Handling
// ✅ Good: Return errors from handlers
func UserProfile(ctx *router.PageContext) (templ.Component, error) {
    user, err := getUser(ctx.Param("id"))
    if err != nil {
        return nil, err
    }
    return UserProfileView(user), nil
}

// ❌ Bad: Don't panic or ignore errors
Context Usage
// ✅ Good: Pass context through the stack
func handler(ctx *router.PageContext) (templ.Component, error) {
    user := ctx.GetString("user_id")
    return UserView(user), nil
}

// ❌ Bad: Don't use global variables

Performance

ForgeUI is designed for performance:

Server-Side Rendering
  • Fast: Pure Go rendering with minimal overhead
  • Efficient: No JavaScript runtime required for basic pages
  • Scalable: Handles thousands of requests per second
Asset Pipeline
  • Optimized: Built-in minification and fingerprinting
  • Cached: Long-lived browser caching with cache busting
  • Small: Tailwind CSS purging removes unused styles
Progressive Enhancement
  • Lightweight: Start with 0KB of JavaScript
  • Optional: Add Alpine.js (15KB) or HTMX (14KB) only when needed
  • Lazy: Load components on demand
Benchmarks

Typical performance on modest hardware (4 core, 8GB RAM):

  • Simple page render: ~0.5ms
  • Complex dashboard: ~2ms
  • Component with children: ~0.1ms per child
  • Throughput: 10,000+ req/s

Production Checklist

Before deploying to production:

  • Set WithDebug(false)
  • Enable asset minification
  • Enable asset fingerprinting
  • Use HTTPS (TLS)
  • Set up proper logging
  • Configure CORS if needed
  • Set up rate limiting
  • Enable CSRF protection
  • Configure proper caching headers
  • Test with production data
  • Set up monitoring and alerts

Troubleshooting

Common Issues

Components not rendering?

  • Check if you've initialized the app with app.Initialize(ctx)
  • Verify Tailwind CSS is included in your HTML

Styles not applying?

  • Ensure Tailwind CSS is properly configured
  • Check if the asset pipeline is enabled
  • Verify the CSS file is being served

HTMX not working?

  • Include htmx.Scripts() in your HTML head
  • Check browser console for errors
  • Verify HTMX attributes are correct

Alpine.js not working?

  • Include alpine.Scripts() in your HTML head
  • Check for JavaScript errors in console
  • Verify Alpine syntax is correct

Community & Support

Roadmap

Planned features and improvements:

  • More component variants and customization options
  • Server-side validation helpers
  • Form builder with automatic validation
  • More built-in plugins
  • WebSocket utilities
  • Admin panel template
  • CLI improvements (scaffolding, generators)
  • Performance monitoring utilities
  • i18n support

License

MIT License - See LICENSE file for details

Credits & Inspiration

ForgeUI stands on the shoulders of giants:

  • templ - Type-safe HTML templating for Go
  • templui - shadcn-inspired component library for templ
  • shadcn/ui - Design inspiration and component patterns
  • Tailwind CSS - Utility-first CSS framework
  • Alpine.js - Lightweight JavaScript framework
  • HTMX - High power tools for HTML
  • Lucide - Beautiful icon library

Made with ❤️ for the Go community

Documentation

Overview

Package forgeui is an SSR-first UI framework for Go

ForgeUI provides a full-stack web application framework built on templ with Alpine.js interactivity, Tailwind CSS styling, and templui components.

Key Features:

  • SSR-first with progressive enhancement
  • Type-safe templ templates
  • templui component library (shadcn-inspired)
  • Alpine.js and HTMX integration helpers
  • Functional options pattern for flexible configuration
  • Plugin system for extensibility

Basic usage:

app := forgeui.New(
    forgeui.WithDebug(true),
    forgeui.WithThemeName("default"),
)

app.Get("/", func(ctx *router.PageContext) (templ.Component, error) {
    return HomePage(), nil
})

http.ListenAndServe(":3000", app.Handler())

Subpackages:

  • plugin: Plugin system for extending ForgeUI functionality
  • router: HTTP routing with layouts, loaders, and middleware
  • theme: Theme system with dark mode support
  • alpine: Alpine.js integration helpers
  • htmx: HTMX attribute helpers
  • assets: Asset management and fingerprinting
  • bridge: Go-JS RPC bridge
  • primitives: Low-level layout primitives
  • components: templui-based UI component library
  • icons: Icon system with Lucide icons

Index

Constants

View Source
const Version = "0.0.3"

Version is the current version of ForgeUI

Variables

This section is empty.

Functions

func ApplyOptions

func ApplyOptions[T any](props *T, opts []Option[T])

ApplyOptions applies a slice of options to props This is a helper function for components to apply functional options

func CN

func CN(classes ...string) string

CN (ClassName) merges class names, filtering empty strings This is useful for combining multiple class strings with conditional classes

func If

func If(condition bool, value string) string

If returns the value if condition is true, empty string otherwise Useful for conditional class application

func IfElse

func IfElse(condition bool, trueVal, falseVal string) string

IfElse returns trueVal if condition is true, falseVal otherwise Useful for binary conditional class application

func MapGet

func MapGet[K comparable, V any](m map[K]V, key K, defaultVal V) V

MapGet returns map value or default value if key doesn't exist Generic helper for safely accessing maps with defaults

func ThemeFromContext

func ThemeFromContext(ctx context.Context) (any, bool)

ThemeFromContext retrieves theme from context

func ToString

func ToString(v any) string

ToString converts various types to string for HTML attributes

func WithConfig

func WithConfig(ctx context.Context, config *Config) context.Context

WithConfig adds config to context

func WithTheme

func WithTheme(ctx context.Context, theme any) context.Context

WithTheme adds theme to context

Types

type Align

type Align string

Align represents alignment for floating elements

const (
	AlignStart  Align = "start"
	AlignCenter Align = "center"
	AlignEnd    Align = "end"
)

type App

type App struct {
	Assets *assets.Manager
	// contains filtered or unexported fields
}

App is the main ForgeUI application with enhanced features

func New

func New(opts ...AppOption) *App

New creates a new ForgeUI application with enhanced initialization

func (*App) AlpineBridgeScriptPath added in v0.0.8

func (a *App) AlpineBridgeScriptPath() string

AlpineBridgeScriptPath returns the full path to the Alpine bridge JavaScript file

func (*App) Bridge added in v0.0.2

func (a *App) Bridge() *bridge.Bridge

Bridge returns the bridge system (may be nil if not enabled)

func (*App) BridgeCallPath added in v0.0.8

func (a *App) BridgeCallPath() string

BridgeCallPath returns the full bridge call endpoint path

func (*App) BridgeScriptPath added in v0.0.8

func (a *App) BridgeScriptPath() string

BridgeScriptPath returns the full path to the bridge JavaScript file

func (*App) BridgeScripts added in v0.0.8

func (a *App) BridgeScripts(includeAlpine bool, csrfToken ...string) templ.Component

BridgeScripts returns properly configured bridge script tags as a templ.Component. This respects the BasePath configuration.

func (*App) BridgeStreamPath added in v0.0.8

func (a *App) BridgeStreamPath() string

BridgeStreamPath returns the full bridge stream endpoint path

func (*App) CSSPath added in v1.0.0

func (a *App) CSSPath() string

CSSPath returns the URL path to the compiled CSS stylesheet. This respects the BasePath and StaticPath configuration.

func (*App) Config

func (a *App) Config() *AppConfig

Config returns the application configuration

func (*App) DarkTheme added in v0.0.2

func (a *App) DarkTheme() *theme.Theme

DarkTheme returns the dark theme

func (*App) Delete

func (a *App) Delete(pattern string, handler router.PageHandler) *router.Route

Delete registers a DELETE route (convenience method)

func (*App) FontFaceCSS added in v1.0.0

func (a *App) FontFaceCSS() string

FontFaceCSS returns the @font-face CSS rules for all configured fonts. Returns an empty string if no font config is set.

func (a *App) FontPreloadLinks() templ.Component

FontPreloadLinks returns a templ.Component that renders <link rel="preload"> tags for all configured fonts that have Preload: true. Returns a nop component if no font config is set.

func (*App) Get

func (a *App) Get(pattern string, handler router.PageHandler) *router.Route

Get registers a GET route (convenience method)

func (*App) Group added in v0.0.2

func (a *App) Group(prefix string) *router.Group

Group creates a new route group

func (*App) Handler added in v0.0.2

func (a *App) Handler() http.Handler

Handler returns an http.Handler that serves the entire application This includes static assets, bridge endpoints, and routed pages

func (*App) HasBridge added in v0.0.2

func (a *App) HasBridge() bool

HasBridge returns true if bridge system is enabled

func (*App) HotReloadPath added in v0.0.8

func (a *App) HotReloadPath() string

HotReloadPath returns the full hot reload SSE endpoint path

func (*App) Initialize

func (a *App) Initialize(ctx context.Context) error

Initialize prepares the application (plugins, router, assets, etc.) This will be expanded in later phases as more systems are added

func (*App) IsCDNMode added in v1.0.0

func (a *App) IsCDNMode() bool

IsCDNMode returns true if compiled CSS was not built (e.g., Tailwind CLI not available). When in CDN mode, layouts should include the Tailwind CDN script and inline theme styles.

func (*App) IsDev

func (a *App) IsDev() bool

IsDev returns true if the application is in debug/development mode

func (*App) LightTheme added in v0.0.2

func (a *App) LightTheme() *theme.Theme

LightTheme returns the light theme

func (*App) Page added in v0.0.2

func (a *App) Page(pattern string) *PageBuilder

Page creates a new PageBuilder for fluent page registration

func (*App) Patch

func (a *App) Patch(pattern string, handler router.PageHandler) *router.Route

Patch registers a PATCH route (convenience method)

func (*App) Post

func (a *App) Post(pattern string, handler router.PageHandler) *router.Route

Post registers a POST route (convenience method)

func (*App) Put

func (a *App) Put(pattern string, handler router.PageHandler) *router.Route

Put registers a PUT route (convenience method)

func (*App) RegisterLayout added in v0.0.2

func (a *App) RegisterLayout(name string, fn router.LayoutFunc, opts ...router.LayoutOption)

RegisterLayout registers a named layout

func (*App) Router

func (a *App) Router() *router.Router

Router returns the application's HTTP router

func (*App) StaticPath added in v1.0.0

func (a *App) StaticPath() string

StaticPath returns the full URL path prefix for static assets.

func (*App) Theme added in v0.0.2

func (a *App) Theme() *theme.Theme

Theme returns the light theme

func (*App) ThemeStylesheet added in v1.0.0

func (a *App) ThemeStylesheet() templ.Component

ThemeStylesheet returns a <link rel="stylesheet"> templ.Component for the compiled CSS. Returns a nop component if CSS was not compiled (CDN mode).

func (*App) Use

func (a *App) Use(middleware ...router.Middleware) *App

Use adds global middleware (convenience method)

type AppConfig

type AppConfig struct {
	// Debug enables debug/development mode
	Debug bool

	// Theme is the active theme name (legacy support)
	Theme string

	// AssetPublicDir is the source directory for static assets
	AssetPublicDir string

	// AssetOutputDir is the output directory for processed assets
	AssetOutputDir string

	// AssetManifest is the path to a manifest file for production builds
	AssetManifest string

	// AssetFileSystem is an optional custom filesystem for assets (e.g., embed.FS)
	AssetFileSystem fs.FS

	// Bridge configuration (optional)
	BridgeConfig *bridge.Config
	EnableBridge bool

	// Theme configuration (enhanced)
	LightTheme *theme.Theme
	DarkTheme  *theme.Theme

	// FontConfig holds typography configuration (fonts, preloading, etc.)
	FontConfig *theme.FontConfig

	// DefaultLayout is the default layout name for all pages
	DefaultLayout string

	// InputCSS is an optional path to a custom Tailwind v4 input CSS file.
	// When set, this is used instead of auto-generating one from themes.
	InputCSS string

	// Verbose enables detailed logging for asset processing and other subsystems.
	Verbose bool

	// BasePath is the base URL path for all ForgeUI routes (static, bridge, etc.)
	// Example: "/api/identity/ui" results in:
	//   - Static: /api/identity/ui/static/...
	//   - Bridge: /api/identity/ui/bridge/...
	BasePath string

	// StaticPath is the URL path for static assets (relative to BasePath if set)
	// Default: "/static"
	StaticPath string

	// Component defaults (from legacy Config)
	DefaultSize    Size
	DefaultVariant Variant
	DefaultRadius  Radius
}

AppConfig holds enhanced ForgeUI application configuration

func DefaultAppConfig

func DefaultAppConfig() *AppConfig

DefaultAppConfig returns sensible defaults for ForgeUI application

type AppOption

type AppOption func(*AppConfig)

AppOption is a functional option for configuring the App

func WithAppStaticPath

func WithAppStaticPath(path string) AppOption

WithAppStaticPath sets the URL path for static assets

func WithAssetFileSystem added in v0.0.8

func WithAssetFileSystem(fsys fs.FS) AppOption

WithAssetFileSystem sets a custom filesystem for serving assets (e.g., embed.FS) This is useful when embedding assets in the binary or using custom filesystem implementations

func WithAssetManifest

func WithAssetManifest(path string) AppOption

WithAssetManifest sets the path to a manifest file for production builds

func WithAssetOutputDir

func WithAssetOutputDir(dir string) AppOption

WithAssetOutputDir sets the output directory for processed assets

func WithAssetPublicDir

func WithAssetPublicDir(dir string) AppOption

WithAssetPublicDir sets the source directory for static assets

func WithAssets

func WithAssets(publicDir string, opts ...string) AppOption

WithAssets sets the asset directories

func WithAssetsPath

func WithAssetsPath(path string) AppOption

WithAssetsPath sets the filesystem assets path (deprecated, use WithAssetPublicDir)

func WithBasePath added in v0.0.8

func WithBasePath(path string) AppOption

WithBasePath sets the base URL path for all ForgeUI routes This prefixes static, bridge, and other ForgeUI endpoints Example: WithBasePath("/api/identity/ui") results in:

  • Static: /api/identity/ui/static/...
  • Bridge: /api/identity/ui/bridge/...

func WithBridge

func WithBridge(opts ...bridge.ConfigOption) AppOption

WithBridge enables and configures the bridge system

func WithDebug

func WithDebug(debug bool) AppOption

WithDebug enables or disables debug mode (alias for WithDev)

func WithDefaultLayout

func WithDefaultLayout(layout string) AppOption

WithDefaultLayout sets the default layout for all pages

func WithDefaultRadius

func WithDefaultRadius(radius Radius) AppOption

WithDefaultRadius sets the default border radius

func WithDefaultSize

func WithDefaultSize(size Size) AppOption

WithDefaultSize sets the default component size

func WithDefaultVariant

func WithDefaultVariant(variant Variant) AppOption

WithDefaultVariant sets the default component variant

func WithDev

func WithDev(dev bool) AppOption

WithDev enables or disables development mode

func WithEmbedFS added in v0.0.8

func WithEmbedFS(fsys fs.FS) AppOption

WithEmbedFS is an alias for WithAssetFileSystem for better discoverability

func WithFonts added in v1.0.0

func WithFonts(fc *theme.FontConfig) AppOption

WithFonts sets the font configuration for the application. This enables font preloading and @font-face generation.

func WithInputCSS added in v1.0.0

func WithInputCSS(path string) AppOption

WithInputCSS sets a custom Tailwind v4 input CSS file. When set, this is used instead of auto-generating one from themes.

func WithStaticPath

func WithStaticPath(path string) AppOption

WithStaticPath sets the static assets path (alias for WithAppStaticPath)

func WithThemeName

func WithThemeName(theme string) AppOption

WithThemeName sets the theme name (legacy support)

func WithThemes

func WithThemes(light, dark *theme.Theme) AppOption

WithThemes sets the light and dark themes

func WithVerbose added in v1.0.0

func WithVerbose(verbose bool) AppOption

WithVerbose enables verbose logging for asset processing

type BaseProps

type BaseProps struct {
	Class    string
	Disabled bool
	ID       string
}

BaseProps contains common properties shared by many components

type CVA

type CVA struct {
	// contains filtered or unexported fields
}

CVA (Class Variance Authority) manages component class variants It provides a type-safe way to handle component variants and their combinations

func NewCVA

func NewCVA(base ...string) *CVA

NewCVA creates a new CVA instance with base classes Base classes are always included in the output

func (*CVA) Classes

func (c *CVA) Classes(variants map[string]string) string

Classes generates the final class string based on the provided variant values It combines base classes, variant-specific classes, and compound variant classes

func (*CVA) Compound

func (c *CVA) Compound(conditions map[string]string, classes ...string) *CVA

Compound adds a compound variant rule that applies classes when multiple conditions match Example: cva.Compound(map[string]string{"size": "sm", "variant": "primary"}, "extra-class")

func (*CVA) Default

func (c *CVA) Default(name, value string) *CVA

Default sets the default value for a variant dimension This value is used when no value is explicitly provided for that variant

func (*CVA) Variant

func (c *CVA) Variant(name string, options map[string][]string) *CVA

Variant adds a variant dimension with its possible values and corresponding classes Example: cva.Variant("size", map[string][]string{"sm": {"text-sm", "px-2"}, "lg": {"text-lg", "px-4"}})

type ComponentError

type ComponentError struct {
	Component string
	Message   string
	Err       error
}

ComponentError represents an error in component rendering

func (*ComponentError) Error

func (e *ComponentError) Error() string

func (*ComponentError) Unwrap

func (e *ComponentError) Unwrap() error

type CompoundVariant

type CompoundVariant struct {
	Conditions map[string]string
	Classes    []string
}

CompoundVariant applies classes when multiple conditions match

type Config deprecated

type Config struct {
	// Debug enables debug mode
	Debug bool

	// Theme is the active theme name
	Theme string

	// StaticPath is the URL path for static assets
	StaticPath string

	// AssetsPath is the filesystem path for assets (deprecated, use AssetPublicDir)
	AssetsPath string

	// AssetPublicDir is the source directory for static assets
	AssetPublicDir string

	// AssetOutputDir is the output directory for processed assets
	AssetOutputDir string

	// AssetManifest is the path to a manifest file for production builds
	AssetManifest string

	// DefaultSize is the default component size
	DefaultSize Size

	// DefaultVariant is the default component variant
	DefaultVariant Variant

	// DefaultRadius is the default border radius
	DefaultRadius Radius
}

Config holds ForgeUI application configuration

Deprecated: Use AppConfig instead. Config is kept for backward compatibility.

func ConfigFromContext

func ConfigFromContext(ctx context.Context) (*Config, bool)

ConfigFromContext retrieves config from context

func DefaultConfig deprecated

func DefaultConfig() *Config

DefaultConfig returns sensible defaults for ForgeUI configuration

Deprecated: Use DefaultAppConfig instead

type ConfigOption

type ConfigOption = AppOption

ConfigOption is a functional option for Config Note: ConfigOption is now an alias for AppOption for unified configuration

type Option

type Option[T any] func(*T)

Option is a generic functional option type for configuring component properties

type PageBuilder

type PageBuilder struct {
	// contains filtered or unexported fields
}

PageBuilder provides a fluent API for building and registering pages

func (*PageBuilder) DELETE

func (pb *PageBuilder) DELETE() *PageBuilder

DELETE is a convenience method to set method to DELETE

func (*PageBuilder) GET

func (pb *PageBuilder) GET() *PageBuilder

GET is a convenience method to set method to GET

func (*PageBuilder) Handler

func (pb *PageBuilder) Handler(handler router.PageHandler) *PageBuilder

Handler sets the page handler function

func (*PageBuilder) Layout

func (pb *PageBuilder) Layout(layout string) *PageBuilder

Layout sets the layout name for this page

func (*PageBuilder) Loader

func (pb *PageBuilder) Loader(loader router.LoaderFunc) *PageBuilder

Loader sets the data loader function

func (*PageBuilder) Meta

func (pb *PageBuilder) Meta(title, description string) *PageBuilder

Meta sets the page metadata (title and description)

func (*PageBuilder) MetaFull

func (pb *PageBuilder) MetaFull(meta *router.RouteMeta) *PageBuilder

MetaFull sets complete page metadata

func (*PageBuilder) Method

func (pb *PageBuilder) Method(method string) *PageBuilder

Method sets the HTTP method for this page

func (*PageBuilder) Middleware

func (pb *PageBuilder) Middleware(middleware ...router.Middleware) *PageBuilder

Middleware adds middleware to this page

func (*PageBuilder) Name

func (pb *PageBuilder) Name(name string) *PageBuilder

Name sets a name for this route (for URL generation)

func (*PageBuilder) NoLayout

func (pb *PageBuilder) NoLayout() *PageBuilder

NoLayout disables layout for this page

func (*PageBuilder) PATCH

func (pb *PageBuilder) PATCH() *PageBuilder

PATCH is a convenience method to set method to PATCH

func (*PageBuilder) POST

func (pb *PageBuilder) POST() *PageBuilder

POST is a convenience method to set method to POST

func (*PageBuilder) PUT

func (pb *PageBuilder) PUT() *PageBuilder

PUT is a convenience method to set method to PUT

func (*PageBuilder) Register

func (pb *PageBuilder) Register() *router.Route

Register registers the page with the router

type PluginError

type PluginError struct {
	Plugin  string
	Message string
	Err     error
}

PluginError represents a plugin-related error

func (*PluginError) Error

func (e *PluginError) Error() string

func (*PluginError) Unwrap

func (e *PluginError) Unwrap() error

type Position

type Position string

Position represents positioning for floating elements (popovers, tooltips, dropdowns)

const (
	PositionTop    Position = "top"
	PositionRight  Position = "right"
	PositionBottom Position = "bottom"
	PositionLeft   Position = "left"
)

type Props

type Props any

Props is the base interface for component properties Components can implement this interface to add validation

type Radius

type Radius string

Radius represents border radius options

const (
	RadiusNone Radius = "none"
	RadiusSM   Radius = "sm"
	RadiusMD   Radius = "md"
	RadiusLG   Radius = "lg"
	RadiusXL   Radius = "xl"
	RadiusFull Radius = "full"
)

type Side

type Side string

Side represents positioning side for drawers, popovers, etc.

const (
	SideTop    Side = "top"
	SideRight  Side = "right"
	SideBottom Side = "bottom"
	SideLeft   Side = "left"
)

type Size

type Size string

Size represents component size variants

const (
	SizeXS   Size = "xs"
	SizeSM   Size = "sm"
	SizeMD   Size = "md"
	SizeLG   Size = "lg"
	SizeXL   Size = "xl"
	SizeFull Size = "full" // Full width/height for modals
	SizeIcon Size = "icon" // Special size for icon-only buttons
)

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a props validation error

func (*ValidationError) Error

func (e *ValidationError) Error() string

type Variant

type Variant string

Variant represents visual style variants

const (
	VariantDefault     Variant = "default"
	VariantPrimary     Variant = "primary"
	VariantSecondary   Variant = "secondary"
	VariantDestructive Variant = "destructive"
	VariantOutline     Variant = "outline"
	VariantGhost       Variant = "ghost"
	VariantLink        Variant = "link"
)

Directories

Path Synopsis
Package alpine provides Alpine.js integration helpers for ForgeUI.
Package alpine provides Alpine.js integration helpers for ForgeUI.
Package animation provides smooth transitions and animations for ForgeUI components.
Package animation provides smooth transitions and animations for ForgeUI components.
cli
Package cli provides a command-line interface framework for ForgeUI.
Package cli provides a command-line interface framework for ForgeUI.
cmd
forgeui command
components
icon
templui component icon - version: v1.5.0 installed by templui v1.5.0 📚 Documentation: https://templui.io/docs/components/icon
templui component icon - version: v1.5.0 installed by templui v1.5.0 📚 Documentation: https://templui.io/docs/components/icon
Package htmx provides HTMX integration for ForgeUI.
Package htmx provides HTMX integration for ForgeUI.
Package icons provides a flexible icon system with Lucide icon integration.
Package icons provides a flexible icon system with Lucide icon integration.
Package plugin provides the ForgeUI plugin system.
Package plugin provides the ForgeUI plugin system.
Package plugins provides convenience imports for all built-in ForgeUI plugins.
Package plugins provides convenience imports for all built-in ForgeUI plugins.
analytics
Package analytics provides event tracking integration for ForgeUI.
Package analytics provides event tracking integration for ForgeUI.
charts
Package charts provides data visualization components using Chart.js.
Package charts provides data visualization components using Chart.js.
htmxplugin
Package htmxplugin provides an HTMX plugin wrapper for ForgeUI's plugin system.
Package htmxplugin provides an HTMX plugin wrapper for ForgeUI's plugin system.
seo
Package seo provides SEO meta tag and structured data management for ForgeUI.
Package seo provides SEO meta tag and structured data management for ForgeUI.
sortable
Package sortable provides drag-and-drop list reordering using SortableJS.
Package sortable provides drag-and-drop list reordering using SortableJS.
themes/corporate
Package corporate provides a professional theme preset for business applications.
Package corporate provides a professional theme preset for business applications.
toast
Package toast provides a toast notification plugin for ForgeUI.
Package toast provides a toast notification plugin for ForgeUI.
Package primitives provides low-level layout primitives for ForgeUI.
Package primitives provides low-level layout primitives for ForgeUI.
Package theme provides a comprehensive theming system with color tokens, dark mode support, and CSS generation following shadcn/ui design patterns.
Package theme provides a comprehensive theming system with color tokens, dark mode support, and CSS generation following shadcn/ui design patterns.
templui util templui.go - version: v1.5.0 installed by templui v1.5.0
templui util templui.go - version: v1.5.0 installed by templui v1.5.0

Jump to

Keyboard shortcuts

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