Documentation
¶
Overview ¶
Package utils provides shared types, Tailwind class merging, and generic helpers used across all templ-components packages.
BaseProps is embedded by every component props struct for consistent ID, Class, Attrs, AriaLabel, and Nonce propagation. Class() merges Tailwind classes with conflict resolution via tailwind-merge-go.
Test rendering utilities: Render, RenderAll, Assert* helpers for component testing.
Index ¶
- Constants
- func AssertContains(t TestReporter, output, want string)
- func AssertContainsAll(t TestReporter, output string, wants ...string)
- func AssertContainsClass(t TestReporter, output string, wants ...string)
- func AssertEqual[T comparable](t TestReporter, context string, got, want T)
- func AssertNotContains(t TestReporter, output, notWant string)
- func Class(classes ...string) string
- func Coalesce[T comparable](values ...T) T
- func ContextWithNonce(ctx context.Context, nonce string) context.Context
- func CurrentYear() string
- func DismissButton(bgClass string, textClass string) templ.Component
- func DismissScript() string
- func EnsureID(prefix, id string) string
- func Lookup[K comparable, V any](m map[K]V, key K, fallback V) V
- func NonceFromContext(ctx context.Context) string
- func Render(t TestReporter, c templ.Component) string
- func RenderAll(t TestReporter, components ...templ.Component) string
- func ResolveNonce(ctx context.Context, explicit string) string
- func ScriptAttrs(nonce string) templ.Attributes
- func ScriptComponent(nonce, script, errLabel string) templ.Component
- func Ternary[T any](condition bool, a, b T) T
- func ValidateID(componentName, id string) error
- type BaseProps
- type ComponentProps
- type Finding
- type TestReporter
Examples ¶
Constants ¶
const ( TransitionFast = "transition-all duration-150 ease-out motion-reduce:transition-none motion-reduce:duration-0" TransitionNormal = "transition-all duration-200 ease-out motion-reduce:transition-none motion-reduce:duration-0" TransitionColors = "transition-colors motion-reduce:transition-none motion-reduce:duration-0" TransitionTransform = "transition-transform motion-reduce:transition-none" )
Motion class constants for consistent animation timing across all packages. Durations follow motion design research guidelines:
- 150ms: micro-interactions (hover, toggle, tooltip)
- 200ms: overlays (modal, drawer, dropdown)
- 300ms: panel transitions, large element movement
Every transition includes motion-reduce fallbacks for vestibular safety. Use these instead of inline strings so timing is consistent and auditable.
const Version = "1.27.0"
Version is the semantic version of the templ-components library. It is the single source of truth for the current release and should be bumped in lockstep with the CHANGELOG and Git tag.
Variables ¶
This section is empty.
Functions ¶
func AssertContains ¶
func AssertContains(t TestReporter, output, want string)
AssertContains checks that the rendered output contains a substring.
func AssertContainsAll ¶
func AssertContainsAll(t TestReporter, output string, wants ...string)
AssertContainsAll checks that the rendered output contains every substring in wants. Reports a single test error per missing substring.
func AssertContainsClass ¶ added in v1.27.0
func AssertContainsClass(t TestReporter, output string, wants ...string)
AssertContainsClass checks that the rendered output contains every want as a WHOLE whitespace- or quote-delimited token. Substring asserts false-positive on class affixes ("p-2" matches "p-24", "ring-1" matches "ring-10"); token membership closes that gap while staying agnostic to tailwind-merge class reordering (each want matches as its own token, never as a slice of an ordered class attribute). Quotes split tokens too, so `class="p-2"` inside HTML attribute syntax matches; a bare substring glued inside a longer token ("p-24") still does not.
func AssertEqual ¶
func AssertEqual[T comparable](t TestReporter, context string, got, want T)
AssertEqual checks that got equals want, reporting a test error with context if not.
func AssertNotContains ¶
func AssertNotContains(t TestReporter, output, notWant string)
AssertNotContains checks that the rendered output does not contain a substring.
func Class ¶
Class merges Tailwind classes intelligently using tailwind-merge-go. Conflicting classes are resolved with later arguments overriding earlier ones. Thread-safe via sync.Mutex to protect the shared LRU cache.
func Coalesce ¶ added in v1.27.0
func Coalesce[T comparable](values ...T) T
Coalesce returns the first argument that is not the zero value for its type, or the zero value when every argument is zero. It is the generic form of the library's override-or-default idiom, the `Ternary(x != "", x, fallback)` shape, and reads in precedence order: Coalesce(props.AriaLabel, props.Label, "Commands").
Note: like Ternary, all arguments are eagerly evaluated.
func ContextWithNonce ¶ added in v1.24.0
ContextWithNonce returns a child context carrying the request-scoped CSP nonce. Call it once in middleware; every context-aware component resolves the nonce from it (see ResolveNonce).
func DismissButton ¶
DismissButton renders the shared alert/notification dismiss control used by feedback.Alert and errorpage.ErrorAlert. The bg/text classes must be passed in because the caller owns the visual style set (feedback.FeedbackType vs errorpage.Family).
The X icon path is shared with the icons package via svg.PathXMark (the single source of truth for the close glyph): utils cannot import icons (leaf-package rule), but both packages already depend on utils/svg. The SVG matches the icons package's stroke template (class, fill, viewBox, stroke-width, stroke, aria-hidden).
Example ¶
package main
import (
"github.com/larsartmann/templ-components/utils"
)
func main() {
_ = utils.DismissButton("bg-gray-100", "text-gray-500")
}
Output:
func DismissScript ¶
func DismissScript() string
DismissScript returns shared JavaScript for dismissing elements via [data-dismiss] click delegation. Used by Alert, Toast, and ErrorAlert components. Handles both role="alert" (Alert) and role="status" (Toast) containers.
func EnsureID ¶
EnsureID returns id if non-empty, otherwise generates a unique ID with the given prefix using crypto/rand for collision safety across HTMX page loads. Format: tc-<prefix>-<16 hex chars> (e.g. tc-modal-a1b2c3d4e5f6a7b8). If crypto/rand fails (extremely unlikely), falls back to an atomic counter + nanosecond timestamp — never raw nanoseconds (predictable under concurrency).
func Lookup ¶
func Lookup[K comparable, V any](m map[K]V, key K, fallback V) V
Lookup returns the map value for key, or fallback if not found. Replaces the repetitive if-ok-return pattern used across all enum lookups.
func NonceFromContext ¶ added in v1.24.0
NonceFromContext returns the request-scoped nonce, or "" when absent — the zero value, never a panic and never a sentinel.
func Render ¶
func Render(t TestReporter, c templ.Component) string
Render renders a templ component to a string for testing.
func RenderAll ¶
func RenderAll(t TestReporter, components ...templ.Component) string
RenderAll renders multiple templ components into a single concatenated string. Useful for integration tests that verify component composition.
func ResolveNonce ¶ added in v1.24.0
ResolveNonce applies the library's context precedence (ADR-0047): explicit props > context > zero value. An explicit prop always wins; context only fills empty; both empty yields "" and the component's omit-empty rendering applies.
func ScriptAttrs ¶ added in v1.21.0
func ScriptAttrs(nonce string) templ.Attributes
ScriptAttrs returns the nonce attribute for an inline <script> (or <style>) tag, or nil when nonce is empty.
Rendering `nonce=""` for an unset nonce silently kills the script on any strict-CSP page (a nonce attribute with the wrong value never matches the CSP header) while non-CSP pages gain nothing from it. Omitting the attribute on empty keeps the script working for non-CSP consumers and changes nothing for strict-CSP ones — an inline script without a valid nonce is blocked there either way. This is the same omit-empty rule the theme scripts and the Datastar live-region busy script follow (issues #7, #9, #24).
func ScriptComponent ¶ added in v1.21.0
ScriptComponent renders a CSP-safe `<script>` tag wrapping the given JS verbatim — THE canonical writer for component singleton scripts. New script-emitting components MUST use it instead of hand-rolling an Fprintf: it owns the omit-empty nonce rule (an empty nonce renders NO nonce attribute, never `nonce=""` — the dead-script class behind the 2026-10-01 demo outage), HTML-escapes the nonce value, and wraps write errors with the caller's errLabel for debugging. A nonce-carrying render is byte-identical to `<script nonce="…">\n<js></script>\n`.
The nonce resolves through the ADR-0047 precedence: an explicit props nonce always wins; a request context fills an empty prop — BOTH context sources, utils.ContextWithNonce middleware AND templ's own templ.WithNonce (the mechanism consumers already wire in templ middleware, and the fallback feedback.Alert shipped before #493); both empty renders NO nonce attribute. Resolution happens per render (inside the ComponentFunc), so one component value is safe across requests with different context nonces.
func Ternary ¶
Ternary returns a if condition is true, otherwise b. Note: both a and b are eagerly evaluated (this is a function, not a macro), so callers passing function calls or side-effecting expressions should use inline if/else in templ instead: { if cond }...{ else }...{ end }.
func ValidateID ¶
ValidateID returns an error if id is empty, using componentName in the message.
Types ¶
type BaseProps ¶
type BaseProps struct {
ID string
Class string
Attrs templ.Attributes
AriaLabel string
Nonce string
}
BaseProps provides common configurable attributes for all components.
func (*BaseProps) GetBaseProps ¶
GetBaseProps returns the embedded BaseProps. This method is promoted to all structs that embed BaseProps, satisfying the ComponentProps interface.
func (*BaseProps) SetBaseProps ¶
SetBaseProps updates the embedded BaseProps. This method is promoted to all structs that embed BaseProps, satisfying the ComponentProps interface.
type ComponentProps ¶
ComponentProps is the interface implemented by all component props structs that embed BaseProps. It enables generic component composition, validation, and wrapper functions across the entire component library.
type Finding ¶ added in v1.24.0
type Finding struct {
// File is the path relative to the directory the caller passed.
File string
// Line is the 1-based line number in the original file.
Line int
// Rule is a stable, machine-readable rule identifier (e.g. "rtl-physical").
Rule string
// Message is a human-readable description with the fix hint.
Message string
// Snippet is the trimmed offending source line.
Snippet string
}
Finding is a single compliance-scanner violation located in a source file. The scanners behind the repo's guard tests share this model so the same scan logic can run inside `go test` (repo guards) and inside the `tc lint` CLI (consumer adoption).
func ScanDarkMode ¶ added in v1.24.0
ScanDarkMode walks dir recursively and reports color classes without a dark: variant on the same line, in .templ and .go component sources (generated *_templ.go and *_test.go files are excluded). Two rules are reported: "darkmode-neutral" (grays/white) and "darkmode-semantic" (blue/red/green/amber/orange).
It is the engine behind TestDarkModeCompliance + TestDarkModeSemanticColors (repo guards) and `tc lint --dark`. The library's documented same-in-both- mode exceptions are built in; consumers suppress their own exceptions with the per-line `tc-lint:ignore` allowlist. Findings use dir-relative paths.
func ScanIconPaths ¶ added in v1.24.0
ScanIconPaths reports inlined SVG `d="M..."` path literals in the DIRECT .templ and .go children of dir (generated *_templ.go and *_test.go files excluded, canonical definitions exempt). The single-source rule: stroke and fill glyphs come from the icons package (icons.Icon for markup, icons.IconPathData for JS injection); paths needed across module boundaries live as shared constants in utils/svg.
It is the engine behind TestInlineIconPathCompliance (repo guard) and `tc lint --icons`. Findings use dir-relative paths.
func ScanMotionReduce ¶ added in v1.24.0
ScanMotionReduce walks dir recursively and reports transition/animation classes in .templ files that lack a motion-reduce fallback — the accessibility safety net for users with reduced-motion enabled. HTML comments are blanked before scanning, so prose never trips the class regexes.
It is the engine behind TestMotionReduceCompliance (repo guard) and `tc lint --motion`. Findings use dir-relative paths.
func ScanRTL ¶ added in v1.24.0
ScanRTL walks dir recursively and reports RTL logical-property violations in .templ files: physical directional classes (ml-/mr-/pl-/pr-/text-left/ text-right/border-l-/border-r-) and the deprecated inset aliases (start-*/end-*). Logical properties automatically mirror in RTL (dir="rtl") without code changes; physical properties do not and cause broken RTL layouts. HTML comments are blanked before scanning, so prose never trips the class regexes.
It is the engine behind TestRTLLogicalProperties (repo guard) and `tc lint --rtl` (consumer adoption). Findings use dir-relative paths and are returned in walk order.
type TestReporter ¶ added in v1.18.1
type TestReporter interface {
Helper()
Fatalf(format string, args ...any)
Errorf(format string, args ...any)
}
TestReporter is the subset of *testing.T the render helpers use. *testing.T satisfies it. The interface exists so this PRODUCTION package never imports testing: importing testing here linked the Go test framework (testing.init et al.) into every consumer binary that pulls utils (found in dnsblockd via `go tool nm`, 2026-09-19). Test-only helpers stay importable from _test.go files with zero changes while the production import graph stays test-free.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cdn provides shared CDN URL helpers for runtime libraries (HTMX, Datastar, etc.).
|
Package cdn provides shared CDN URL helpers for runtime libraries (HTMX, Datastar, etc.). |
|
Package format provides display-formatting helpers for dashboards, tables, and detail views: byte counts, durations, percentages, compact counts, and the empty-value placeholder.
|
Package format provides display-formatting helpers for dashboards, tables, and detail views: byte counts, durations, percentages, compact counts, and the empty-value placeholder. |
|
Package golden provides golden file comparison for snapshot tests.
|
Package golden provides golden file comparison for snapshot tests. |
|
Package svg provides shared SVG rendering primitives and path constants used across multiple component packages (display, feedback, icons).
|
Package svg provides shared SVG rendering primitives and path constants used across multiple component packages (display, feedback, icons). |
|
Package tone is the library's canonical color language: one Tone axis ("why is this thing colored"), one Hue axis ("which hue family"), and the two tables that map them to complete Tailwind class literals.
|
Package tone is the library's canonical color language: one Tone axis ("why is this thing colored"), one Hue axis ("which hue family"), and the two tables that map them to complete Tailwind class literals. |
|
Package wire is the transport-agnostic wiring contract shared by the HTMX and Datastar integrations.
|
Package wire is the transport-agnostic wiring contract shared by the HTMX and Datastar integrations. |