forgeui

package module
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: 10 Imported by: 0

README

ForgeUI

ForgeUI is a comprehensive SSR-first UI framework for Go, built on gomponents with 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 functional options pattern
  • CVA: Class Variance Authority for flexible variant management
  • 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
  • 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 - no JavaScript required
  • 🎯 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
package main

import (
    "log"
    "net/http"
    
    g "maragu.dev/gomponents"
    "maragu.dev/gomponents/html"
    
    "github.com/xraph/forgeui"
    "github.com/xraph/forgeui/components/button"
    "github.com/xraph/forgeui/components/card"
    "github.com/xraph/forgeui/primitives"
    "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.Router())
}

func HomePage(ctx *router.PageContext) (g.Node, error) {
    return html.Html(
        html.Head(
            html.Meta(html.Charset("UTF-8")),
            html.Title(g.Text("ForgeUI App")),
            html.Link(html.Rel("stylesheet"), html.Href("/static/styles.css")),
        ),
        html.Body(
            primitives.Container(
                primitives.VStack("8",
                    card.Card(
                        card.Header(
                            card.Title("Welcome to ForgeUI"),
                            card.Description("Build beautiful UIs with Go"),
                        ),
                        card.Content(
                            primitives.VStack("4",
                                primitives.Text(
                                    primitives.TextChildren(
                                        g.Text("ForgeUI provides type-safe, composable UI components."),
                                    ),
                                ),
                                button.Primary(
                                    g.Text("Get Started"),
                                    button.WithSize(forgeui.SizeLG),
                                ),
                            ),
                        ),
                    ),
                ),
            ),
        ),
    ), nil
}
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:

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

func HomePage(ctx *router.PageContext) (g.Node, error) {
    return html.Html(
        html.Head(
            html.Title(g.Text("Interactive App")),
            alpine.Scripts(), // Add Alpine.js
        ),
        html.Body(
            html.Div(
                alpine.XData(`{count: 0}`),
                html.Button(
                    alpine.XOn("click", "count++"),
                    g.Text("Increment"),
                ),
                html.Span(alpine.XText("count")),
            ),
        ),
    ), nil
}

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 Variants
// Primary button
button.Primary(g.Text("Save"))

// Destructive button
button.Destructive(
    g.Text("Delete"),
    button.WithSize(forgeui.SizeLG),
)

// Icon button
button.IconButton(
    g.Text("×"),
    button.WithVariant(forgeui.VariantGhost),
)

// Button group
button.Group(
    []button.GroupOption{button.WithGap("2")},
    button.Primary(g.Text("Save")),
    button.Secondary(g.Text("Cancel")),
)
Card Component
card.Card(
    card.Header(
        card.Title("Settings"),
        card.Description("Manage your account settings"),
    ),
    card.Content(
        // Your content here
    ),
    card.Footer(
        button.Primary(g.Text("Save Changes")),
    ),
)
Form Example
form.Form(
    []form.Option{
        form.WithAction("/submit"),
        form.WithMethod("POST"),
    },
    input.Field(
        "Email",
        []input.Option{
            input.WithType("email"),
            input.WithName("email"),
            input.WithPlaceholder("Enter your email"),
            input.Required(),
        },
        input.FormDescription("We'll never share your email."),
    ),
    checkbox.Checkbox(
        checkbox.WithName("subscribe"),
        checkbox.WithID("subscribe"),
    ),
    button.Primary(
        g.Text("Submit"),
        button.WithType("submit"),
    ),
)
Layout with Primitives
primitives.Container(
    primitives.VStack("8",
        primitives.Text(
            primitives.TextAs("h1"),
            primitives.TextSize("text-4xl"),
            primitives.TextWeight("font-bold"),
            primitives.TextChildren(g.Text("Dashboard")),
        ),
        primitives.Grid(
            primitives.GridCols(1),
            primitives.GridColsMD(2),
            primitives.GridColsLG(3),
            primitives.GridGap("6"),
            primitives.GridChildren(
                card.Card(/* ... */),
                card.Card(/* ... */),
                card.Card(/* ... */),
            ),
        ),
    ),
)

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) (g.Node, 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)
    userID := ctx.GetInt("user_id")
    
    return html.Div(/* ... */), 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
html.Head(
    bridge.BridgeScripts(bridge.ScriptConfig{
        Endpoint: "/api/bridge",
        CSRFToken: csrfToken,
        IncludeAlpine: true,
    }),
)

// Alpine.js integration
html.Button(
    g.Attr("@click", "result = await $bridge.call('createUser', {name, email})"),
    g.Text("Create User"),
)

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:

// Include HTMX
html.Head(
    htmx.Scripts(),
    htmx.IndicatorCSS(),
)

// HTMX attributes
html.Button(
    htmx.HxGet("/api/users"),
    htmx.HxTarget("#user-list"),
    htmx.HxSwap("innerHTML"),
    g.Text("Load Users"),
)

// Advanced triggers
html.Input(
    htmx.HxTriggerDebounce("keyup", "500ms"),
    htmx.HxGet("/search"),
)

// Server-side detection
func handler(w http.ResponseWriter, r *http.Request) {
    if htmx.IsHTMX(r) {
        // Return partial HTML
        renderPartial(w)
    } else {
        // Return full page
        renderFullPage(w)
    }
}

// Response headers
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
html.Head(
    alpine.Scripts(),
)

// Alpine directives
html.Div(
    alpine.XData(`{count: 0}`),
    html.Button(
        alpine.XOn("click", "count++"),
        g.Text("Increment"),
    ),
    html.Span(alpine.XText("count")),
)

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

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

Icons

1600+ Lucide icons with full customization:

// Basic usage
icons.Check()
icons.Search()
icons.User()

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

// In buttons
button.Primary(
    g.Group([]g.Node{
        icons.Plus(icons.WithSize(16)),
        g.Text("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 gomponents nodes
  • 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
  • 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)
├── layout/         # Layout helpers
├── 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 CVA for variants: All component variants should use CVA
  3. Functional options pattern: Use for component configuration
  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 components
button.Primary(
    g.Group([]g.Node{
        icons.Plus(icons.WithSize(16)),
        g.Text("Add Item"),
    }),
)

// ❌ Bad: Don't nest unrelated components
Error Handling
// ✅ Good: Return errors from handlers
func UserProfile(ctx *router.PageContext) (g.Node, error) {
    user, err := getUser(ctx.Param("id"))
    if err != nil {
        return nil, err
    }
    return renderUser(user), nil
}

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

// ❌ Bad: Don't use global variables
Performance
// ✅ Good: Reuse nodes when possible
var headerNode = html.Header(/* ... */)

// ✅ Good: Use streaming for large responses
// ✅ Good: Enable asset fingerprinting in production
// ✅ Good: Minify CSS and JS in production

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:

  • gomponents - The foundation for Go HTML components
  • 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 component library for Go

ForgeUI provides type-safe, composable UI components built on gomponents with Alpine.js interactivity, Tailwind CSS styling, and shadcn-inspired design.

Key Features:

  • SSR-first with progressive enhancement
  • Pure Go API with full type safety
  • CVA (Class Variance Authority) for variant management
  • Functional options pattern for flexible configuration
  • Comprehensive component library
  • Plugin system for extensibility

Basic usage:

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

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

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
  • animation: Animation and transition utilities
  • assets: Asset management and fingerprinting
  • primitives: Low-level layout primitives
  • components: 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) 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) 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) 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) 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) 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) Theme added in v0.0.2

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

Theme returns the light theme

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

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

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

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

	// StaticPath is the URL path for static assets
	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 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 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 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

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 Node

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

Node wraps gomponents.Node with a fluent API for building HTML elements

func El

func El(tag string) *Node

El creates a new element node with the specified HTML tag

func (*Node) Attr

func (n *Node) Attr(key, value string) *Node

Attr adds an HTML attribute to the element

func (*Node) Build

func (n *Node) Build() g.Node

Build renders the node to a gomponents.Node This is the final step that produces the actual renderable element

func (*Node) Children

func (n *Node) Children(children ...g.Node) *Node

Children adds child nodes to the element

func (*Node) Class

func (n *Node) Class(classes ...string) *Node

Class adds CSS classes to the element Multiple calls accumulate classes

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
accordion
Package accordion provides collapsible accordion components following shadcn/ui patterns.
Package accordion provides collapsible accordion components following shadcn/ui patterns.
alert
Package alert provides alert components with different variants.
Package alert provides alert components with different variants.
avatar
Package avatar provides avatar components with image and fallback support.
Package avatar provides avatar components with image and fallback support.
badge
Package badge provides badge/tag components with variant support.
Package badge provides badge/tag components with variant support.
breadcrumb
Package breadcrumb provides breadcrumb navigation components following shadcn/ui patterns.
Package breadcrumb provides breadcrumb navigation components following shadcn/ui patterns.
button
Package button provides button components with multiple variants, sizes, and states following shadcn/ui design patterns.
Package button provides button components with multiple variants, sizes, and states following shadcn/ui design patterns.
card
Package card provides card components following shadcn/ui patterns.
Package card provides card components following shadcn/ui patterns.
checkbox
Package checkbox provides checkbox components.
Package checkbox provides checkbox components.
dropdown
Package dropdown provides dropdown menu components with keyboard navigation.
Package dropdown provides dropdown menu components with keyboard navigation.
emptystate
Package emptystate provides an EmptyState component for displaying "no data" or "empty results" scenarios with optional icons, text, and actions.
Package emptystate provides an EmptyState component for displaying "no data" or "empty results" scenarios with optional icons, text, and actions.
form
Package form provides form wrapper and validation helpers.
Package form provides form wrapper and validation helpers.
input
Package input provides input components for forms.
Package input provides input components for forms.
label
Package label provides label components for form fields.
Package label provides label components for form fields.
list
Package list provides list components for displaying items in ordered or unordered lists with various styling options.
Package list provides list components for displaying items in ordered or unordered lists with various styling options.
menu
Package menu provides menu and navigation components following shadcn/ui patterns.
Package menu provides menu and navigation components following shadcn/ui patterns.
modal
Package modal provides modal dialog components with Alpine.js state management.
Package modal provides modal dialog components with Alpine.js state management.
pagination
Package pagination provides pagination components following shadcn/ui patterns.
Package pagination provides pagination components following shadcn/ui patterns.
popover
Package popover provides floating content anchored to a trigger element.
Package popover provides floating content anchored to a trigger element.
progress
Package progress provides progress bar components.
Package progress provides progress bar components.
radio
Package radio provides radio button components.
Package radio provides radio button components.
select
Package selectc provides select dropdown components matching shadcn/ui design.
Package selectc provides select dropdown components matching shadcn/ui design.
separator
Package separator provides horizontal and vertical separators.
Package separator provides horizontal and vertical separators.
sidebar
Package sidebar provides sidebar navigation components with provider pattern integration.
Package sidebar provides sidebar navigation components with provider pattern integration.
skeleton
Package skeleton provides skeleton loading placeholders.
Package skeleton provides skeleton loading placeholders.
slider
Package slider provides range slider components.
Package slider provides range slider components.
spinner
Package spinner provides loading spinner components.
Package spinner provides loading spinner components.
switch
Package switchc provides toggle switch components.
Package switchc provides toggle switch components.
table
Package table provides table components for displaying tabular data.
Package table provides table components for displaying tabular data.
tabs
Package tabs provides tab components following shadcn/ui patterns.
Package tabs provides tab components following shadcn/ui patterns.
textarea
Package textarea provides textarea components for multi-line text input.
Package textarea provides textarea components for multi-line text input.
toast
Package toast provides notification system with queue management.
Package toast provides notification system with queue management.
tooltip
Package tooltip provides small informational popups on hover or focus.
Package tooltip provides small informational popups on hover or focus.
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 layout provides composable layout builders for ForgeUI applications.
Package layout provides composable layout builders for ForgeUI applications.
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.

Jump to

Keyboard shortcuts

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