minty

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

Minty

Minty is a fresh, ultra-concise, type-safe HTML generation library for Go web applications. It provides a fluent API for creating HTML components without traditional templates, offering compile-time safety and excellent IDE support.

STATUS: PRELIMINAR, VERY BETA

DOCS: Completely out of sync, will be updating soon

EXAMPLES: The code examples are a sample of the best features that already work in minty's current incarnation. Ignore the docs for now.

Features

  • Type-safe HTML generation - Catch errors at compile time, not runtime
  • Fluent builder pattern - Intuitive, chainable API
  • Dynamic client-side components - Without writing any Javascript by hand
  • HTMX integration - First-class support for HTMX attributes and patterns
  • Theme system - Pluggable themes (Bootstrap, Tailwind, Bulma, Material Design)
  • Domain libraries - Pre-built components for common business domains
  • Control flow helpers - If, IfElse, Each, Map, Filter, and more
  • Zero dependencies - Pure Go, no external requirements

Installation

go get github.com/ha1tch/minty

Quick Start

package main

import (
    "os"
    mi "github.com/ha1tch/minty"
)

func main() {
    // Create a simple page
    page := func(b *mi.Builder) mi.Node {
        return b.Html(
            b.Head(b.Title("Hello Minty")),
            b.Body(
                b.H1(mi.Class("title"), "Welcome!"),
                b.P("This is a paragraph."),
                b.A(mi.Href("/about"), "Learn more"),
            ),
        )
    }
    
    // Render to stdout
    mi.Render(page, os.Stdout)
}

Package Structure

github.com/ha1tch/minty
├── /                    # Core library (HTML builder, attributes, HTMX)
├── mintytypes/          # Pure business types (Money, Address, Status, etc.)
├── mintyex/             # Extensions (UI helpers, re-exports mintytypes)  
├── mintyui/             # UI component abstractions (Theme interface)
├── domains/             # Business domain libraries (depend only on mintytypes)
│   ├── mintyfin/        # Finance domain (accounts, transactions, invoices)
│   ├── mintycart/       # E-commerce domain (products, carts, orders)
│   └── mintymove/       # Logistics domain (shipments, tracking, vehicles)
├── presentation/        # UI adapters (domain → themed components)
│   ├── mintyfinui/
│   ├── mintycartui/
│   └── mintymoveui/
├── themes/              # Theme implementations
│   ├── bootstrap/       # Bootstrap 5 theme
│   ├── tailwind/        # Tailwind CSS theme
│   ├── bulma/           # Bulma CSS theme
│   └── material/        # Material Design theme
├── examples/            # Example applications
└── docs/                # Comprehensive documentation
Clean Architecture

The dependency graph enforces clean architecture:

        mintytypes (pure - no dependencies)
        ↗          ↖
    minty           domains/*
        ↖          ↗
         mintyex
            ↑
      presentation/*
  • mintytypes: Pure business types with zero external dependencies
  • domains: Business logic depends only on mintytypes (no UI knowledge)
  • mintyex: UI helpers + re-exports mintytypes for convenience
  • presentation: Adapts domain data to themed UI components

Core Concepts

The Builder Pattern

All HTML elements are created through the Builder type. Use the global B instance or create your own:

import mi "github.com/ha1tch/minty"

// Using global builder
div := mi.B.Div(mi.Class("container"), "Hello")

// Using builder in templates (most common)
template := func(b *mi.Builder) mi.Node {
    return b.Div(mi.Class("container"),
        b.H1("Title"),
        b.P("Content"),
    )
}
Attributes

Attributes are created using helper functions:

b.A(
    mi.Href("/page"),
    mi.Class("nav-link"),
    mi.Target("_blank"),
    mi.Rel("noopener"),
    "Click me",
)
HTMX Integration

First-class HTMX support:

b.Button(
    mi.Class("btn"),
    mi.HtmxPost("/api/submit"),
    mi.HtmxTarget("#result"),
    mi.HtmxSwap("innerHTML"),
    mi.HtmxIndicator("#spinner"),
    "Submit",
)
Control Flow

Conditional rendering:

mi.If(isLoggedIn, userGreeting)
mi.IfElse(hasItems, itemsList, emptyMessage)
mi.Each(items, func(item Item) mi.H {
    return func(b *mi.Builder) mi.Node {
        return b.Li(item.Name)
    }
})

Themes

Use pre-built themes for consistent styling:

import (
    mi "github.com/ha1tch/minty"
    "github.com/ha1tch/minty/themes/bootstrap"
)

theme := bootstrap.NewBootstrapTheme()

// Use themed components
button := theme.Button("Click me", "primary")
card := theme.Card("Title", content)
form := theme.FormInput("Email", "email", "email")

Documentation

Comprehensive documentation is available in the /docs directory:

  1. Introduction - Getting started
  2. Design Philosophy - Architecture decisions
  3. Architecture - System design
  4. Syntax & API - Complete API reference
  5. Components - Component library
  6. HTMX Integration - HTMX patterns
  7. Business Domains - Domain libraries
  8. Iterators - Collection utilities
  9. Themes - Theme system
  10. Presentation Layer - UI patterns
  11. JavaScript Integration - JS interop

Examples

Run the simple example:

cd examples/simple
go run main.go

Development Status

All packages compile and tests pass.

Stable (Ready for use)
  • Core library (HTML builder, attributes)
  • HTMX integration
  • Theme system (Bootstrap, Tailwind, Bulma, Material)
  • Domain libraries (mintyfin, mintycart, mintymove)
  • Extensions (mintyex)
  • UI abstractions (mintyui)
  • Presentation adapters (mintycartui, mintyfinui, mintymoveui)

Standard Import Aliases

For consistency across the codebase, use these import aliases:

import (
    mi   "github.com/ha1tch/minty"           // Core library
    mt   "github.com/ha1tch/minty/mintytypes" // Pure business types
    miex "github.com/ha1tch/minty/mintyex"   // Extensions (includes mt re-exports)
    mui  "github.com/ha1tch/minty/mintyui"   // UI components
    
    // Domain packages (import mt, not miex)
    mifi "github.com/ha1tch/minty/domains/mintyfin"   // Finance
    mica "github.com/ha1tch/minty/domains/mintycart"  // E-commerce
    mimo "github.com/ha1tch/minty/domains/mintymove"  // Logistics
)

Note: Domain packages import mintytypes directly (as mt) to maintain clean architecture. Presentation layers can import mintyex which re-exports all types for convenience.

License

Apache 2.0

https://github.com/ha1tch/minty?tab=Apache-2.0-1-ov-file

Author

Copyright (C)2026 haitch

h@ual.fi

https://oldbytes.space/@haitchfive

Documentation

Overview

helpers.go provides utility functions for working with dynamic data in minty. These helpers bridge the gap between JavaScript's dynamic object model and Go's static type system, making it easier to work with map[string]interface{} data commonly encountered when migrating from React/JavaScript.

Import with: import mi "github.com/ha1tch/minty"

Package minty provides ultra-concise HTML generation for Go web applications. Import with: import mi "github.com/ha1tch/minty"

Index

Constants

This section is empty.

Variables

View Source
var B = &Builder{}

Global builder instance using standard Minty alias pattern

View Source
var HTMXSwapStrategies = struct {
	InnerHTML   string
	OuterHTML   string
	BeforeBegin string
	AfterBegin  string
	BeforeEnd   string
	AfterEnd    string
	Delete      string
	None        string
}{
	InnerHTML:   "innerHTML",
	OuterHTML:   "outerHTML",
	BeforeBegin: "beforebegin",
	AfterBegin:  "afterbegin",
	BeforeEnd:   "beforeend",
	AfterEnd:    "afterend",
	Delete:      "delete",
	None:        "none",
}

HTMXSwapStrategies provides constants for common swap strategies.

View Source
var HTMXTriggers = struct {
	Click         string
	Change        string
	KeyUp         string
	KeyDown       string
	Input         string
	Load          string
	Revealed      string
	Intersect     string
	SubmitForm    string
	ChangeDelayed string
	KeyUpDelayed  string
	InputDelayed  string
}{
	Click:         "click",
	Change:        "change",
	KeyUp:         "keyup",
	KeyDown:       "keydown",
	Input:         "input",
	Load:          "load",
	Revealed:      "revealed",
	Intersect:     "intersect",
	SubmitForm:    "submit",
	ChangeDelayed: "change delay:500ms",
	KeyUpDelayed:  "keyup changed delay:300ms",
	InputDelayed:  "input delay:300ms",
}

HTMXTriggers provides constants for common trigger patterns.

Functions

func All added in v0.1.0

func All(items []interface{}, pred Predicate) bool

All returns true if all items match the predicate.

Usage:

allPublished := mi.All(posts, mi.Where("status", "published"))

func Any added in v0.1.0

func Any(items []interface{}, pred Predicate) bool

Any returns true if any item matches the predicate.

Usage:

hasPublished := mi.Any(posts, mi.Where("status", "published"))

func Avg added in v0.1.0

func Avg(items []interface{}, key string) float64

Avg returns the average of an integer field across all items.

Usage:

avgViews := mi.Avg(posts, "views")

func Bool added in v0.1.0

func Bool(m map[string]interface{}, key string) bool

Bool safely extracts a bool from a map. Returns false if key is missing or value is not a boolean.

Usage:

post := map[string]interface{}{"published": true}
mi.Bool(post, "published") // true
mi.Bool(post, "missing")   // false

func Contains added in v0.1.0

func Contains(m map[string]interface{}, key, substr string) bool

Contains checks if a map field (as string) contains a substring. Case-sensitive by default.

Usage:

if mi.Contains(post, "title", "Go") { ... }

func ContainsI added in v0.1.0

func ContainsI(m map[string]interface{}, key, substr string) bool

ContainsI checks if a map field contains a substring (case-insensitive).

Usage:

if mi.ContainsI(post, "title", "go") { ... }

func Count added in v0.1.0

func Count(items []interface{}, pred Predicate) int

Count returns the number of items that match the predicate.

Usage:

publishedCount := mi.Count(posts, mi.Where("status", "published"))

func Eq added in v0.1.0

func Eq(m map[string]interface{}, key, val string) bool

Eq checks if a map field equals a string value.

Usage:

if mi.Eq(post, "status", "published") { ... }

func FilterItems added in v0.1.0

func FilterItems(items []interface{}, pred Predicate) []interface{}

FilterItems returns items from a slice that match the predicate.

Usage:

published := mi.FilterItems(posts, mi.Where("status", "published"))
popular := mi.FilterItems(posts, func(item interface{}) bool {
    p := item.(map[string]interface{})
    return mi.Int(p, "views") > 1000
})

func Find added in v0.1.0

func Find(items []interface{}, pred Predicate) interface{}

Find returns the first item that matches the predicate, or nil if not found.

Usage:

featured := mi.Find(posts, mi.Where("featured", "true"))

func Float added in v0.1.0

func Float(m map[string]interface{}, key string) float64

Float safely extracts a float64 from a map. Returns 0 if key is missing or value cannot be converted to float64.

Usage:

product := map[string]interface{}{"price": 19.99}
mi.Float(product, "price") // 19.99

func GetHTMXCurrentURL

func GetHTMXCurrentURL(r *http.Request) string

GetHTMXCurrentURL returns the current URL of the browser.

func GetHTMXTarget

func GetHTMXTarget(r *http.Request) string

GetHTMXTarget returns the target element ID from HTMX request headers.

func GetHTMXTrigger

func GetHTMXTrigger(r *http.Request) string

GetHTMXTrigger returns the ID of the element that triggered the request.

func GetHTMXTriggerName

func GetHTMXTriggerName(r *http.Request) string

GetHTMXTriggerName returns the name of the event that triggered the request.

func GroupItems added in v0.1.0

func GroupItems(items []interface{}, key string) map[string][]interface{}

GroupItems groups items by a string field value.

Usage:

byStatus := mi.GroupItems(posts, "status")
// map[string][]interface{}{"published": [...], "draft": [...]}

func Gt added in v0.1.0

func Gt(m map[string]interface{}, key string, val int) bool

Gt checks if a map field is greater than an int value.

Usage:

if mi.Gt(post, "likes", 0) { ... }

func Gte added in v0.1.0

func Gte(m map[string]interface{}, key string, val int) bool

Gte checks if a map field is greater than or equal to an int value.

func HTMXHandler

func HTMXHandler(fullPageTemplate H, fragmentTemplate H) http.HandlerFunc

HTMXHandler creates an HTTP handler that automatically handles HTMX vs full page requests.

func HTMXHandlerFunc

func HTMXHandlerFunc(fullPageFn func(*http.Request) H, fragmentFn func(*http.Request) H) http.HandlerFunc

HTMXHandlerFunc creates an HTTP handler from functions that return templates.

func HTMXStopPolling

func HTMXStopPolling(w http.ResponseWriter)

HTMXStopPolling stops HTMX polling by returning 286 status.

func Int added in v0.1.0

func Int(m map[string]interface{}, key string) int

Int safely extracts an int from a map. Returns 0 if key is missing or value cannot be converted to int. Handles int, float64, and string types.

Usage:

post := map[string]interface{}{"views": 42, "rating": 4.5}
mi.Int(post, "views")   // 42
mi.Int(post, "rating")  // 4 (truncated)
mi.Int(post, "missing") // 0

func IsHTMX

func IsHTMX(r *http.Request) bool

IsHTMX checks if the request was made by HTMX.

func IsHTMXBoosted

func IsHTMXBoosted(r *http.Request) bool

IsHTMXBoosted checks if the request was boosted by HTMX.

func Lt added in v0.1.0

func Lt(m map[string]interface{}, key string, val int) bool

Lt checks if a map field is less than an int value.

func Lte added in v0.1.0

func Lte(m map[string]interface{}, key string, val int) bool

Lte checks if a map field is less than or equal to an int value.

func MaxInt added in v0.1.0

func MaxInt(items []interface{}, key string) int

MaxInt returns the maximum value of an integer field.

Usage:

maxViews := mi.MaxInt(posts, "views")

func MinInt added in v0.1.0

func MinInt(items []interface{}, key string) int

MinInt returns the minimum value of an integer field.

Usage:

minViews := mi.MinInt(posts, "views")

func Ne added in v0.1.0

func Ne(m map[string]interface{}, key, val string) bool

Ne checks if a map field does not equal a string value.

Usage:

if mi.Ne(post, "status", "draft") { ... }

func Pluck added in v0.1.0

func Pluck(items []interface{}, key string) []string

Pluck extracts a single field from each item as a slice of strings.

Usage:

titles := mi.Pluck(posts, "title") // []string{"Hello", "World", ...}

func PluckInt added in v0.1.0

func PluckInt(items []interface{}, key string) []int

PluckInt extracts a single integer field from each item.

Usage:

viewCounts := mi.PluckInt(posts, "views") // []int{100, 200, ...}

func Render

func Render(template H, w io.Writer) error

Render renders a template to the provided writer.

func RenderFragment

func RenderFragment(template H, w http.ResponseWriter) error

RenderFragment renders an HTML fragment for HTMX responses.

func RenderFragmentWithTrigger

func RenderFragmentWithTrigger(template H, w http.ResponseWriter, triggerEvents string) error

RenderFragmentWithTrigger renders a fragment and sets trigger events.

func RenderHandler

func RenderHandler(template H) http.HandlerFunc

RenderHandler creates an HTTP handler that renders a Minty template.

func RenderHandlerFunc

func RenderHandlerFunc(fn func(*http.Request) H) http.HandlerFunc

RenderHandlerFunc creates an HTTP handler from a function that returns a template.

func RenderToString

func RenderToString(template H) string

RenderToString renders a template and returns the HTML as a string.

func SanitizeInput

func SanitizeInput(input string) string

SanitizeInput performs basic input sanitization.

func SetHTMXLocation

func SetHTMXLocation(w http.ResponseWriter, url string)

SetHTMXLocation sets the HX-Location response header for client-side redirects.

func SetHTMXPushURL

func SetHTMXPushURL(w http.ResponseWriter, url string)

SetHTMXPushURL sets the HX-Push-Url response header to update browser history.

func SetHTMXRedirect

func SetHTMXRedirect(w http.ResponseWriter, url string)

SetHTMXRedirect sets the HX-Redirect response header for full redirects.

func SetHTMXRefresh

func SetHTMXRefresh(w http.ResponseWriter)

SetHTMXRefresh sets the HX-Refresh response header to refresh the page.

func SetHTMXReplaceURL

func SetHTMXReplaceURL(w http.ResponseWriter, url string)

SetHTMXReplaceURL sets the HX-Replace-Url response header to replace current URL.

func SetHTMXReswap

func SetHTMXReswap(w http.ResponseWriter, strategy string)

SetHTMXReswap sets the HX-Reswap response header to change swap behavior.

func SetHTMXRetarget

func SetHTMXRetarget(w http.ResponseWriter, selector string)

SetHTMXRetarget sets the HX-Retarget response header to change the target.

func SetHTMXTrigger

func SetHTMXTrigger(w http.ResponseWriter, events string)

SetHTMXTrigger sets the HX-Trigger response header to trigger client-side events.

func SetHTMXTriggerAfterSettle

func SetHTMXTriggerAfterSettle(w http.ResponseWriter, events string)

SetHTMXTriggerAfterSettle sets the HX-Trigger-After-Settle response header.

func SetHTMXTriggerAfterSwap

func SetHTMXTriggerAfterSwap(w http.ResponseWriter, events string)

SetHTMXTriggerAfterSwap sets the HX-Trigger-After-Swap response header.

func SortBy added in v0.1.0

func SortBy(items []interface{}, key string, dir SortDir) []interface{}

SortBy returns a new slice sorted by the given field. The original slice is not modified.

Usage:

byDate := mi.SortBy(posts, "date", mi.Desc)
byTitle := mi.SortBy(posts, "title", mi.Asc)

func SortByMulti added in v0.1.0

func SortByMulti(items []interface{}, fields ...SortField) []interface{}

func Str added in v0.1.0

func Str(m map[string]interface{}, key string) string

Str safely extracts a string from a map. Returns empty string if key is missing or value is not a string (falls back to fmt.Sprint for other types).

Usage:

post := map[string]interface{}{"title": "Hello", "views": 42}
mi.Str(post, "title")  // "Hello"
mi.Str(post, "views")  // "42" (converted)
mi.Str(post, "missing") // ""

func Sum added in v0.1.0

func Sum(items []interface{}, key string) int

Sum returns the sum of an integer field across all items.

Usage:

totalViews := mi.Sum(posts, "views")

func SumFloat added in v0.1.0

func SumFloat(items []interface{}, key string) float64

SumFloat returns the sum of a float field across all items.

Usage:

totalRevenue := mi.SumFloat(orders, "amount")

func ToMap added in v0.1.0

func ToMap(v interface{}) map[string]interface{}

ToMap safely converts an interface{} to map[string]interface{}. Returns nil if conversion fails.

Usage:

if m := mi.ToMap(item); m != nil {
    title := mi.Str(m, "title")
}

func ToSlice added in v0.1.0

func ToSlice(v interface{}) []interface{}

ToSlice safely converts an interface{} to []interface{}. Returns nil if conversion fails.

func Truthy added in v0.1.0

func Truthy(v interface{}) bool

Truthy performs a JavaScript-like truthy check on a value. Returns false for: nil, false, 0, 0.0, "", empty slices Returns true for everything else.

Usage:

mi.Truthy(nil)           // false
mi.Truthy("")            // false
mi.Truthy(0)             // false
mi.Truthy("hello")       // true
mi.Truthy(42)            // true
mi.Truthy([]int{1,2,3})  // true

Types

type Attribute

type Attribute interface {
	Apply(*Element)
}

Attribute represents an HTML attribute that can be applied to elements.

func AbbrAttr

func AbbrAttr(value string) Attribute

Abbr creates an abbr attribute.

func Accept

func Accept(value string) Attribute

Accept creates an accept attribute.

func AccessKey

func AccessKey(value string) Attribute

AccessKey creates an accesskey attribute.

func Action

func Action(url string) Attribute

Action creates an action attribute for forms.

func Alt

func Alt(text string) Attribute

Alt creates an alt attribute for images.

func AriaChecked

func AriaChecked(value bool) Attribute

AriaChecked creates an aria-checked attribute.

func AriaDescribedby

func AriaDescribedby(value string) Attribute

AriaDescribedby creates an aria-describedby attribute.

func AriaDisabled

func AriaDisabled(value bool) Attribute

AriaDisabled creates an aria-disabled attribute.

func AriaExpanded

func AriaExpanded(value bool) Attribute

AriaExpanded creates an aria-expanded attribute.

func AriaHidden

func AriaHidden(value bool) Attribute

AriaHidden creates an aria-hidden attribute.

func AriaLabel

func AriaLabel(value string) Attribute

AriaLabel creates an aria-label attribute.

func AriaLabelledby

func AriaLabelledby(value string) Attribute

AriaLabelledby creates an aria-labelledby attribute.

func AriaSelected

func AriaSelected(value bool) Attribute

AriaSelected creates an aria-selected attribute.

func Async

func Async() Attribute

Async creates an async boolean attribute.

func Attr

func Attr(name, value string) Attribute

Attr creates an arbitrary attribute with the given name and value. Use this for attributes not covered by specific helper functions, such as SVG attributes or custom attributes.

func Autocomplete

func Autocomplete(value string) Attribute

Autocomplete creates an autocomplete attribute.

func Autofocus

func Autofocus() Attribute

Autofocus creates an autofocus boolean attribute.

func Autoplay

func Autoplay() Attribute

Autoplay creates an autoplay boolean attribute.

func Charset

func Charset(value string) Attribute

Charset creates a charset attribute.

func Checked

func Checked() Attribute

Checked creates a checked boolean attribute.

func CiteAttr

func CiteAttr(value string) Attribute

Cite creates a cite attribute.

func Class

func Class(value string) Attribute

Class creates a class attribute.

func Cols

func Cols(value int) Attribute

Cols creates a cols attribute for textarea.

func Colspan

func Colspan(value int) Attribute

Colspan creates a colspan attribute.

func Content

func Content(value string) Attribute

Content creates a content attribute.

func ContentEditable

func ContentEditable(value bool) Attribute

ContentEditable creates a contenteditable attribute.

func Controls

func Controls() Attribute

Controls creates a controls boolean attribute.

func Crossorigin

func Crossorigin(value string) Attribute

Crossorigin creates a crossorigin attribute.

func Cx

func Cx(value string) Attribute

Cx creates a cx attribute for SVG circle elements.

func Cy

func Cy(value string) Attribute

Cy creates a cy attribute for SVG circle elements.

func D

func D(value string) Attribute

D creates a d attribute for SVG path elements.

func Data

func Data(name, value string) Attribute

Data creates a data-* attribute.

func DataAttr

func DataAttr(name, value string) Attribute

DataAttr is an alias for Data, creates a data-* attribute.

func Datetime

func Datetime(value string) Attribute

Datetime creates a datetime attribute.

func Defer

func Defer() Attribute

Defer creates a defer boolean attribute.

func Dir

func Dir(value string) Attribute

Dir creates a dir attribute for text direction.

func Disabled

func Disabled() Attribute

Disabled creates a disabled boolean attribute.

func Download

func Download(filename string) Attribute

Download creates a download attribute.

func Enctype

func Enctype(value string) Attribute

Enctype creates an enctype attribute.

func Fill

func Fill(value string) Attribute

Fill creates a fill attribute for SVG elements.

func For

func For(value string) Attribute

For creates a for attribute for labels.

func Form

func Form(value string) Attribute

Form creates a form attribute.

func Formaction

func Formaction(value string) Attribute

Formaction creates a formaction attribute.

func Formenctype

func Formenctype(value string) Attribute

Formenctype creates a formenctype attribute.

func Formmethod

func Formmethod(value string) Attribute

Formmethod creates a formmethod attribute.

func Formnovalidate

func Formnovalidate() Attribute

Formnovalidate creates a formnovalidate boolean attribute.

func Formtarget

func Formtarget(value string) Attribute

Formtarget creates a formtarget attribute.

func Headers

func Headers(value string) Attribute

Headers creates a headers attribute.

func Height

func Height(value interface{}) Attribute

Height creates a height attribute.

func Hidden

func Hidden() Attribute

Hidden creates a hidden boolean attribute.

func High

func High(value float64) Attribute

High creates a high attribute for meter.

func Href

func Href(url string) Attribute

Href creates an href attribute for links.

func Hreflang

func Hreflang(value string) Attribute

Hreflang creates an hreflang attribute.

func HtmxBoost

func HtmxBoost() Attribute

HtmxBoost creates an hx-boost attribute for progressive enhancement.

func HtmxConfirm

func HtmxConfirm(message string) Attribute

HtmxConfirm creates an hx-confirm attribute for confirmation dialogs.

func HtmxDelete

func HtmxDelete(url string) Attribute

HtmxDelete creates an hx-delete attribute for HTMX DELETE requests.

func HtmxExt

func HtmxExt(extensions string) Attribute

HtmxExt creates an hx-ext attribute for HTMX extensions.

func HtmxGet

func HtmxGet(url string) Attribute

HtmxGet creates an hx-get attribute for HTMX GET requests.

func HtmxHeaders

func HtmxHeaders(headers string) Attribute

HtmxHeaders creates an hx-headers attribute for custom headers.

func HtmxInclude

func HtmxInclude(selector string) Attribute

HtmxInclude creates an hx-include attribute to include additional form data.

func HtmxIndicator

func HtmxIndicator(selector string) Attribute

HtmxIndicator creates an hx-indicator attribute to show loading indicators.

func HtmxLoadingClass

func HtmxLoadingClass() Attribute

HtmxLoadingClass creates an htmx-indicator class for loading states.

func HtmxPatch

func HtmxPatch(url string) Attribute

HtmxPatch creates an hx-patch attribute for HTMX PATCH requests.

func HtmxPost

func HtmxPost(url string) Attribute

HtmxPost creates an hx-post attribute for HTMX POST requests.

func HtmxPreserve

func HtmxPreserve() Attribute

HtmxPreserve creates an hx-preserve attribute to preserve elements during swaps.

func HtmxPrompt

func HtmxPrompt(message string) Attribute

HtmxPrompt creates an hx-prompt attribute for user input prompts.

func HtmxPushURL

func HtmxPushURL(url string) Attribute

HtmxPushURL creates an hx-push-url attribute for browser history.

func HtmxPut

func HtmxPut(url string) Attribute

HtmxPut creates an hx-put attribute for HTMX PUT requests.

func HtmxReplaceURL

func HtmxReplaceURL(url string) Attribute

HtmxReplaceURL creates an hx-replace-url attribute to replace current URL.

func HtmxSwap

func HtmxSwap(strategy string) Attribute

HtmxSwap creates an hx-swap attribute to specify how to swap content.

func HtmxSwapOOB

func HtmxSwapOOB(value string) Attribute

HtmxSwapOOB creates an hx-swap-oob attribute for out-of-band swaps.

func HtmxSync

func HtmxSync(value string) Attribute

HtmxSync creates an hx-sync attribute for request synchronization.

func HtmxTarget

func HtmxTarget(selector string) Attribute

HtmxTarget creates an hx-target attribute to specify where to place response.

func HtmxTrigger

func HtmxTrigger(trigger string) Attribute

HtmxTrigger creates an hx-trigger attribute to specify what triggers the request.

func HtmxVals

func HtmxVals(values string) Attribute

HtmxVals creates an hx-vals attribute for additional parameters.

func HttpEquiv

func HttpEquiv(value string) Attribute

HttpEquiv creates an http-equiv attribute.

func HxConfirm

func HxConfirm(message string) Attribute

HxConfirm is an alias for HtmxConfirm

func HxDelete

func HxDelete(url string) Attribute

HxDelete is an alias for HtmxDelete

func HxGet

func HxGet(url string) Attribute

HxGet is an alias for HtmxGet

func HxInclude

func HxInclude(selector string) Attribute

HxInclude is an alias for HtmxInclude

func HxIndicator

func HxIndicator(selector string) Attribute

HxIndicator is an alias for HtmxIndicator

func HxPatch

func HxPatch(url string) Attribute

HxPatch is an alias for HtmxPatch

func HxPost

func HxPost(url string) Attribute

HxPost is an alias for HtmxPost

func HxPut

func HxPut(url string) Attribute

HxPut is an alias for HtmxPut

func HxSwap

func HxSwap(strategy string) Attribute

HxSwap is an alias for HtmxSwap

func HxTarget

func HxTarget(selector string) Attribute

HxTarget is an alias for HtmxTarget

func HxTrigger

func HxTrigger(trigger string) Attribute

HxTrigger is an alias for HtmxTrigger

func HxVals

func HxVals(values string) Attribute

HxVals is an alias for HtmxVals

func ID

func ID(value string) Attribute

ID creates an id attribute.

func Lang

func Lang(value string) Attribute

Lang creates a lang attribute.

func List

func List(value string) Attribute

List creates a list attribute.

func Loop

func Loop() Attribute

Loop creates a loop boolean attribute.

func Low

func Low(value float64) Attribute

Low creates a low attribute for meter.

func Max

func Max(value interface{}) Attribute

Max creates a max attribute.

func MaxLength

func MaxLength(value int) Attribute

MaxLength creates a maxlength attribute.

func Media

func Media(value string) Attribute

Media creates a media attribute.

func Method

func Method(value string) Attribute

Method creates a method attribute for forms.

func Min

func Min(value interface{}) Attribute

Min creates a min attribute.

func MinLength

func MinLength(value int) Attribute

MinLength creates a minlength attribute.

func Multiple

func Multiple() Attribute

Multiple creates a multiple boolean attribute.

func Muted

func Muted() Attribute

Muted creates a muted boolean attribute.

func Name

func Name(value string) Attribute

Name creates a name attribute.

func Novalidate

func Novalidate() Attribute

Novalidate creates a novalidate boolean attribute.

func Open

func Open() Attribute

Open creates an open boolean attribute.

func Optimum

func Optimum(value float64) Attribute

Optimum creates an optimum attribute for meter.

func Pattern

func Pattern(value string) Attribute

Pattern creates a pattern attribute.

func Placeholder

func Placeholder(value string) Attribute

Placeholder creates a placeholder attribute.

func Points

func Points(value string) Attribute

Points creates a points attribute for SVG polygon/polyline elements.

func Poster

func Poster(url string) Attribute

Poster creates a poster attribute for video.

func Preload

func Preload(value string) Attribute

Preload creates a preload attribute.

func R

func R(value string) Attribute

R creates an r attribute for SVG circle elements.

func Readonly

func Readonly() Attribute

Readonly creates a readonly boolean attribute.

func Referrerpolicy

func Referrerpolicy(value string) Attribute

Referrerpolicy creates a referrerpolicy attribute.

func Rel

func Rel(value string) Attribute

Rel creates a rel attribute for link relationships.

func Required

func Required() Attribute

Required creates a required boolean attribute.

func Role

func Role(value string) Attribute

Role creates a role attribute.

func Rows

func Rows(value int) Attribute

Rows creates a rows attribute for textarea.

func Rowspan

func Rowspan(value int) Attribute

Rowspan creates a rowspan attribute.

func Scope

func Scope(value string) Attribute

Scope creates a scope attribute.

func Selected

func Selected() Attribute

Selected creates a selected boolean attribute.

func Size

func Size(value int) Attribute

Size creates a size attribute.

func Sizes

func Sizes(value string) Attribute

Sizes creates a sizes attribute.

func Spellcheck

func Spellcheck(value bool) Attribute

Spellcheck creates a spellcheck attribute.

func Src

func Src(url string) Attribute

Src creates a src attribute for images and media elements.

func Srcset

func Srcset(value string) Attribute

Srcset creates a srcset attribute.

func Step

func Step(value interface{}) Attribute

Step creates a step attribute.

func Stroke

func Stroke(value string) Attribute

Stroke creates a stroke attribute for SVG elements.

func StrokeWidth

func StrokeWidth(value string) Attribute

StrokeWidth creates a stroke-width attribute for SVG elements.

func Style

func Style(value string) Attribute

Style creates a style attribute.

func TabIndex

func TabIndex(value int) Attribute

TabIndex creates a tabindex attribute.

func Target

func Target(value string) Attribute

Target creates a target attribute for links.

func Title

func Title(value string) Attribute

Title creates a title attribute.

func Translate

func Translate(value bool) Attribute

Translate creates a translate attribute.

func Type

func Type(value string) Attribute

Type creates a type attribute for input elements.

func Value

func Value(value string) Attribute

Value creates a value attribute.

func ViewBox

func ViewBox(value string) Attribute

ViewBox creates a viewBox attribute for SVG elements.

func Width

func Width(value interface{}) Attribute

Width creates a width attribute.

type BooleanAttribute

type BooleanAttribute struct {
	Name string
}

BooleanAttribute represents a boolean HTML attribute.

func (BooleanAttribute) Apply

func (ba BooleanAttribute) Apply(element *Element)

Apply adds the boolean attribute to an element.

type Builder

type Builder struct{}

Builder provides methods for creating HTML elements with the Minty pattern.

func (*Builder) A

func (b *Builder) A(args ...interface{}) Node

A creates an <a> element.

func (*Builder) Abbr

func (b *Builder) Abbr(children ...interface{}) Node

Abbr creates an <abbr> element.

func (*Builder) Address

func (b *Builder) Address(children ...interface{}) Node

Address creates an <address> element.

func (*Builder) Area

func (b *Builder) Area(attrs ...Attribute) Node

Area creates an <area> element (self-closing).

func (*Builder) Article

func (b *Builder) Article(children ...interface{}) Node

Article creates an <article> element.

func (*Builder) Aside

func (b *Builder) Aside(children ...interface{}) Node

Aside creates an <aside> element.

func (*Builder) Audio

func (b *Builder) Audio(children ...interface{}) Node

Audio creates an <audio> element.

func (*Builder) B

func (b *Builder) B(children ...interface{}) Node

B creates a <b> element.

func (*Builder) Base

func (b *Builder) Base(attrs ...Attribute) Node

Base creates a <base> element (self-closing).

func (*Builder) Bdi

func (b *Builder) Bdi(children ...interface{}) Node

Bdi creates a <bdi> element.

func (*Builder) Bdo

func (b *Builder) Bdo(children ...interface{}) Node

Bdo creates a <bdo> element.

func (*Builder) Blockquote

func (b *Builder) Blockquote(children ...interface{}) Node

Blockquote creates a <blockquote> element.

func (*Builder) Body

func (b *Builder) Body(children ...interface{}) Node

Body creates a <body> element.

func (*Builder) Br

func (b *Builder) Br() Node

Br creates a <br> element (self-closing).

func (*Builder) Button

func (b *Builder) Button(args ...interface{}) Node

Button creates a <button> element.

func (*Builder) Canvas

func (b *Builder) Canvas(children ...interface{}) Node

Canvas creates a <canvas> element.

func (*Builder) Caption

func (b *Builder) Caption(children ...interface{}) Node

Caption creates a <caption> element.

func (*Builder) Circle

func (b *Builder) Circle(children ...interface{}) Node

Circle creates an SVG <circle> element.

func (*Builder) Cite

func (b *Builder) Cite(children ...interface{}) Node

Cite creates a <cite> element.

func (*Builder) Code

func (b *Builder) Code(children ...interface{}) Node

Code creates a <code> element.

func (*Builder) Col

func (b *Builder) Col(attrs ...Attribute) Node

Col creates a <col> element (self-closing).

func (*Builder) Colgroup

func (b *Builder) Colgroup(children ...interface{}) Node

Colgroup creates a <colgroup> element.

func (*Builder) Data

func (b *Builder) Data(children ...interface{}) Node

Data creates a <data> element.

func (*Builder) Datalist

func (b *Builder) Datalist(children ...interface{}) Node

Datalist creates a <datalist> element.

func (*Builder) Dd

func (b *Builder) Dd(children ...interface{}) Node

Dd creates a <dd> element.

func (*Builder) Defs

func (b *Builder) Defs(children ...interface{}) Node

Defs creates an SVG <defs> element.

func (*Builder) Del

func (b *Builder) Del(children ...interface{}) Node

Del creates a <del> element.

func (*Builder) Details

func (b *Builder) Details(children ...interface{}) Node

Details creates a <details> element.

func (*Builder) Dfn

func (b *Builder) Dfn(children ...interface{}) Node

Dfn creates a <dfn> element.

func (*Builder) Dialog

func (b *Builder) Dialog(children ...interface{}) Node

Dialog creates a <dialog> element.

func (*Builder) Div

func (b *Builder) Div(children ...interface{}) Node

Div creates a <div> element.

func (*Builder) Dl

func (b *Builder) Dl(children ...interface{}) Node

Dl creates a <dl> element.

func (*Builder) Dt

func (b *Builder) Dt(children ...interface{}) Node

Dt creates a <dt> element.

func (*Builder) Em

func (b *Builder) Em(children ...interface{}) Node

Em creates an <em> element.

func (*Builder) Embed

func (b *Builder) Embed(attrs ...Attribute) Node

Embed creates an <embed> element (self-closing).

func (*Builder) Fieldset

func (b *Builder) Fieldset(children ...interface{}) Node

Fieldset creates a <fieldset> element.

func (*Builder) Footer

func (b *Builder) Footer(children ...interface{}) Node

Footer creates a <footer> element.

func (*Builder) Form

func (b *Builder) Form(args ...interface{}) Node

Form creates a <form> element.

func (*Builder) G

func (b *Builder) G(children ...interface{}) Node

G creates an SVG <g> (group) element.

func (*Builder) H1

func (b *Builder) H1(children ...interface{}) Node

H1 creates an <h1> element.

func (*Builder) H2

func (b *Builder) H2(children ...interface{}) Node

H2 creates an <h2> element.

func (*Builder) H3

func (b *Builder) H3(children ...interface{}) Node

H3 creates an <h3> element.

func (*Builder) H4

func (b *Builder) H4(children ...interface{}) Node

H4 creates an <h4> element.

func (*Builder) H5

func (b *Builder) H5(children ...interface{}) Node

H5 creates an <h5> element.

func (*Builder) H6

func (b *Builder) H6(children ...interface{}) Node

H6 creates an <h6> element.

func (*Builder) Head

func (b *Builder) Head(children ...interface{}) Node

Head creates a <head> element.

func (*Builder) Header

func (b *Builder) Header(children ...interface{}) Node

Header creates a <header> element.

func (*Builder) Hgroup

func (b *Builder) Hgroup(children ...interface{}) Node

Hgroup creates an <hgroup> element.

func (*Builder) Hr

func (b *Builder) Hr(attrs ...Attribute) Node

Hr creates an <hr> element (self-closing).

func (*Builder) Html

func (b *Builder) Html(children ...interface{}) Node

Html creates an <html> element.

func (*Builder) I

func (b *Builder) I(children ...interface{}) Node

I creates an <i> element.

func (*Builder) Iframe

func (b *Builder) Iframe(children ...interface{}) Node

Iframe creates an <iframe> element.

func (*Builder) Img

func (b *Builder) Img(attrs ...Attribute) Node

Img creates an <img> element (self-closing).

func (*Builder) Input

func (b *Builder) Input(attrs ...Attribute) Node

Input creates an <input> element (self-closing).

func (*Builder) Ins

func (b *Builder) Ins(children ...interface{}) Node

Ins creates an <ins> element.

func (*Builder) Kbd

func (b *Builder) Kbd(children ...interface{}) Node

Kbd creates a <kbd> element.

func (*Builder) Label

func (b *Builder) Label(args ...interface{}) Node

Label creates a <label> element.

func (*Builder) Legend

func (b *Builder) Legend(children ...interface{}) Node

Legend creates a <legend> element.

func (*Builder) Li

func (b *Builder) Li(children ...interface{}) Node

Li creates an <li> element.

func (*Builder) Line

func (b *Builder) Line(children ...interface{}) Node

Line creates an SVG <line> element.

func (b *Builder) Link(attrs ...Attribute) Node

Link creates a <link> element (self-closing).

func (*Builder) Main

func (b *Builder) Main(children ...interface{}) Node

Main creates a <main> element.

func (*Builder) Map

func (b *Builder) Map(children ...interface{}) Node

Map creates a <map> element.

func (*Builder) Mark

func (b *Builder) Mark(children ...interface{}) Node

Mark creates a <mark> element.

func (*Builder) Math

func (b *Builder) Math(children ...interface{}) Node

Math creates a <math> element.

func (*Builder) Menu

func (b *Builder) Menu(children ...interface{}) Node

Menu creates a <menu> element.

func (*Builder) Meta

func (b *Builder) Meta(attrs ...Attribute) Node

Meta creates a <meta> element (self-closing).

func (*Builder) Meter

func (b *Builder) Meter(children ...interface{}) Node

Meter creates a <meter> element.

func (*Builder) Nav

func (b *Builder) Nav(children ...interface{}) Node

Nav creates a <nav> element.

func (*Builder) Noscript

func (b *Builder) Noscript(children ...interface{}) Node

Noscript creates a <noscript> element.

func (*Builder) Object

func (b *Builder) Object(children ...interface{}) Node

Object creates an <object> element.

func (*Builder) Ol

func (b *Builder) Ol(children ...interface{}) Node

Ol creates an <ol> element.

func (*Builder) Optgroup

func (b *Builder) Optgroup(args ...interface{}) Node

Optgroup creates an <optgroup> element.

func (*Builder) Option

func (b *Builder) Option(args ...interface{}) Node

Option creates an <option> element.

func (*Builder) Output

func (b *Builder) Output(children ...interface{}) Node

Output creates an <output> element.

func (*Builder) P

func (b *Builder) P(children ...interface{}) Node

P creates a <p> element.

func (*Builder) Param

func (b *Builder) Param(attrs ...Attribute) Node

Param creates a <param> element (self-closing).

func (*Builder) Path

func (b *Builder) Path(children ...interface{}) Node

Path creates an SVG <path> element.

func (*Builder) Picture

func (b *Builder) Picture(children ...interface{}) Node

Picture creates a <picture> element.

func (*Builder) Polygon

func (b *Builder) Polygon(children ...interface{}) Node

Polygon creates an SVG <polygon> element.

func (*Builder) Polyline

func (b *Builder) Polyline(children ...interface{}) Node

Polyline creates an SVG <polyline> element.

func (*Builder) Pre

func (b *Builder) Pre(children ...interface{}) Node

Pre creates a <pre> element.

func (*Builder) Progress

func (b *Builder) Progress(children ...interface{}) Node

Progress creates a <progress> element.

func (*Builder) Q

func (b *Builder) Q(children ...interface{}) Node

Q creates a <q> element.

func (*Builder) Rect

func (b *Builder) Rect(children ...interface{}) Node

Rect creates an SVG <rect> element.

func (*Builder) Rp

func (b *Builder) Rp(children ...interface{}) Node

Rp creates an <rp> element.

func (*Builder) Rt

func (b *Builder) Rt(children ...interface{}) Node

Rt creates an <rt> element.

func (*Builder) Ruby

func (b *Builder) Ruby(children ...interface{}) Node

Ruby creates a <ruby> element.

func (*Builder) S

func (b *Builder) S(children ...interface{}) Node

S creates an <s> element.

func (*Builder) Samp

func (b *Builder) Samp(children ...interface{}) Node

Samp creates a <samp> element.

func (*Builder) Script

func (b *Builder) Script(children ...interface{}) Node

Script creates a <script> element.

func (*Builder) Section

func (b *Builder) Section(children ...interface{}) Node

Section creates a <section> element.

func (*Builder) Select

func (b *Builder) Select(args ...interface{}) Node

Select creates a <select> element.

func (*Builder) Slot

func (b *Builder) Slot(children ...interface{}) Node

Slot creates a <slot> element.

func (*Builder) Small

func (b *Builder) Small(children ...interface{}) Node

Small creates a <small> element.

func (*Builder) Source

func (b *Builder) Source(attrs ...Attribute) Node

Source creates a <source> element (self-closing).

func (*Builder) Span

func (b *Builder) Span(children ...interface{}) Node

Span creates a <span> element.

func (*Builder) Strong

func (b *Builder) Strong(children ...interface{}) Node

Strong creates a <strong> element.

func (*Builder) Style

func (b *Builder) Style(children ...interface{}) Node

Style creates a <style> element.

func (*Builder) Sub

func (b *Builder) Sub(children ...interface{}) Node

Sub creates a <sub> element.

func (*Builder) Summary

func (b *Builder) Summary(children ...interface{}) Node

Summary creates a <summary> element.

func (*Builder) Sup

func (b *Builder) Sup(children ...interface{}) Node

Sup creates a <sup> element.

func (*Builder) Svg

func (b *Builder) Svg(children ...interface{}) Node

Svg creates an <svg> element.

func (*Builder) SvgText

func (b *Builder) SvgText(children ...interface{}) Node

SvgText creates an SVG <text> element.

func (*Builder) Table

func (b *Builder) Table(children ...interface{}) Node

Table creates a <table> element.

func (*Builder) Tbody

func (b *Builder) Tbody(children ...interface{}) Node

Tbody creates a <tbody> element.

func (*Builder) Td

func (b *Builder) Td(children ...interface{}) Node

Td creates a <td> element.

func (*Builder) Template

func (b *Builder) Template(children ...interface{}) Node

Template creates a <template> element.

func (*Builder) Text

func (b *Builder) Text(content string) Node

Text creates a text node (for explicit text handling).

func (*Builder) Textarea

func (b *Builder) Textarea(args ...interface{}) Node

Textarea creates a <textarea> element.

func (*Builder) Tfoot

func (b *Builder) Tfoot(children ...interface{}) Node

Tfoot creates a <tfoot> element.

func (*Builder) Th

func (b *Builder) Th(children ...interface{}) Node

Th creates a <th> element.

func (*Builder) Thead

func (b *Builder) Thead(children ...interface{}) Node

Thead creates a <thead> element.

func (*Builder) Time

func (b *Builder) Time(children ...interface{}) Node

Time creates a <time> element.

func (*Builder) Title

func (b *Builder) Title(text string) Node

Title creates a <title> element.

func (*Builder) Tr

func (b *Builder) Tr(children ...interface{}) Node

Tr creates a <tr> element.

func (*Builder) Track

func (b *Builder) Track(attrs ...Attribute) Node

Track creates a <track> element (self-closing).

func (*Builder) U

func (b *Builder) U(children ...interface{}) Node

U creates a <u> element.

func (*Builder) Ul

func (b *Builder) Ul(children ...interface{}) Node

Ul creates a <ul> element.

func (*Builder) Use

func (b *Builder) Use(children ...interface{}) Node

Use creates an SVG <use> element.

func (*Builder) Var

func (b *Builder) Var(children ...interface{}) Node

Var creates a <var> element.

func (*Builder) Video

func (b *Builder) Video(children ...interface{}) Node

Video creates a <video> element.

func (*Builder) Wbr

func (b *Builder) Wbr() Node

Wbr creates a <wbr> element (self-closing).

type DarkMode

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

DarkMode provides framework-agnostic dark mode support for minty applications. It generates the necessary JavaScript for theme detection, persistence, and toggling.

Supported frameworks:

  • Tailwind CSS (class="dark" on html element)
  • Bootstrap 5.3+ (data-bs-theme="dark" attribute)
  • Custom CSS variable schemes (any data-* attribute)

Not supported (by design):

  • MUI, Vuetify, Angular Material (require framework-specific state management)

See DARKMODE.md for architectural rationale.

func DarkModeAttr

func DarkModeAttr(attrName, lightValue, darkValue string, opts ...DarkModeOption) *DarkMode

DarkModeAttr creates a dark mode handler using a custom attribute. Use this for CSS variable schemes that respond to data attributes.

Example for custom CSS:

:root[data-theme="dark"] { --bg: #1a1a1a; --text: #fff; }
:root[data-theme="light"] { --bg: #fff; --text: #1a1a1a; }

darkMode := mi.DarkModeAttr("data-theme", "light", "dark")

func DarkModeBootstrap

func DarkModeBootstrap(opts ...DarkModeOption) *DarkMode

DarkModeBootstrap creates a dark mode handler configured for Bootstrap 5.3+. Bootstrap uses data-bs-theme="dark" attribute on the html element.

func DarkModeTailwind

func DarkModeTailwind(opts ...DarkModeOption) *DarkMode

DarkModeTailwind creates a dark mode handler configured for Tailwind CSS. Tailwind uses class="dark" on the html element.

func NewDarkMode

func NewDarkMode(opts ...DarkModeOption) *DarkMode

NewDarkMode creates a dark mode handler with Tailwind defaults. Use DarkModeTailwind(), DarkModeBootstrap(), or DarkModeAttr() for framework-specific presets.

func (*DarkMode) Script

func (dm *DarkMode) Script(b *Builder) Node

Script generates the JavaScript for dark mode initialisation. Place this in the <head> to prevent flash of wrong theme on page load.

Example:

b.Head(
    b.Script(mi.Raw(`tailwind.config = { darkMode: 'class' }`)),
    darkMode.Script(b),
)

func (*DarkMode) ScriptRaw

func (dm *DarkMode) ScriptRaw() string

ScriptRaw returns the raw JavaScript string without wrapping in a script tag. Useful when combining with other scripts.

func (*DarkMode) Toggle

func (dm *DarkMode) Toggle(b *Builder, attrs ...interface{}) Node

Toggle generates a button element that toggles dark mode. Pass additional attributes to style the button.

Example:

darkMode.Toggle(b,
    mi.Class("p-2 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-700"),
    mi.Attr("title", "Toggle dark mode"),
)

func (*DarkMode) ToggleID

func (dm *DarkMode) ToggleID() string

ToggleID returns the ID of the icon element, useful for custom toggle implementations.

type DarkModeConfig

type DarkModeConfig struct {
	// Toggle mechanism
	UseClass   bool   // true = toggle class, false = toggle attribute
	ClassName  string // Class name to toggle (e.g., "dark")
	AttrName   string // Attribute name (e.g., "data-bs-theme")
	LightValue string // Attribute value for light mode
	DarkValue  string // Attribute value for dark mode

	// Persistence
	StorageKey string // localStorage key, default "theme"
	Default    string // "system", "light", or "dark"

	// UI
	LightIcon string // Icon shown when in light mode (clicking goes dark)
	DarkIcon  string // Icon shown when in dark mode (clicking goes light)
	IconID    string // ID for the icon element

	// Output
	Minify bool // Minify generated JavaScript
}

DarkModeConfig holds configuration for dark mode behaviour.

type DarkModeOption

type DarkModeOption func(*DarkModeConfig)

DarkModeOption configures a DarkMode instance.

func DarkModeDefault

func DarkModeDefault(d string) DarkModeOption

DarkModeDefault sets the default theme when no preference is stored. Valid values: "system" (follows OS preference), "light", "dark"

func DarkModeIconID

func DarkModeIconID(id string) DarkModeOption

DarkModeIconID sets the ID for the icon element inside the toggle button.

func DarkModeIcons

func DarkModeIcons(lightIcon, darkIcon string) DarkModeOption

DarkModeIcons sets the icons for the toggle button. lightIcon is shown when in light mode (clicking switches to dark). darkIcon is shown when in dark mode (clicking switches to light).

func DarkModeMinify

func DarkModeMinify() DarkModeOption

DarkModeMinify enables JavaScript minification.

func DarkModeSVGIcons

func DarkModeSVGIcons() DarkModeOption

DarkModeSVGIcons uses Heroicon SVG icons instead of emoji. This provides better cross-platform consistency.

func DarkModeStorage

func DarkModeStorage(key string) DarkModeOption

DarkModeStorage sets the localStorage key for persistence.

type Element

type Element struct {
	Tag         string
	Attributes  map[string]string
	Children    []Node
	SelfClosing bool
}

Element represents an HTML tag with attributes and children.

func (*Element) Render

func (e *Element) Render(w io.Writer) error

Render outputs the element as HTML.

type FilterOption

type FilterOption struct {
	Value string
	Label string
}

type Fragment

type Fragment struct {
	Children []Node
}

Fragment represents a collection of nodes without a wrapper element.

func (*Fragment) Render

func (f *Fragment) Render(w io.Writer) error

Render outputs all child nodes.

type H

type H func(*Builder) Node

H represents a template function that generates HTML.

func ArticleLayout

func ArticleLayout(title, author string, publishDate string, content H) H

ArticleLayout creates a layout optimized for article content.

func AutoRefresh

func AutoRefresh(url string, interval string) H

AutoRefresh creates an element that automatically refreshes via HTMX.

func BreadcrumbNavigation(links []NavLink) H

BreadcrumbNavigation creates a breadcrumb navigation.

func CardLayout

func CardLayout(title string, content H, actions H) H

CardLayout creates a card-style layout component.

func Component

func Component(className string, content H) H

Component creates a reusable component wrapper.

func Container

func Container(content H) H

Container creates a simple container wrapper.

func Document

func Document(title string, headNodes []Node, body Node) H

Document creates a complete HTML document structure. It takes a title string, head nodes slice, and body node.

func ErrorMessage

func ErrorMessage(message string) H

ErrorMessage creates a styled error message.

func FlexLayout

func FlexLayout(direction, justify, align string, content H) H

FlexLayout creates a flexbox layout container.

func FormField

func FormField(label, name, fieldType, value, errorMsg string, required bool, attributes ...Attribute) H

FormField creates a form field with label, input, and error display.

func FullLayout

func FullLayout(title string, nav, main, aside, footer H) H

FullLayout creates a complete HTML5 layout with semantic structure.

func GridLayout

func GridLayout(columns string, gap string, content H) H

Grid creates a CSS Grid layout container.

func HTMXForm

func HTMXForm(method, action, targetSelector string, children ...interface{}) H

HTMXForm creates a form that submits via HTMX.

func HTMXLoadingIndicator

func HTMXLoadingIndicator(text string) H

HTMXLoadingIndicator creates a loading indicator for HTMX requests.

func HTMXLoadingSpinner

func HTMXLoadingSpinner() H

HTMXLoadingSpinner creates a CSS-based loading spinner.

func If

func If(condition bool, template H) H

If returns the template if the condition is true, otherwise returns an empty fragment.

func IfElse

func IfElse(condition bool, trueTemplate, falseTemplate H) H

IfElse returns the trueTemplate if condition is true, otherwise returns falseTemplate.

func InfiniteScroll

func InfiniteScroll(loadURL, targetSelector string) H

InfiniteScroll creates an element that triggers infinite scroll loading.

func InfoMessage

func InfoMessage(message string) H

InfoMessage creates a styled info message.

func Join

func Join[T any](items []T, renderer func(T) H, separator H) H

Join renders items with a separator between them.

func Layout

func Layout(title string, content H) H

Layout creates a simple HTML page layout with title and content. This is the basic layout pattern for Week 2.

func LayoutWithCSS

func LayoutWithCSS(title string, cssURL string, content H) H

LayoutWithCSS creates a layout with custom CSS styles.

func LayoutWithMeta

func LayoutWithMeta(title, description string, keywords []string, content H) H

LayoutWithMeta creates a layout with custom meta tags.

func LiveSearch

func LiveSearch(searchURL, targetSelector, placeholder string) H

LiveSearch creates a live search input with HTMX.

func Map

func Map[T any](items []T, renderer func(T) H) H

Map transforms a slice of one type to a slice of Nodes using a renderer.

func ModalLayout

func ModalLayout(id, title string, content, actions H) H

ModalLayout creates a modal dialog layout.

func Navigation(links []NavLink) H

Navigation creates a semantic navigation bar.

func Notification

func Notification(message, notificationType string) H

Notification creates a notification that can be dismissed.

func Paginate

func Paginate[T any](items []T, page, perPage int, renderer func([]T, PaginationInfo) H) H

func Partition

func Partition[T any](items []T, predicate func(T) bool, trueRenderer, falseRenderer func([]T) H) H

Partition splits items into two groups based on a predicate.

func ProgressBar

func ProgressBar(progressURL string, targetSelector string) H

ProgressBar creates a progress bar that updates via HTMX.

func SearchWithFilters

func SearchWithFilters(searchURL string, filters []FilterOption) H

SearchWithFilters creates a search interface with filter options.

func SectionLayout

func SectionLayout(heading string, content H) H

Section creates a semantic section with optional heading.

func SelectField

func SelectField(label, name, value, errorMsg string, required bool, options []SelectOption) H

SelectField creates a select field with options.

func SkipLink(href, text string) H

SkipLink creates an accessibility skip link.

func SuccessMessage

func SuccessMessage(message string) H

SuccessMessage creates a styled success message.

func TabContainer

func TabContainer(tabs []Tab, activeTab string) H

func TextareaField

func TextareaField(label, name, value, errorMsg string, required bool, rows, cols int) H

TextareaField creates a textarea field with label and error display.

func Unless

func Unless(condition bool, template H) H

Unless returns the template if the condition is false (opposite of If).

func VisuallyHidden

func VisuallyHidden(content H) H

VisuallyHidden creates content that's hidden visually but available to screen readers.

func WarningMessage

func WarningMessage(message string) H

WarningMessage creates a styled warning message.

func When

func When[T comparable](value T, cases []WhenCase[T], defaultTemplate H) H

When renders the first matching case based on the value.

func WithDefault

func WithDefault[T any](items []T, template H, defaultTemplate H) H

WithDefault returns the template if items is not empty, otherwise returns the default template.

type NavLink struct {
	URL  string
	Text string
}

NavLink represents a navigation link.

type Node

type Node interface {
	Render(w io.Writer) error
}

Node represents any HTML content that can be rendered.

func Chunk

func Chunk[T any](items []T, chunkSize int, renderer func([]T) H) []Node

Chunk renders items in chunks of specified size.

func Each

func Each[T any](items []T, renderer func(T) H) []Node

Each renders a slice of items using the provided renderer function. Returns a slice of Nodes that can be spread into parent elements.

func EachWithIndex

func EachWithIndex[T any](items []T, renderer func(int, T) H) []Node

EachWithIndex renders a slice of items with index using the provided renderer function.

func Filter

func Filter[T any](items []T, predicate func(T) bool, renderer func(T) H) []Node

Filter renders only items that match the predicate condition.

func GroupBy

func GroupBy[T any, K comparable](items []T, keyFn func(T) K, renderer func(K, []T) H) []Node

GroupBy groups items by a key function and renders each group.

func IfTruthy added in v0.1.0

func IfTruthy(v interface{}, then H) Node

IfTruthy renders content only if the value is truthy (JavaScript-like). This is useful for conditionally showing content based on map values without explicit nil/empty checks.

Usage:

mi.IfTruthy(post["category"], func(b *mi.Builder) mi.Node {
    return b.Span(mi.Class("category"), mi.Str(post, "category"))
})

func IfTruthyElse added in v0.1.0

func IfTruthyElse(v interface{}, then, els H) Node

IfTruthyElse renders 'then' if value is truthy, otherwise renders 'els'.

Usage:

mi.IfTruthyElse(user["avatar"],
    func(b *mi.Builder) mi.Node { return b.Img(mi.Src(mi.Str(user, "avatar"))) },
    func(b *mi.Builder) mi.Node { return b.Span("No avatar") },
)

func NewFragment

func NewFragment(nodes ...Node) Node

NewFragment creates a fragment containing the given nodes.

func Range

func Range(start, end int, renderer func(int) H) []Node

Range generates a sequence of numbers and renders each using the renderer.

func Raw

func Raw(content string) Node

Raw creates a node with unescaped HTML content.

func RawHTML

func RawHTML(content string) Node

RawHTML is an alias for Raw, creates unescaped HTML content.

func Repeat

func Repeat(count int, template H) []Node

Repeat renders the same template multiple times.

func Skip

func Skip[T any](items []T, n int, renderer func(T) H) []Node

Skip renders items starting from the nth item.

func Take

func Take[T any](items []T, n int, renderer func(T) H) []Node

Take renders only the first n items from a slice.

func Txt

func Txt(content string) Node

Txt creates a text node (standalone function, alias for b.Text).

type PaginationInfo

type PaginationInfo struct {
	CurrentPage int
	PerPage     int
	TotalItems  int
	TotalPages  int
}

Paginate renders items with pagination support.

type Predicate added in v0.1.0

type Predicate func(interface{}) bool

Predicate is a function that tests if an item matches a condition.

func And added in v0.1.0

func And(predicates ...Predicate) Predicate

And combines multiple predicates with AND logic.

Usage:

result := mi.Filter(posts, mi.And(
    mi.Where("status", "published"),
    mi.WhereGt("views", 100),
))

func Or added in v0.1.0

func Or(predicates ...Predicate) Predicate

Or combines multiple predicates with OR logic.

Usage:

result := mi.Filter(posts, mi.Or(
    mi.Where("status", "published"),
    mi.Where("status", "featured"),
))

func Where added in v0.1.0

func Where(key, val string) Predicate

Where creates a predicate that checks if a map field equals a string value.

Usage:

published := mi.Filter(posts, mi.Where("status", "published"))

func WhereContains added in v0.1.0

func WhereContains(key, substr string) Predicate

WhereContains creates a predicate that checks if a map field contains a substring.

Usage:

goPosts := mi.Filter(posts, mi.WhereContains("title", "Go"))

func WhereContainsI added in v0.1.0

func WhereContainsI(key, substr string) Predicate

WhereContainsI creates a case-insensitive contains predicate.

func WhereGt added in v0.1.0

func WhereGt(key string, val int) Predicate

WhereGt creates a predicate that checks if a map field is > an int value.

Usage:

popular := mi.Filter(posts, mi.WhereGt("views", 1000))

func WhereGte added in v0.1.0

func WhereGte(key string, val int) Predicate

WhereGte creates a predicate that checks if a map field is >= an int value.

func WhereLt added in v0.1.0

func WhereLt(key string, val int) Predicate

WhereLt creates a predicate that checks if a map field is < an int value.

func WhereNot added in v0.1.0

func WhereNot(key, val string) Predicate

WhereNot creates a predicate that checks if a map field does NOT equal a value.

Usage:

notDraft := mi.Filter(posts, mi.WhereNot("status", "draft"))

func WhereTruthy added in v0.1.0

func WhereTruthy(key string) Predicate

WhereTruthy creates a predicate that checks if a map field is truthy.

Usage:

withCategory := mi.Filter(posts, mi.WhereTruthy("category"))

type RawNode

type RawNode struct {
	Content string
}

RawNode represents unescaped HTML content (use with caution).

func (*RawNode) Render

func (r *RawNode) Render(w io.Writer) error

Render outputs unescaped content.

type SelectOption

type SelectOption struct {
	Value string
	Text  string
}

SelectOption represents an option in a select field.

type SortDir added in v0.1.0

type SortDir int

SortDir represents sort direction.

const (
	// Asc sorts in ascending order (A-Z, 0-9, oldest first)
	Asc SortDir = iota
	// Desc sorts in descending order (Z-A, 9-0, newest first)
	Desc
)

type SortField added in v0.1.0

type SortField struct {
	Key string
	Dir SortDir
}

SortByMulti sorts by multiple fields in order of priority. Each field can have its own sort direction.

Usage:

sorted := mi.SortByMulti(posts,
    mi.SortField{"status", mi.Asc},
    mi.SortField{"date", mi.Desc},
)

type StringAttribute

type StringAttribute struct {
	Name  string
	Value string
}

StringAttribute represents an attribute with a string value.

func (StringAttribute) Apply

func (sa StringAttribute) Apply(element *Element)

Apply adds the string attribute to an element.

type Tab

type Tab struct {
	ID    string
	Title string
	URL   string
}

TabContainer creates a tabbed interface with HTMX.

type TextNode

type TextNode struct {
	Content string
}

TextNode represents escaped text content.

func (*TextNode) Render

func (t *TextNode) Render(w io.Writer) error

Render outputs the text with HTML escaping.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a form validation error.

func ValidateEmail

func ValidateEmail(value, fieldName string) *ValidationError

ValidateEmail checks if a value is a valid email format.

func ValidateMaxLength

func ValidateMaxLength(value, fieldName string, maxLen int) *ValidationError

ValidateMaxLength checks maximum length.

func ValidateMinLength

func ValidateMinLength(value, fieldName string, minLen int) *ValidationError

ValidateMinLength checks minimum length.

func ValidateRequired

func ValidateRequired(value, fieldName string) *ValidationError

ValidateRequired checks if a field is not empty.

type ValidationResult

type ValidationResult struct {
	IsValid bool
	Errors  []ValidationError
}

ValidationResult represents the result of form validation.

func (*ValidationResult) AddError

func (vr *ValidationResult) AddError(field, message string)

AddError adds a validation error to the result.

func (*ValidationResult) GetError

func (vr *ValidationResult) GetError(field string) string

GetError returns the first error for a specific field, or empty string if none.

func (*ValidationResult) HasError

func (vr *ValidationResult) HasError(field string) bool

HasError checks if there's an error for a specific field.

type WhenCase

type WhenCase[T comparable] struct {
	Value    T
	Template H
}

When provides multiple condition/template pairs (like a switch statement).

Directories

Path Synopsis
domains
mintycart
Package mintycart provides pure e-commerce domain logic for the Minty System.
Package mintycart provides pure e-commerce domain logic for the Minty System.
mintyfin
Package mintyfin provides pure finance domain logic for the Minty System.
Package mintyfin provides pure finance domain logic for the Minty System.
mintymove
Package mintymove provides pure logistics and movement domain logic for the Minty System.
Package mintymove provides pure logistics and movement domain logic for the Minty System.
Package mintydyn provides dynamic UI components with automatic pattern detection for the Minty HTML generation library.
Package mintydyn provides dynamic UI components with automatic pattern detection for the Minty HTML generation library.
Package mintyex provides UI helper functions for the Minty System.
Package mintyex provides UI helper functions for the Minty System.
Package mintytypes provides pure business types, interfaces, and utilities.
Package mintytypes provides pure business types, interfaces, and utilities.
Package mintyui provides theme-based UI components and utilities for building consistent user interfaces across domains.
Package mintyui provides theme-based UI components and utilities for building consistent user interfaces across domains.
presentation
mintycartui
Package mintycartui provides UI presentation adapters for the mintycart domain.
Package mintycartui provides UI presentation adapters for the mintycart domain.
mintyfinui
Package mintyfinui provides UI presentation adapters for the mintyfin domain.
Package mintyfinui provides UI presentation adapters for the mintyfin domain.
mintymoveui
Package mintymoveui provides UI presentation adapters for the mintymove domain.
Package mintymoveui provides UI presentation adapters for the mintymove domain.
themes
bootstrap
Package bootstrap provides a Bootstrap 5 theme implementation for mintyui
Package bootstrap provides a Bootstrap 5 theme implementation for mintyui
bulma
Package bulma provides a Bulma CSS theme implementation for mintyui
Package bulma provides a Bulma CSS theme implementation for mintyui
material
Package material provides a Material Design theme implementation for mintyui
Package material provides a Material Design theme implementation for mintyui
tailwind
Package tailwind provides a Tailwind CSS theme implementation for mintyui
Package tailwind provides a Tailwind CSS theme implementation for mintyui

Jump to

Keyboard shortcuts

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