ui

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-htmx-ui

Composable Go + templ + Tailwind UI components with embedded styles and optional charts. Designed to work with HTMX, server-rendered pages and application-owned SSE updates.

go get github.com/marcuoli/go-htmx-ui@v0.7.0

Render a widget

import ui "github.com/marcuoli/go-htmx-ui"

templ Summary() {
    @ui.Widget(ui.WidgetProps{}) {
        @ui.WidgetHeader(ui.WidgetHeaderProps{Title: "Requests", Count: "123456"})
        @ui.WidgetMetric("Input tokens", "682888", "Reported usage")
    }
}

Commit your generated templ Go files as usual. Ordinary Go consumers do not need Node or the templ generator.

Serve the assets

mux.Handle("GET /assets/ui/", ui.AssetHandler("/assets/ui/"))
// Render once inside the full page's <head>.
@ui.Head(ui.HeadProps{AssetPrefix: "/assets/ui/", Charts: true})

Use Charts: false (the default) for CSS-only components. Both helpers share the same application-owned prefix; neither registers global routes or inserts HTML into an existing page. Render Head once, outside HTMX/SSE fragments. HeadProps.Nonce optionally applies the application's CSP nonce to the external deferred scripts. JavaScript-only applications can still serve Assets() and list the stylesheet/scripts explicitly as documented in the chart guide.

Choose any asset URL prefix. The library has no router, authentication, database, CDN, font or network transport dependency. Assets include the unmodified official Apache ECharts 6.1.0 full bundle and its required third-party notices.

Components

Widgets, widget headers, metrics, exact/compact values, native ECharts hosts, empty states, data disclosures, page headers, action groups, tabs, buttons, link buttons, labeled fields, inputs, selects, dialog shells/headers/bodies, badges, status indicators with optional pulsing rings, explicit authentication lock/text indicators, and version labels.

See component and integration guide for props, slots, theme tokens, chart lifecycle, accessibility and boundaries. Tables remain in go-htmx-table; compose them inside widgets rather than copying a table implementation.

Route shared component, API, style and asset requests through this module's designated owning development session. Consuming apps retain domain logic and adopt released shared versions rather than maintaining divergent copies.

Showcase

go run ./examples/showcase -listen 127.0.0.1:8099

Open http://127.0.0.1:8099 for synthetic dark/light widgets, forms, a modal, an updating chart and composition with published go-htmx-table v0.2.0. Example page layout and table styling belong to the example.

For the neutral standalone Alpine/HTMX consumer at /alpine, run the showcase with -runtime-assets /external/node_modules pointing to installed development dependencies. The example application serves those official runtimes itself; the library does not bundle them or register Alpine globally. See the component guide for StatusAlpineBindings, live classes/visibility and pulse styles.

The same example supports HTMX 4.0.1 with -htmx4, selecting the development-only official npm alias and loading its hx-alpine-compat extension before Alpine. The chart controller supports both HTMX 2 and 4 lifecycle events. Frameworks are still application-owned; selecting HTMX 4 is a separate application migration, particularly for inherited attributes and event/error handling.

Application metadata uses go-versioning v0.1.1. Pass validated application build information to ui.VersionLabel; the component never probes Git, the working directory or the UI dependency's module version. An unversioned example correctly displays 0.0.0+unknown. Library releases use conventional Go module tags (v0.2.0), separate from consuming applications' date/PR build versions.

Repository layout

go-htmx-ui/
├── *.go, *.templ       # Public ui components and generated Go
├── web/
│   ├── assets/        # Embedded CSS, JavaScript and license notices
│   ├── styles/        # Canonical Tailwind sources
│   ├── scripts/       # Frontend build tooling
│   ├── tests/         # JavaScript contract tests
│   └── package*.json  # Frontend dependency manifest and lockfile
├── examples/showcase/
├── docs/
└── .github/workflows/

The public Go package stays at the module root. ui.Assets() returns the same asset filenames without a repository prefix; v0.6.0 intentionally changes the chart API and runtime filenames. See the migration guide before upgrading. Go tests remain beside their Go source files.

Compatibility

Requires Go 1.27.3 and templ v0.3.1100, with matching generated sources and published go-htmx-table v0.2.0. Upgrade the runtime and regenerate consuming applications together; older generated caller templates may reference APIs removed by templ v0.3.1100. The earlier v0.6.0 release remains unchanged.

The canonical first-party chart controller is ui-htmx-charts.js. Assets() also serves its previous echarts-ui.js name as an alias to the same bytes, so existing native-chart URLs continue working. Load either name once, after the formatter; the official echarts.min.js engine is unchanged.

Development

go tool templ generate
npm --prefix web ci
npm --prefix web run build
npm --prefix web test
go test ./...
go vet ./...
go mod verify

web/styles/components.css is the canonical Tailwind source. web/assets/ui.css is generated without preflight, global body styles or fonts. Component rules use the standard components cascade layer so downstream utilities and custom classes can override them. The build scopes Tailwind fallback initialization and namespaces its internal custom properties. Applications can use the prebuilt CSS or adapt the source into their asset pipeline; preserve those isolation steps. App layout classes stay outside this library.

The latest official Go and frontend releases are checked during dependency reviews. Current direct versions: templ v0.3.1100, go-htmx-table v0.2.0, go-versioning v0.1.1, Tailwind 4.3.4 and ECharts 6.1.0. The generator is pinned as a Go tool. Retain official parse v0.0.0-20250122154542-74294addb73e: the newer v0.0.0-20261027111828-db2689052003 adds Parser.Match, which templ's generator does not implement. Recheck that upstream exception on the next review. ECharts' exact transitive versions and Tailwind's bundled WASI dependencies remain as upstream ships them; no dependency sources or bundles are patched.

Version maintenance

Use the existing go-versioning dependency for conventional module-core policy:

go run ./scripts/module-version -previous v0.6.0 -bump minor -check v0.7.0

The read-only command emits a JSON plan using versioning.ParseCore and Core.Bump; it rejects application date/PR tags and mismatched expected tags. CI checks the pending release plan. Tag creation and publication remain separate authorized release steps; the planner never writes Git refs or publishes.

For first-party development against a local go-versioning checkout, create an external Go workspace containing both repositories and set GOWORK to that workspace file while validating. Keep that workspace outside source; do not commit machine paths or a local replace. Release checks use GOWORK=off and the published dependency. The optional go-versioning inspect command can record explicit source metadata; its date/PR tag allocator belongs to consuming applications and does not replace this library's conventional module tags.

For dependencies outside the checkout, set GO_HTMX_UI_NODE_MODULES to an absolute node_modules directory containing the pinned frontend dependencies. The asset builder resolves sources relative to its own script and uses the OS temporary directory selected by the caller (for example, TEMP/TMPDIR). Use --output-dir /absolute/artifact/directory for retained outputs and optionally --write-source to promote snapshots. With no arguments the builder stages in the configured temporary directory and promotes checked-in assets for normal CI.

MIT license. See third-party notices.

Native ECharts (v0.6.0)

WidgetChartProps.Option accepts a native ECharts object: series, xAxis, yAxis, legend, grid, dataZoom and upstream coordinate systems. There is no labels/datasets browser translation layer. EChartsOption is a Go map, and MarshalEChartsOption serializes it as JSON; EChartsConfig supplies validated unit/date callbacks and lifecycle state separately.

option := ui.EChartsOption{
    "xAxis": map[string]any{"type": "category", "data": []string{"A", "B", "C"}},
    "yAxis": map[string]any{"type": "value"},
    "series": []any{map[string]any{
        "id": "requests", "name": "Requests", "type": "line",
        "data": []any{0, nil, 5},
    }},
}
// In templ: @ui.WidgetChart(ui.WidgetChartProps{ID:"requests", Label:"Requests", Option:option})

The official unmodified echarts.min.js is the only third-party engine asset. First-party echarts-format.js contains display arithmetic; ui-htmx-charts.js handles initialization, native snapshots, reading state, resize, themes and HTMX cleanup. No functions are revived from JSON. Tooltips use ECharts rich text.

This is a breaking pre-1.0 release: upgrade native options, the host markup, script includes and GoHTMXUI.echarts calls together. Older published versions remain unchanged; there is no silent old-schema fallback or compatibility bundle URL in v0.6.0. Consumer upgrades/deployments are separate.

The library owns presentation and lifecycle. Applications retain collection, transport/authentication, history, preferences, aggregation and business logic.

Documentation

Overview

Package ui provides composable templ components, Tailwind styles and optional chart rendering. Applications retain their routes, permissions and live transport.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Actions

func Actions() templ.Component

func AssetHandler added in v0.7.0

func AssetHandler(prefix string) http.Handler

AssetHandler serves the embedded assets below an application-owned URL path. Empty prefix defaults to /assets/ui/; other prefixes are normalized to a local absolute path with a trailing slash, just as in HeadProps. Register the handler at that prefix in the application's router and apply its middleware there. Calling AssetHandler does not register routes or change the default mux.

func Assets

func Assets() fs.FS

Assets serves ui.css, the official echarts.min.js and first-party echarts-format.js/ui-htmx-charts.js without a repository-layout prefix. Serve with http.FileServer and http.StripPrefix at the application-owned URL. The former echarts-ui.js filename remains an alias to the same controller. v0.6.0's retired chart-schema bundle URLs remain unavailable.

func AuthStatus added in v0.7.0

func AuthStatus(props AuthStatusProps) templ.Component

AuthStatus renders a closed lock for confirmed sign-in, an open lock for confirmed sign-out, and a neutral question icon for unknown state. All three fragments remain stable; changing data-auth-state switches icon and text together through CSS. The library never infers state from labels or credentials.

func Badge

func Badge() templ.Component

func Button

func Button(props ButtonProps) templ.Component

func Dialog

func Dialog(props DialogProps) templ.Component

Dialog supplies the native shell; apps explicitly open it and own close/focus behavior, form submission and authorization. No content is moved or fetched here.

func DialogBody

func DialogBody() templ.Component

func DialogHeader

func DialogHeader(props DialogHeaderProps) templ.Component

func Field

func Field(props FieldProps) templ.Component
func Head(props HeadProps) templ.Component

Head emits shared assets once in a full page's head, not in HTMX/SSE fragments. It uses external deferred scripts, leaves CSP policy to the application, and does not insert a page shell, inline code, fonts or global routes.

func Input

func Input(props InputProps) templ.Component

func LinkButton

func LinkButton(props LinkButtonProps) templ.Component

func MarshalEChartsOption added in v0.6.0

func MarshalEChartsOption(option any) (string, error)

MarshalEChartsOption serializes native JSON without generating JavaScript or trusting HTML. Widgets escape the result into an attribute; JS-only clients use JSON.stringify with the same native object. Runtime validation also applies.

func MetricText

func MetricText(value string) string

Format only numeric metric labels. Keep units, unavailable values, small precise costs and partial-coverage qualifiers in their original form.

func PageHeader(props PageHeaderProps) templ.Component

func Select

func Select(props SelectProps) templ.Component

func StatusIndicator added in v0.7.0

func StatusIndicator(props StatusIndicatorProps) templ.Component

StatusIndicator renders a decorative dot and an escaped, visible label. Only the ring animates; the solid core and label remain readable. Connection checks, freshness and transport belong to the caller, which can update data-tone, data-pulse and the label without replacing the component's markup.

func Tab

func Tab(props TabProps) templ.Component

func Tabs

func Tabs(label string) templ.Component

func VersionLabel

func VersionLabel(info versioning.Info) templ.Component

func Widget

func Widget(props WidgetProps) templ.Component

Keep the existing root element, classes and live attributes without adding a wrapper: table scrolling, semantic landmarks and DOM patch identity depend on them.

func WidgetChart

func WidgetChart(props WidgetChartProps) templ.Component

The stable native ECharts host and its fallback remain siblings. Preserve the host and engine-owned children during application DOM patches; call update.

func WidgetData

func WidgetData(label string) templ.Component

func WidgetEmpty

func WidgetEmpty() templ.Component

func WidgetHeader

func WidgetHeader(props WidgetHeaderProps) templ.Component

The children slot holds the view's actions or badges. Counts retain exact tooltips while using the same compact formatter as other numeric widgets.

func WidgetMetric

func WidgetMetric(label, value, note string) templ.Component

func WidgetMetricFrame

func WidgetMetricFrame(props WidgetMetricProps) templ.Component

func WidgetMetricValue

func WidgetMetricValue(value, exact string) templ.Component

Types

type AuthState added in v0.7.0

type AuthState string

AuthState is an application's explicit authentication observation. Unknown includes checking, unavailable or stale observations; failures do not imply AuthSignedOut, and healthy service status does not imply AuthSignedIn.

const (
	AuthUnknown   AuthState = "unknown"
	AuthSignedIn  AuthState = "signed-in"
	AuthSignedOut AuthState = "signed-out"
)

type AuthStatusProps added in v0.7.0

type AuthStatusProps struct {
	State                                       AuthState
	SignedInLabel, SignedOutLabel, UnknownLabel string
	Class, LabelClass                           string
	Attributes                                  templ.Attributes
}

AuthStatusProps configures presentation only. Labels can be localized and are escaped; empty labels use the defaults. Attributes target the stable wrapper, for example an ID, live region or x-bind:data-auth-state expression. The caller must switch State to AuthUnknown when a verified observation becomes stale.

type ButtonKind

type ButtonKind string
const (
	Primary   ButtonKind = "primary"
	Secondary ButtonKind = "secondary"
	Danger    ButtonKind = "danger"
)

type ButtonProps

type ButtonProps struct {
	Type, Class string
	Kind        ButtonKind
	Disabled    bool
	Attributes  templ.Attributes
}

type DialogHeaderProps

type DialogHeaderProps struct{ TitleID, Title, Description string }

type DialogProps

type DialogProps struct {
	ID, TitleID, Class string
	Attributes         templ.Attributes
}

type EChartsBubbleSize added in v0.6.0

type EChartsBubbleSize struct {
	SeriesID    string   `json:"seriesId,omitempty"`
	SeriesIndex *int     `json:"seriesIndex,omitempty"`
	Dimension   int      `json:"dimension"`
	Min         *float64 `json:"min,omitempty"`
	Max         *float64 `json:"max,omitempty"`
}

EChartsBubbleSize supplies the numeric dimension used by the native scatter symbolSize callback. Min/Max are accepted diameter bounds, not inferred weights.

type EChartsConfig added in v0.6.0

type EChartsConfig struct {
	Locale      string                 `json:"locale,omitempty"`
	TimeZone    string                 `json:"timeZone,omitempty"`
	Formats     []EChartsFormatBinding `json:"formats,omitempty"`
	Tooltip     []EChartsTooltip       `json:"tooltip,omitempty"`
	BubbleSizes []EChartsBubbleSize    `json:"bubbleSizes,omitempty"`
	Events      EChartsEvents          `json:"events,omitzero"`
	Messages    EChartsMessages        `json:"messages,omitzero"`
	Empty       bool                   `json:"empty,omitempty"`
	Loading     bool                   `json:"loading,omitempty"`
}

EChartsConfig contains only callbacks JSON cannot encode and shared lifecycle state. Geometry, chart families and data are always native Option fields.

type EChartsConversion added in v0.6.0

type EChartsConversion struct {
	Factor float64 `json:"factor"`
	Offset float64 `json:"offset,omitempty"`
}

type EChartsEvents added in v0.6.0

type EChartsEvents struct {
	Select bool `json:"select,omitempty"`
	Zoom   bool `json:"zoom,omitempty"`
}

type EChartsFormatBinding added in v0.6.0

type EChartsFormatBinding struct {
	Target    string             `json:"target"`
	Format    EChartsValueFormat `json:"format"`
	Dimension *int               `json:"dimension,omitempty"`
	Compact   bool               `json:"compact,omitempty"`
}

EChartsFormatBinding installs a trusted callback only at a documented native formatter target. Dimension selects a vector coordinate; nil means scalar.

type EChartsMessages added in v0.6.0

type EChartsMessages struct {
	Empty       string `json:"empty,omitempty"`
	Error       string `json:"error,omitempty"`
	Unavailable string `json:"unavailable,omitempty"`
	Loading     string `json:"loading,omitempty"`
}

type EChartsOption added in v0.6.0

type EChartsOption map[string]any

EChartsOption is a native ECharts option object. Fields such as series, xAxis, yAxis, legend, grid and dataZoom use the upstream JSON contract directly. It is not a library-specific chart schema. Functions cannot be serialized.

type EChartsTooltip added in v0.6.0

type EChartsTooltip struct {
	SeriesID    string                `json:"seriesId,omitempty"`
	SeriesIndex *int                  `json:"seriesIndex,omitempty"`
	Values      []EChartsTooltipValue `json:"values"`
}

type EChartsTooltipValue added in v0.6.0

type EChartsTooltipValue struct {
	Dimension *int               `json:"dimension,omitempty"`
	Label     string             `json:"label,omitempty"`
	Format    EChartsValueFormat `json:"format"`
}

type EChartsValueFormat added in v0.6.0

type EChartsValueFormat struct {
	Unit        string             `json:"unit,omitempty"`
	Precision   *int               `json:"precision,omitempty"`
	Scale       string             `json:"scale,omitempty"`
	InputUnit   string             `json:"inputUnit,omitempty"`
	DisplayUnit string             `json:"displayUnit,omitempty"`
	Conversion  *EChartsConversion `json:"conversion,omitempty"`
}

EChartsValueFormat describes display-only conversion; samples and bounds stay in their native input units. Unit "time" uses Locale/TimeZone, numeric units use the documented bit/byte/rate/custom conversion rules.

type FieldProps

type FieldProps struct {
	For, Label, Hint, Class string
	Attributes              templ.Attributes
}

type HeadProps added in v0.7.0

type HeadProps struct {
	AssetPrefix string
	Charts      bool
	Nonce       string
}

HeadProps configures a page's shared stylesheet and optional chart scripts. AssetPrefix is the local URL path registered with AssetHandler; empty uses /assets/ui/. Charts includes the engine, formatter and controller in that order. Nonce is an optional application-supplied CSP nonce for external scripts.

type InputProps

type InputProps struct {
	ID, Name, Value, Type, Placeholder, Class string
	Required, Disabled                        bool
	Attributes                                templ.Attributes
}

type LinkButtonProps

type LinkButtonProps struct {
	Href, Class string
	Kind        ButtonKind
	Attributes  templ.Attributes
}

type Option

type Option struct {
	Value, Label string
	Disabled     bool
}

type PageHeaderProps

type PageHeaderProps struct {
	Title, Description, Class string
	Attributes                templ.Attributes
}

Presentation props accept server-defined attributes for HTMX and other callers. Permissions, CSRF fields and event handlers remain the application's responsibility.

type SelectProps

type SelectProps struct {
	ID, Name, Value, Class string
	Options                []Option
	Required, Disabled     bool
	Attributes             templ.Attributes
}

type StatusAlpineBindings added in v0.7.0

type StatusAlpineBindings struct {
	Show, Label, LabelClass, Tone, Pulse string
}

StatusAlpineBindings holds optional, trusted developer-written expressions. The application loads Alpine and owns the state these expressions reference. Empty expressions add no binding. Pulse is converted to a true/false data attribute; LabelClass augments the label's static classes using Alpine rules.

type StatusIndicatorProps added in v0.7.0

type StatusIndicatorProps struct {
	Label, Class    string
	LabelClass      string
	Tone            StatusTone
	Pulse           bool
	PulseStyle      StatusPulseStyle
	Alpine          *StatusAlpineBindings
	Attributes      templ.Attributes
	LabelAttributes templ.Attributes
}

StatusIndicatorProps configures a dot and visible text label. The zero tone and unrecognized tones render neutral; Pulse is opt-in for every tone. Attributes target the wrapper (for IDs, HTMX, live regions or data bindings); LabelAttributes target the text span (for example, Alpine's x-text). Attributes and classes must be server-defined, as with the other controls.

type StatusPulseStyle added in v0.7.0

type StatusPulseStyle string

StatusPulseStyle selects the decorative animation without deciding when it should run. StatusRing is the default; StatusPing expands a filled circle.

const (
	StatusRing StatusPulseStyle = "ring"
	StatusPing StatusPulseStyle = "ping"
)

type StatusTone added in v0.7.0

type StatusTone string

StatusTone selects a status indicator's semantic color, independently of its label and animation. Applications decide which observations warrant each tone.

const (
	StatusNeutral StatusTone = "neutral"
	StatusSuccess StatusTone = "success"
	StatusWarning StatusTone = "warning"
	StatusDanger  StatusTone = "danger"
	StatusInfo    StatusTone = "info"
)

type TabProps

type TabProps struct {
	Label, Href, Class string
	Active             bool
	Attributes         templ.Attributes
}

type WidgetChartProps

type WidgetChartProps struct {
	ID, Label                                string
	Option                                   any
	Config                                   EChartsConfig
	EmptyMessage, ErrorMessage, NoScriptNote string
	Compact                                  bool
}

WidgetChartProps accepts native ECharts options and safe callback/lifecycle metadata. Option may be EChartsOption, a JSON-marshallable struct or RawMessage. v0.6.0 intentionally replaces Spec; older pinned releases retain that API.

type WidgetElement

type WidgetElement uint8

WidgetElement preserves the semantic containers used by existing pages. A closed set prevents callers from constructing arbitrary HTML tag names.

const (
	WidgetSection WidgetElement = iota
	WidgetDiv
	WidgetAside
	WidgetNav
)

type WidgetHeaderProps

type WidgetHeaderProps struct {
	Title, Description, Count           string
	Class, TitleClass, DescriptionClass string
}

type WidgetMetricProps

type WidgetMetricProps struct {
	Label, Note string
	Heading     bool
}

type WidgetProps

type WidgetProps struct {
	Element    WidgetElement
	Class      string
	Attributes templ.Attributes
}

WidgetProps contains presentation and trusted, server-defined attributes. Feature views retain responsibility for permission checks, links and data.

Directories

Path Synopsis
examples
showcase command
scripts
module-version command
Command module-version plans conventional library tags with go-versioning's core policy.
Command module-version plans conventional library tags with go-versioning's core policy.

Jump to

Keyboard shortcuts

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