api

package
v1.21.23 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2026 License: Apache-2.0 Imports: 43 Imported by: 58

Documentation

Overview

Package api provides fluent builders for creating styled Text objects. TextBuilder and StyleBuilder use the builder pattern to construct rich text with Tailwind CSS-compatible styling for consistent formatting across output types.

Index

Constants

View Source
const (
	FieldTypeString   = "string"
	FieldTypeInt      = "int"
	FieldTypeFloat    = "float"
	FieldTypeBoolean  = "boolean"
	FieldTypeDate     = "date"
	FieldTypeDuration = "duration"
	FieldTypeArray    = "array"
	FieldTypeMap      = "map"
	FieldTypeStruct   = "struct"
	FieldTypeBytes    = "bytes"
)

Field type constants

View Source
const (
	FormatTable    = "table"
	FormatTree     = "tree"
	FormatCurrency = "currency"
	FormatHide     = "hide"
	FormatList     = "list"
	FormatDate     = "date"
	FormatFloat    = "float"
	FormatMarkdown = "markdown"
	FormatJSON     = "json"
	FormatYAML     = "yaml"
	FormatCSV      = "csv"
	FormatHTML     = "html"
	FormatPDF      = "pdf"
	FormatPretty   = "pretty"
)

Format constants

View Source
const (
	EmptyValue     = "(empty)"
	DateTimeFormat = "2006-01-02 15:04:05"
	DateFormat     = "2006-01-02"
	TimeFormat     = "15:04:05"
	RFC3339Format  = "2006-01-02T15:04:05Z07:00"
	ISO8601Format  = "2006-01-02T15:04:05Z"
	AltDateFormat1 = "01/02/2006"
	AltDateFormat2 = "02/01/2006"
	AltDateFormat3 = "2006/01/02"
	UnixDateFormat = "Mon Jan _2 15:04:05 MST 2006"
	KitchenFormat  = "3:04PM"
)

Common strings

View Source
const (
	ColorGreen = "green"
	ColorRed   = "red"
	ColorBlue  = "blue"
)

Color constants

View Source
const (
	SortAsc  = "asc"
	SortDesc = "desc"
)

Sort direction constants

View Source
const (
	// 1 point = 25.4/72 mm (exact: 1/72 inch = 25.4mm/72)
	PointsToMM = 25.4 / 72.0
	// 1 mm = 72/25.4 points (exact reciprocal)
	MMToPoints = 72.0 / 25.4
)

Unit conversion constants

Variables

View Source
var B = M * K
View Source
var BR = HtmlElement{
	Tag: "br",
	Attributes: map[string]string{
		"class": "clicky",
	},
	Content:  "",
	Fallback: Text{Content: "\n"},
}
View Source
var HR = HtmlElement{
	Tag:      "hr",
	Content:  "",
	Fallback: Text{Content: "\n--------------------------\n"},
}
View Source
var K = int64(1000)
View Source
var M = K * K
View Source
var NBSP = HtmlElement{
	Tag:      "",
	Content:  " ",
	Fallback: Text{Content: " "},
}
View Source
var RenderFuncRegistry = map[string]RenderFunc{}

RenderFuncRegistry stores named custom render functions

View Source
var TAB = HtmlElement{
	Tag:      "",
	Content:  "  ",
	Fallback: Text{Content: "  "},
}

Functions

func Clz

func Clz(v bool, clz string, elseClz ...string) string

func ExtractOrderValue

func ExtractOrderValue(style string) int

ExtractOrderValue extracts the Tailwind order-X class value from a style string. Returns 0 for columns without order-X (they appear first). Supports order-1 through order-12 (standard Tailwind range).

func GetChromaCSS

func GetChromaCSS() string

GetChromaCSS returns the CSS stylesheet for chroma syntax highlighting with line wrapping support. This should be included in HTML documents that use Code.HTML() output.

func GetDiffCSS

func GetDiffCSS() string

GetDiffCSS returns a small starter stylesheet matching the class names emitted by Diff.HTML. Include alongside GetChromaCSS in HTML pages.

func GetTerminalLines

func GetTerminalLines() int

func GetTerminalWidth

func GetTerminalWidth() int

func InferValueType

func InferValueType(value interface{}) string

InferValueType determines the appropriate field type for a given value using reflection and type assertions, returning standard type constants.

func IsEmpty

func IsEmpty(v any) bool

IsEmpty checks if a value is considered empty. It accepts any type: nil, common Go types get fast-path checks, and everything else falls back to reflection.

func ParseEpoch

func ParseEpoch(e any) *time.Time

func PrettifyFieldName

func PrettifyFieldName(name string) string

PrettifyFieldName converts field names to readable format

func RegisterRenderFunc

func RegisterRenderFunc(name string, fn RenderFunc)

RegisterRenderFunc adds a named custom render function to the global registry. These functions can be referenced in field configurations for specialized formatting.

func RenderTreeHTML

func RenderTreeHTML(tree *TextTree, interactive bool) string

RenderTreeHTML renders a TextTree as interactive HTML This is the main entry point for HTML tree rendering

func SafeDerefPointer

func SafeDerefPointer(val reflect.Value) (reflect.Value, bool)

SafeDerefPointer safely dereferences a pointer value, returning the dereferenced value and whether it was nil.

func SetTerminalLines

func SetTerminalLines(height int)

func SplitCamelCase

func SplitCamelCase(s string) []string

SplitCamelCase splits camelCase strings into words

Types

type Admonition

type Admonition struct {
	Severity Severity
	Title    Textable
	Body     Textable
}

Admonition is a callout block (`!!! <severity> <title>`) with an indented body. Title and Body are each a single Textable; Title may be nil (header shows the severity word only) and Body may be nil (header only).

func (Admonition) ANSI

func (a Admonition) ANSI() string

func (Admonition) HTML

func (a Admonition) HTML() string

func (Admonition) Markdown

func (a Admonition) Markdown() string

func (Admonition) String

func (a Admonition) String() string

type Borders

type Borders struct {
	Left   Line
	Right  Line
	Top    Line
	Bottom Line
}

type Box

type Box struct {
	Rectangle
	Fill    Color
	Border  Borders
	Padding Padding
}

Box represents a styled rectangular container with fill, borders, and padding.

type Button

type Button struct {
	Label   string
	Href    string
	ID      string
	Payload string
	Variant string
}

Button represents a platform-agnostic clickable action across output formats.

func (Button) ANSI

func (b Button) ANSI() string

func (Button) HTML

func (b Button) HTML() string

func (Button) Markdown

func (b Button) Markdown() string

func (Button) String

func (b Button) String() string

type ButtonGroup

type ButtonGroup struct {
	Buttons []Button
}

ButtonGroup represents a set of buttons rendered together.

func (ButtonGroup) ANSI

func (a ButtonGroup) ANSI() string

func (ButtonGroup) HTML

func (a ButtonGroup) HTML() string

func (ButtonGroup) Markdown

func (a ButtonGroup) Markdown() string

func (ButtonGroup) String

func (a ButtonGroup) String() string

type Circle

type Circle struct {
	Color    Color
	Border   Line
	Diameter float64
}

type Class

type Class struct {
	Name       string
	Background *Color
	Foreground *Color
	Font       *Font
	Padding    *Padding
	Border     *Borders
}

Class groups styling properties that can be applied to text elements, similar to CSS classes but with structured property access.

func ResolveStyles

func ResolveStyles(styles ...string) Class

type Code

type Code struct {
	Content  string `json:"content,omitempty"`  // The source code content
	Language string `json:"language,omitempty"` // Language identifier (sql, java, javascript, go, xml, xslt, conf, etc.)
	Style    string `json:"style,omitempty"`    // Optional Tailwind CSS styling for wrapper (HTML only)
}

Code represents source code that can be syntax-highlighted across multiple output formats (ANSI terminal, HTML, Markdown).

func CodeBlock

func CodeBlock(language, content string, styles ...string) Code

func NewCode

func NewCode(content, language string) Code

NewCode creates a new Code instance with the given content and language. If language is empty, it will attempt to detect it from common patterns.

func (Code) ANSI

func (c Code) ANSI() string

ANSI returns the source code with ANSI color codes for terminal display. Uses chroma with a terminal-compatible formatter.

func (Code) HTML

func (c Code) HTML() string

HTML returns the source code as syntax-highlighted HTML. The output includes inline styles and proper HTML escaping.

func (Code) Markdown

func (c Code) Markdown() string

Markdown returns the source code as a Markdown code block with language tag.

func (Code) String

func (c Code) String() string

String returns the plain source code without any syntax highlighting.

func (Code) Trim

func (c Code) Trim() Code

type Collapsed

type Collapsed struct {
	Label   string   // Button label text
	Content Textable // Content to show/hide
	Style   string   // Tailwind CSS classes for button styling
	Icon    *icons.Icon
	// CollapseANSI keeps the block collapsed in terminal output: ANSI renders a
	// label-only "▶ <label>" header and hides the content (which terminals
	// cannot toggle), while HTML/Markdown stay interactively expandable. Use it
	// for bulky-but-secondary content (e.g. a raw-JSON dump) that should not
	// flood a failure trace on the console but must remain in the report/web.
	CollapseANSI bool
}

Collapsed represents a collapsible section with a clickable button to toggle visibility. In HTML output, it uses Alpine.js collapse plugin for smooth animations. For other formats (ANSI, Markdown, plain text), it provides appropriate fallbacks.

func (Collapsed) ANSI

func (c Collapsed) ANSI() string

ANSI returns the content directly without the collapsed wrapper, since terminals don't support interactive expand/collapse. When CollapseANSI is set, the content is hidden and only a "▶ <label>" header is shown, keeping bulky secondary content out of the terminal while leaving it expandable in HTML.

func (Collapsed) HTML

func (c Collapsed) HTML() string

HTML returns HTML with Alpine.js collapse functionality

func (Collapsed) Markdown

func (c Collapsed) Markdown() string

Markdown returns Markdown with HTML details/summary fallback

func (Collapsed) MarkdownSlack

func (c Collapsed) MarkdownSlack() string

func (Collapsed) String

func (c Collapsed) String() string

String returns plain text representation with label and content

type Color

type Color struct {
	Hex     string
	Opacity float64
}

Color represents a color with hex value and optional transparency.

type ColumnBuilder

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

ColumnBuilder provides a fluent API for constructing ColumnDef instances.

func Column

func Column(name string) *ColumnBuilder

Column creates a new column builder with the given field name.

func (*ColumnBuilder) Build

func (b *ColumnBuilder) Build() ColumnDef

Build returns the constructed ColumnDef.

func (*ColumnBuilder) Format

func (b *ColumnBuilder) Format(format string) *ColumnBuilder

Format sets the format type (currency, date, bytes, etc.).

func (*ColumnBuilder) FormatOption

func (b *ColumnBuilder) FormatOption(key, value string) *ColumnBuilder

FormatOption adds a single format option key-value pair.

func (*ColumnBuilder) HeaderStyle

func (b *ColumnBuilder) HeaderStyle(style string) *ColumnBuilder

HeaderStyle sets the Tailwind CSS classes for the column header.

func (*ColumnBuilder) Hidden

func (b *ColumnBuilder) Hidden() *ColumnBuilder

Hidden marks the column as hidden from display.

func (*ColumnBuilder) Label

func (b *ColumnBuilder) Label(label string) *ColumnBuilder

Label sets the display label for the column header.

func (*ColumnBuilder) MaxWidth

func (b *ColumnBuilder) MaxWidth(width int) *ColumnBuilder

MaxWidth sets the maximum display width in characters.

func (*ColumnBuilder) Style

func (b *ColumnBuilder) Style(style string) *ColumnBuilder

Style sets the Tailwind CSS classes for cell content.

func (*ColumnBuilder) Type

func (b *ColumnBuilder) Type(typ string) *ColumnBuilder

Type sets the data type hint (string, int, float, date, etc.).

type ColumnDef

type ColumnDef struct {
	Name          string
	Label         string
	Style         string
	HeaderStyle   string
	Type          string
	Format        string
	FormatOptions map[string]string
	MaxWidth      int
	Hidden        bool
}

ColumnDef defines a table column's schema and display properties. Order is determined by array position when returned from TableProvider.Columns().

func (ColumnDef) DisplayLabel

func (c ColumnDef) DisplayLabel() string

DisplayLabel returns Label if set, otherwise prettifies Name.

type Comment

type Comment string

func (Comment) ANSI

func (c Comment) ANSI() string

func (Comment) HTML

func (c Comment) HTML() string

func (Comment) Markdown

func (c Comment) Markdown() string

func (Comment) String

func (c Comment) String() string

type CompactListNode

type CompactListNode struct {
	Label    string                 `json:"label" yaml:"label"`
	Icon     string                 `json:"icon,omitempty" yaml:"icon,omitempty"`
	Style    string                 `json:"style,omitempty" yaml:"style,omitempty"`
	Items    []string               `json:"items" yaml:"items"`
	Metadata map[string]interface{} `json:"metadata,omitempty" yaml:"metadata,omitempty"`
}

CompactListNode renders multiple items inline rather than as nested children, useful for displaying arrays or lists within tree structures.

func (*CompactListNode) GetChildren

func (n *CompactListNode) GetChildren() []TreeNode

func (*CompactListNode) GetItems

func (n *CompactListNode) GetItems() []string

func (*CompactListNode) Pretty

func (n *CompactListNode) Pretty() Text

type ConcreteBranchNode

type ConcreteBranchNode struct {
	Children []TreeNode `json:"children,omitempty"`
}

func (*ConcreteBranchNode) GetChildren

func (c *ConcreteBranchNode) GetChildren() []TreeNode

func (*ConcreteBranchNode) Pretty

func (c *ConcreteBranchNode) Pretty() Text

type ConcreteTreeNode

type ConcreteTreeNode struct {
	Node Pretty
}

func (*ConcreteTreeNode) GetChildren

func (c *ConcreteTreeNode) GetChildren() []TreeNode

func (*ConcreteTreeNode) Pretty

func (c *ConcreteTreeNode) Pretty() Text

type DescriptionList

type DescriptionList struct {
	Items []KeyValuePair
	Style string // "compact" (default) or "badge"
}

DescriptionList represents a collection of key-value pairs rendered as an HTML description list. It supports two styles: "compact" (default, inline flex layout) and "badge" (pill-shaped badges).

func Map

func Map[T any](m map[string]T, styles ...string) DescriptionList

func (DescriptionList) ANSI

func (dl DescriptionList) ANSI() string

func (DescriptionList) HTML

func (dl DescriptionList) HTML() string

func (DescriptionList) Markdown

func (dl DescriptionList) Markdown() string

func (DescriptionList) MarkdownSlack

func (dl DescriptionList) MarkdownSlack() string

func (DescriptionList) String

func (dl DescriptionList) String() string

type DetailLevel

type DetailLevel int

DetailLevel controls how much of an entity's content Details renders. Higher levels produce richer output; callers pick the level based on verbosity flags or request query params.

const (
	// DetailSummary is the one-line identity view, equivalent to Pretty().
	DetailSummary DetailLevel = iota
	// DetailStandard is the default detail-page view: headline fields,
	// labels, tags, properties, locations, metadata — but no heavy bodies.
	DetailStandard
	// DetailFull includes everything, including raw config bodies and
	// other potentially large sections.
	DetailFull
)

type DetailProvider

type DetailProvider interface {
	RowDetail() Textable
}

DetailProvider is an optional interface for TableProvider types that supply expandable detail content per row. Return nil to indicate no detail.

type Detailable

type Detailable interface {
	Details(ctx context.Context, level DetailLevel) Textable
}

Detailable is implemented by types that render a multi-section detail view. The ctx carries DB / HTTP handles for lazy lookups (joined tables, counts); implementations type-assert it to their richer context type (e.g. duty/context.Context) and degrade gracefully when the assertion fails.

type Diff

type Diff struct {
	Before    string `json:"before,omitempty"`
	After     string `json:"after,omitempty"`
	FromLabel string `json:"from_label,omitempty"`
	ToLabel   string `json:"to_label,omitempty"`
	Context   int    `json:"context,omitempty"`
}

Diff renders a unified diff between two strings across the standard output formats (plain, ANSI, HTML, Markdown). Empty Before/After are allowed; identical inputs render to nothing.

func NewDiff

func NewDiff(before, after, fromLabel, toLabel string) Diff

NewDiff builds a Diff with sensible defaults (3 lines of context).

func (Diff) ANSI

func (d Diff) ANSI() string

ANSI returns the unified diff with terminal colors. Honors fatih/color's NoColor (NO_COLOR env, non-tty stdout, --no-color flag).

func (Diff) HTML

func (d Diff) HTML() string

HTML wraps the unified diff in a <pre> block with per-line span classes (diff-add / diff-remove / diff-hunk / diff-meta). Callers supply their own CSS — see GetDiffCSS for a starter palette.

func (Diff) IsEmpty

func (d Diff) IsEmpty() bool

IsEmpty is true when Before and After are byte-identical.

func (Diff) Markdown

func (d Diff) Markdown() string

Markdown returns the unified diff inside a ```diff fenced code block.

func (Diff) String

func (d Diff) String() string

String returns the plain unified diff (no color).

func (Diff) Unified

func (d Diff) Unified() string

Unified returns the raw unified diff with no color. Empty when IsEmpty.

type FieldMeta

type FieldMeta struct {
	Name         string
	CompactItems bool
	Short        bool
	Format       string
}

FieldMeta contains metadata about a field for rendering purposes

type FieldValue

type FieldValue struct {
	Field        PrettyField
	Value        interface{} // Can be *PrettyData for nested structures
	StringValue  *string
	IntValue     *int64
	FloatValue   *float64
	BooleanValue *bool
	TimeValue    *time.Time
	ArrayValue   []interface{}
	MapValue     map[string]interface{}
	Text         Textable
	Tree         TreeNode
}

FieldValue wraps a raw value with type-safe accessors and formatting metadata. It provides strongly-typed access to primitive values (string, int, float, bool, time) while maintaining the original value and supporting rich text output.

func (FieldValue) Color

func (v FieldValue) Color() string

Color determines the display color by matching the field value against ColorOptions patterns, supporting exact matches and numeric comparisons.

func (FieldValue) DateTimeFormat

func (v FieldValue) DateTimeFormat() string

func (FieldValue) Float

func (v FieldValue) Float() *float64

func (FieldValue) GetFieldType

func (v FieldValue) GetFieldType() string

GetFieldType returns the type of the field

func (FieldValue) Int

func (v FieldValue) Int() *int64

func (FieldValue) IsTableField

func (v FieldValue) IsTableField() bool

IsTableField returns true if this field represents a table

func (FieldValue) IsTreeField

func (v FieldValue) IsTreeField() bool

func (FieldValue) Primitive

func (v FieldValue) Primitive() interface{}

Primitive extracts the underlying typed value, returning the most specific type available (string, int64, float64, bool, time.Time) or the raw value.

func (FieldValue) Time

func (v FieldValue) Time() *time.Time

type Font

type Font struct {
	Name          string
	Weight        string
	Size          float64
	Background    Color
	Foreground    Color
	Bold          bool
	Faint         bool
	Italic        bool
	Underline     bool
	Strikethrough bool
}

Font contains typography styling information including weight, size, colors, and text decorations.

type FormatManager

type FormatManager interface {
	ToPrettyData(data interface{}) (*PrettyData, error)
	Pretty(data interface{}) (string, error)
	JSON(data interface{}) (string, error)
	YAML(data interface{}) (string, error)
	CSV(data interface{}) (string, error)
	Markdown(data interface{}) (string, error)
	HTML(data interface{}) (string, error)
}

FormatManager defines the interface for converting data to various output formats. Implementations handle the complete pipeline from raw data to formatted output across multiple formats (JSON, YAML, CSV, Markdown, HTML, etc.).

type HtmlElement

type HtmlElement struct {
	Tag        string
	Attributes map[string]string
	Content    string
	Fallback   Textable
}

func (HtmlElement) ANSI

func (e HtmlElement) ANSI() string

func (HtmlElement) HTML

func (e HtmlElement) HTML() string

func (HtmlElement) Markdown

func (e HtmlElement) Markdown() string

func (HtmlElement) MarkdownSlack

func (e HtmlElement) MarkdownSlack() string

func (HtmlElement) String

func (e HtmlElement) String() string

type KeyValuePair

type KeyValuePair struct {
	Key   string
	Value any
	Style string // "compact" (default) or "badge"
}

KeyValuePair represents a single key-value pair that can be rendered to multiple output formats. It supports two styles: "compact" (default, inline with minimal spacing) and "badge" (pill-shaped badges).

func KeyValue

func KeyValue(key string, value any, styles ...string) KeyValuePair

func (KeyValuePair) ANSI

func (kv KeyValuePair) ANSI() string

func (KeyValuePair) HTML

func (kv KeyValuePair) HTML() string

func (KeyValuePair) IsEmpty

func (kv KeyValuePair) IsEmpty() bool

func (KeyValuePair) Markdown

func (kv KeyValuePair) Markdown() string

func (KeyValuePair) MarkdownSlack

func (kv KeyValuePair) MarkdownSlack() string

func (KeyValuePair) String

func (kv KeyValuePair) String() string

type Keyed

type Keyed struct {
	Key   string
	Value Textable
}

Keyed wraps a Textable with a data key. Rendering passes through to the wrapped value unchanged in every format; only JSON serialization differs — the value marshals under Key as a single-field object. Use it when a block in a document needs a stable identifier for structured output (e.g. a table keyed by its heading) without altering how it renders.

func (Keyed) ANSI

func (k Keyed) ANSI() string

func (Keyed) HTML

func (k Keyed) HTML() string

func (Keyed) Markdown

func (k Keyed) Markdown() string

func (Keyed) MarshalJSON

func (k Keyed) MarshalJSON() ([]byte, error)

MarshalJSON emits {Key: Value}. The wrapped value serializes via its own MarshalJSON when it implements json.Marshaler, otherwise via its rendered string.

func (Keyed) String

func (k Keyed) String() string

type LabelBadge

type LabelBadge struct {
	Label     string
	Value     string
	Color     string // tailwind bg class, e.g. "bg-blue-100"
	TextColor string // tailwind text class, e.g. "text-slate-700"
	Shape     string // "pill" | "rounded" | "square"; default "rounded"
	Icon      string // iconify icon name, optional
}

LabelBadge is a two-part pill: a muted label followed by an emphasised value, rendered by clicky-ui's <Badge variant="label" />. It is distinct from the single-label Badge() helper in html.go, which produces a plain pill with no label/value split.

The Color/TextColor fields accept tailwind class names (e.g. "bg-blue-100" and "text-slate-700"); Shape controls the corner radius and Icon is an optional iconify name rendered before the label.

func (LabelBadge) ANSI

func (b LabelBadge) ANSI() string

func (LabelBadge) HTML

func (b LabelBadge) HTML() string

func (LabelBadge) Markdown

func (b LabelBadge) Markdown() string

func (LabelBadge) String

func (b LabelBadge) String() string

type Line

type Line struct {
	Color      Color
	Style      LineStyle
	Width      float64
	EndStyle   LineEndStyle
	StartStyle LineEndStyle
}

type LineEndStyle

type LineEndStyle string
const (
	LineEndStyleNone    LineEndStyle = "none"
	LineEndStyleArrow   LineEndStyle = "arrow"
	LineEndStyleDiamond LineEndStyle = "diamond"
)

type LineStyle

type LineStyle string
const (
	Solid  LineStyle = "solid"
	Dashed LineStyle = "dashed"
	Dotted LineStyle = "dotted"
	Double LineStyle = "double"
	None   LineStyle = "none"
)
type Link struct {
	Href    string
	Target  LinkTarget
	Content Text
	// JSON is an optional structured payload carried alongside the link. Unlike
	// Text, a Link serializes to a structured object (see MarshalJSON), so this
	// payload survives JSON encoding and reaches structured-JSON consumers (e.g.
	// a web UI that renders an <a> from the href and uses the payload for
	// client-side navigation). It is ignored by String/ANSI/Markdown/HTML.
	JSON any
}
func NewLink(href string) Link

func (Link) ANSI

func (l Link) ANSI() string

func (Link) Add

func (l Link) Add(child Textable) Link

func (Link) AddText

func (l Link) AddText(content string, styles ...string) Link

func (Link) Append

func (l Link) Append(text any, styles ...string) Link

func (Link) AppendStyle

func (l Link) AppendStyle(classes ...string) Link

func (Link) Appendf

func (l Link) Appendf(format string, args ...interface{}) Link

func (Link) HTML

func (l Link) HTML() string

func (Link) Markdown

func (l Link) Markdown() string

func (Link) MarshalJSON

func (l Link) MarshalJSON() ([]byte, error)

MarshalJSON serializes a Link as a structured object so its href and payload survive JSON encoding. This is deliberately richer than Text.MarshalJSON (which flattens to a plain string): a structured-JSON consumer can render the link as an anchor and use the payload for navigation. Only non-empty fields are emitted.

func (Link) Prefix

func (l Link) Prefix(prefix string) Link

func (Link) Space

func (l Link) Space() Link

func (Link) String

func (l Link) String() string

func (Link) Styles

func (l Link) Styles(classes ...string) Link

func (Link) Suffix

func (l Link) Suffix(suffix string) Link

func (Link) Tab

func (l Link) Tab() Link

func (Link) Text

func (l Link) Text(content string, styles ...string) Link

func (Link) WithJSON

func (l Link) WithJSON(v any) Link

WithJSON attaches a structured payload to the link. The payload is emitted by MarshalJSON under the "json" key; it does not affect text rendering.

func (Link) WithStyles

func (l Link) WithStyles(styles ...string) Link

func (Link) WithTarget

func (l Link) WithTarget(target LinkTarget) Link

func (Link) WithTooltip

func (l Link) WithTooltip(tooltip Textable) Link

type LinkCommand

type LinkCommand struct {
	Command string
	Args    []string
	Flags   map[string]string
	Target  LinkTarget
	AutoRun bool
	Content Text
}

func NewLinkCommand

func NewLinkCommand(command string) LinkCommand

func (LinkCommand) ANSI

func (l LinkCommand) ANSI() string

func (LinkCommand) Add

func (l LinkCommand) Add(child Textable) LinkCommand

func (LinkCommand) AddText

func (l LinkCommand) AddText(content string, styles ...string) LinkCommand

func (LinkCommand) Append

func (l LinkCommand) Append(text any, styles ...string) LinkCommand

func (LinkCommand) AppendStyle

func (l LinkCommand) AppendStyle(classes ...string) LinkCommand

func (LinkCommand) Appendf

func (l LinkCommand) Appendf(format string, args ...interface{}) LinkCommand

func (LinkCommand) HTML

func (l LinkCommand) HTML() string

func (LinkCommand) Markdown

func (l LinkCommand) Markdown() string

func (LinkCommand) Prefix

func (l LinkCommand) Prefix(prefix string) LinkCommand

func (LinkCommand) Space

func (l LinkCommand) Space() LinkCommand

func (LinkCommand) String

func (l LinkCommand) String() string

func (LinkCommand) Styles

func (l LinkCommand) Styles(classes ...string) LinkCommand

func (LinkCommand) Suffix

func (l LinkCommand) Suffix(suffix string) LinkCommand

func (LinkCommand) Tab

func (l LinkCommand) Tab() LinkCommand

func (LinkCommand) Text

func (l LinkCommand) Text(content string, styles ...string) LinkCommand

func (LinkCommand) WithArgs

func (l LinkCommand) WithArgs(args ...string) LinkCommand

func (LinkCommand) WithAutoRun

func (l LinkCommand) WithAutoRun(autoRun bool) LinkCommand

func (LinkCommand) WithFlag

func (l LinkCommand) WithFlag(name, value string) LinkCommand

func (LinkCommand) WithFlags

func (l LinkCommand) WithFlags(flags map[string]string) LinkCommand

func (LinkCommand) WithStyles

func (l LinkCommand) WithStyles(styles ...string) LinkCommand

func (LinkCommand) WithTarget

func (l LinkCommand) WithTarget(target LinkTarget) LinkCommand

func (LinkCommand) WithTooltip

func (l LinkCommand) WithTooltip(tooltip Textable) LinkCommand

type LinkTarget

type LinkTarget string
const (
	LinkTargetDialog LinkTarget = "Dialog"
	LinkTargetHover  LinkTarget = "Hover"
	LinkTargetExpand LinkTarget = "Expand"
	LinkTargetClicky LinkTarget = "_clicky"
	LinkTargetSelf   LinkTarget = "_self"
	LinkTargetWindow LinkTarget = "_window"
	LinkTargetTab    LinkTarget = "_tab"
)

type List

type List struct {
	Items     []Textable
	Unstyled  bool     // Whether to render without any bullet or numbering
	Bullet    Textable // Bullet character or icon
	Numbered  bool     // Whether to use numbered list
	Ordered   bool     // Alias for Numbered
	Style     string   // Additional styles for the list container
	Spacing   int      // Spaces between bullet and content
	Indent    int
	MaxInline int // Max items to render inline, else vertical
}

func (List) ANSI

func (l List) ANSI() string

func (List) HTML

func (l List) HTML() string

func (List) Markdown

func (l List) Markdown() string

func (List) MarkdownSlack

func (l List) MarkdownSlack() string

func (List) String

func (l List) String() string

type Padding

type Padding struct {
	Top    Point
	Right  Point
	Bottom Point
	Left   Point
}

Padding defines spacing around content in CSS box model format using Point units.

func (*Padding) BottomMM

func (p *Padding) BottomMM() float64

BottomMM returns the bottom padding converted to millimeters

func (*Padding) LeftMM

func (p *Padding) LeftMM() float64

LeftMM returns the left padding converted to millimeters

func (*Padding) RightMM

func (p *Padding) RightMM() float64

RightMM returns the right padding converted to millimeters

func (*Padding) TopMM

func (p *Padding) TopMM() float64

TopMM returns the top padding converted to millimeters

type Point

type Point float64

Point represents a measurement in typographic points

func NewPoint

func NewPoint(value float64) Point

NewPoint creates a new Point value

func (Point) Float64

func (p Point) Float64() float64

Float64 returns the point value as a float64

func (Point) String

func (p Point) String() string

String returns a formatted string representation

func (Point) ToMM

func (p Point) ToMM() float64

ToMM converts points to millimeters

type Position

type Position struct {
	X int `json:"x,omitempty"`
	Y int `json:"y,omitempty"`
}

func (Position) RelativeTo

func (p Position) RelativeTo(other Position) Position

type Pretty

type Pretty interface {
	Pretty() Text
}

Pretty enables objects to provide rich text formatting with styling and structure. Types implementing this interface can control their visual representation across different output formats (terminal, HTML, PDF, etc.).

type PrettyData

type PrettyData struct {
	TypedValue

	Schema *PrettyObject

	Original interface{}
}

PrettyData contains structured data processed through schema-driven formatting. It separates regular field values from tabular and tree data, maintaining the original data for serialization while providing formatted access.

func (*PrettyData) GetTable

func (pd *PrettyData) GetTable(tableName string) (*TextTable, bool)

GetTable returns the table data if it exists

func (*PrettyData) GetValue

func (pd *PrettyData) GetValue(fieldName string) (TypedValue, bool)

GetValue retrieves a typed value by field name from the TypedMap

func (*PrettyData) IsEmpty

func (pd *PrettyData) IsEmpty() bool

IsEmpty returns true if the PrettyData has no meaningful content

type PrettyDataRow

type PrettyDataRow map[string]TypedValue

func FilterTableRows

func FilterTableRows(rows []PrettyDataRow, filterExpr string) ([]PrettyDataRow, error)

FilterTableRows filters table rows using a CEL expression. Field values are injected directly into the CEL context (no "row." prefix). Returns filtered rows or error if CEL expression is invalid.

type PrettyField

type PrettyField struct {
	Name          string            `json:"name" yaml:"name"`
	Aliases       []string          `json:"aliases,omitempty" yaml:"aliases,omitempty"`
	Type          string            `json:"type,omitempty" yaml:"type,omitempty"`
	Format        string            `json:"format,omitempty" yaml:"format,omitempty"`
	Label         string            `json:"label,omitempty" yaml:"label,omitempty"`
	Default       string            `json:"default,omitempty" yaml:"default,omitempty"`
	Style         string            `json:"style,omitempty" yaml:"style,omitempty"`
	LabelStyle    string            `json:"label_style,omitempty" yaml:"label_style,omitempty"`
	Color         string            `json:"color,omitempty" yaml:"color,omitempty"`
	DateFormat    string            `json:"date_format,omitempty" yaml:"date_format,omitempty"`
	FormatOptions map[string]string `json:"format_options,omitempty" yaml:"format_options,omitempty"`
	ColorOptions  map[string]string `json:"color_options,omitempty" yaml:"color_options,omitempty"`
	// For nested struct fields
	Fields []PrettyField `json:"fields,omitempty" yaml:"fields,omitempty"`
	// For table formatting
	TableOptions TableOptions `json:"table_options,omitempty" yaml:"table_options,omitempty"`
	// For tree formatting
	TreeOptions *TreeOptions `json:"tree_options,omitempty" yaml:"tree_options,omitempty"`
	// For custom rendering
	RenderFunc   RenderFunc `json:"-" yaml:"-"`
	CompactItems bool       `json:"compact_items,omitempty" yaml:"compact_items,omitempty"`
	// Short renders the field via its value's PrettyShort() (a compact
	// self-link, typically) instead of Pretty()/Textable, in the struct,
	// table, and clicky+json printers. Set by the `short` pretty-tag flag.
	Short bool `json:"short,omitempty" yaml:"short,omitempty"`
}

PrettyField configures how a data field should be formatted and displayed. It supports schema-driven formatting with type inference, custom styling, nested field definitions, and conditional coloring based on field values.

func ParsePrettyTag

func ParsePrettyTag(tag string) PrettyField

ParsePrettyTag converts a struct tag string into field configuration. Supports format options, styling, colors, and tree/table settings.

func ParsePrettyTagWithName

func ParsePrettyTagWithName(fieldName, tag string) PrettyField

ParsePrettyTagWithName creates field configuration from a struct tag, using the provided field name as the default label and identifier.

func (PrettyField) Parse

func (f PrettyField) Parse(value interface{}) (FieldValue, error)

Parse converts a raw value into a FieldValue with type inference and validation. It performs type conversion based on the field's configured type, handles nested structures, and creates appropriate Text objects for rich formatting.

type PrettyFieldData

type PrettyFieldData struct {
	Label Text
	Value Textable
}

type PrettyFull

type PrettyFull interface {
	PrettyFull() Textable
}

type PrettyNode

type PrettyNode interface {
	Pretty() Text
}

PrettyNode extends TreeNode with rich text formatting capabilities.

type PrettyObject

type PrettyObject struct {
	Fields []PrettyField `json:"fields" yaml:"fields"`
}

PrettyObject defines the schema for formatting structured data, containing field definitions that control how each property is displayed.

type PrettyRow

type PrettyRow interface {
	PrettyRow(opts interface{}) map[string]Text
}

PrettyRow enables structs to provide custom table row representation with fine-grained control over columns and cell formatting based on output format options. The opts parameter should be of type formatters.FormatOptions.

type PrettyShort

type PrettyShort interface {
	PrettyShort() Textable
}

PrettyShort enables objects to provide a compact, single-line representation for use in table cells (typically a self-link), distinct from Pretty()'s fuller detail view. Cell renderers prefer PrettyShort() over Pretty() when a value implements it; everything else renders via Pretty()/Textable unchanged. It returns a Textable so an implementer can hand back a value type (e.g. a link struct that itself implements Textable) without an extra render call.

type PrettyStructData

type PrettyStructData struct {
}

type Rectangle

type Rectangle struct {
	Width  int `json:"width,omitempty"`
	Height int `json:"height,omitempty"`
}

type RenderFunc

type RenderFunc func(value interface{}, field PrettyField, theme Theme) string

RenderFunc provides custom rendering logic for field values. It receives the raw value, field configuration, and current theme, allowing complete control over how a field is displayed.

type Severity

type Severity int

Severity classifies an Admonition callout. The zero value is SeverityNote.

const (
	SeverityNote Severity = iota
	SeverityInfo
	SeverityTip
	SeverityWarning
	SeverityDanger
)

func ParseSeverity

func ParseSeverity(s string) Severity

ParseSeverity maps an author-supplied severity word to a Severity. Unknown words fall through to SeverityNote so callers preserve the raw text via the admonition body rather than failing.

func (Severity) Icon

func (s Severity) Icon() icons.Icon

Icon returns the status icon conventionally paired with the severity.

func (Severity) String

func (s Severity) String() string

String returns the canonical lower-case severity keyword, used both as the admonition header word and the HTML class suffix.

type SimpleTreeNode

type SimpleTreeNode struct {
	Label    string                 `json:"label" yaml:"label"`
	Icon     string                 `json:"icon,omitempty" yaml:"icon,omitempty"`
	Style    string                 `json:"style,omitempty" yaml:"style,omitempty"`
	Children []TreeNode             `json:"children,omitempty" yaml:"children,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty" yaml:"metadata,omitempty"`
}

SimpleTreeNode provides a straightforward TreeNode implementation with support for labels, icons, styling, and arbitrary metadata.

func TreeNodeToSimple

func TreeNodeToSimple(node TreeNode) *SimpleTreeNode

TreeNodeToSimple recursively converts any TreeNode implementation to SimpleTreeNode. This normalizes different TreeNode implementations into a concrete type for consistent formatting.

func (*SimpleTreeNode) GetChildren

func (n *SimpleTreeNode) GetChildren() []TreeNode

func (*SimpleTreeNode) Pretty

func (n *SimpleTreeNode) Pretty() Text

type SourceResolver

type SourceResolver interface {
	Resolve(ctx context.Context, frame StackFrame, ctxLines int) (lines []string, startLine int, lang string, ok bool)
}

SourceResolver supplies source lines for a frame so the rendered stack trace can show inline code context. Implementations may consult a local checkout, decompiled JARs, a remote service, or anything else; failures must be non-fatal — return ("", 0, nil, false) when no source is available.

Returning startLine + len(lines)-1 must cover frame.Line so renderers can highlight the focal line. ctxLines is the number of lines requested above and below the focal line; the resolver may return less.

type SourceResolverFunc

type SourceResolverFunc func(ctx context.Context, frame StackFrame, ctxLines int) (lines []string, startLine int, lang string, ok bool)

SourceResolverFunc adapts a plain function to SourceResolver, mirroring http.HandlerFunc so callers don't have to declare a struct.

func (SourceResolverFunc) Resolve

func (f SourceResolverFunc) Resolve(ctx context.Context, frame StackFrame, ctxLines int) ([]string, int, string, bool)

type StackFrame

type StackFrame struct {
	Class             string
	Method            string
	File              string
	Line              int
	Native            bool
	Runtime           bool
	Annotation        string
	SourceLines       []string
	SourceLineNumbers []int
	SourceStartLine   int
	SourceLanguage    string
}

StackFrame is one parsed entry of a runtime stack trace. Only a subset of fields is populated for any given language; renderers tolerate empty values.

Class+Method together form a stable, language-agnostic identifier that SourceResolver implementations may use as a lookup key (e.g., for Java `decompile` output) when no usable File path is available.

type StackTrace

type StackTrace struct {
	ExceptionClass string
	Message        string
	CausedBy       []string
	Frames         []StackFrame
	Language       string
	// contains filtered or unexported fields
}

StackTrace is a parsed runtime stack trace. It carries the high-level exception/cause metadata that most languages emit (Java, Python, .NET) plus the ordered frame list. Construct one via clicky.StackTrace(input, opts...) or one of the language-specific parsers (clicky.StackTraceJava).

func NewStackTrace

func NewStackTrace(opts ...StackTraceOption) StackTrace

NewStackTrace returns an empty trace with options applied. Language-specific parsers populate the fields after construction.

func ParseJavaStackTrace

func ParseJavaStackTrace(input string, opts ...StackTraceOption) StackTrace

ParseJavaStackTrace parses a free-form Java exception dump (the body of `java.lang.Throwable.printStackTrace()`) into a StackTrace ready to render. It tolerates common surrounding noise: EclipseLink "Internal Exception:" / "Caused by:" / "... N more" continuation markers, and frames whose `(File:Line)` parenthesised location omits the line number, marks the method as native, or wraps a JAR descriptor like `(SomeClass.java:42) ~[exampleapp-1.0.jar:?]`.

Frames whose class belongs to a JDK / framework package (java., javax., jdk., sun., com.sun.) are tagged with Runtime=true so renderers can mute them visually. Native methods (`Native Method`) get Native=true.

func (StackTrace) ANSI

func (s StackTrace) ANSI() string

ANSI / Pretty / Markdown delegate to the assembled Text so a StackTrace is a drop-in Textable for any clicky formatter. HTML uses a dedicated structured renderer (renderHTML) so frames and source context get semantic blocks and monospaced layout instead of a single whitespace-collapsed line.

func (StackTrace) HTML

func (s StackTrace) HTML() string

func (StackTrace) Markdown

func (s StackTrace) Markdown() string

func (StackTrace) Pretty

func (s StackTrace) Pretty() Text

func (StackTrace) Render

func (s StackTrace) Render() Text

Render builds the styled api.Text for this trace. ANSI/HTML/Markdown all share the same Text tree — terminal renderers honor `Style` ANSI mappings, HTML preserves arbitrary Tailwind classes, and Markdown round-trips inline styled spans.

func (StackTrace) String

func (s StackTrace) String() string

String renders ANSI for fmt %s usage and convenient terminal printing.

type StackTraceOption

type StackTraceOption func(*stackTraceOptions)

StackTraceOption mutates a StackTrace's render configuration. Use the WithXxx helpers; the option type is exported only so callers can build their own option sets without importing private state.

func WithMaxFrames

func WithMaxFrames(n int) StackTraceOption

WithMaxFrames truncates the rendered stack to the top N kept frames so very long traces don't dominate the output. Zero (default) keeps everything.

func WithSourceResolver

func WithSourceResolver(r SourceResolver) StackTraceOption

WithSourceResolver attaches a SourceResolver that supplies inline source lines. Without one, frames render headers only.

func WithSourceResolverContext

func WithSourceResolverContext(ctx context.Context) StackTraceOption

WithSourceResolverContext supplies the context.Context that resolver calls run under. Defaults to context.Background().

func WithStackContext

func WithStackContext(n int) StackTraceOption

WithStackContext sets the number of source lines rendered before and after each frame's reported line. Default 3. Must be >= 0.

func WithStackExclude

func WithStackExclude(prefixes ...string) StackTraceOption

WithStackExclude drops frames whose class starts with any of the prefixes from the rendered output. Exclude beats include.

func WithStackInclude

func WithStackInclude(prefixes ...string) StackTraceOption

WithStackInclude restricts decoration (frame display + source resolution) to classes whose fully-qualified name starts with one of the given prefixes. An empty include set means "match any".

type StaticHTMLProvider

type StaticHTMLProvider interface {
	StaticHTML() string
}

StaticHTMLProvider is implemented by types that can render pure HTML without JavaScript. Used by Collapsed to avoid embedding scripts (e.g. Grid.js) inside <template x-if> where they won't execute.

type StructParser

type StructParser struct{}

StructParser handles parsing of structs into PrettyObject

func NewStructParser

func NewStructParser() *StructParser

NewStructParser creates a new struct parser

func (*StructParser) GetFieldValue

func (p *StructParser) GetFieldValue(val reflect.Value, fieldName string) reflect.Value

GetFieldValue gets a field value by name from a struct

func (*StructParser) GetTableFields

func (p *StructParser) GetTableFields(val reflect.Value) ([]PrettyField, error)

GetTableFields extracts fields from a struct for table formatting

func (*StructParser) GetTableFieldsFromMap

func (p *StructParser) GetTableFieldsFromMap(val reflect.Value) []PrettyField

GetTableFieldsFromMap extracts fields from a map for table formatting

func (*StructParser) LoadSchemaFromYAML

func (p *StructParser) LoadSchemaFromYAML(filepath string) (*PrettyObject, error)

LoadSchemaFromYAML loads a PrettyObject schema from a YAML file

func (*StructParser) Parse

func (p *StructParser) Parse(data interface{}) (*PrettyObject, error)

Parse takes a struct and returns a PrettyObject

func (*StructParser) ParseDataWithSchema

func (p *StructParser) ParseDataWithSchema(data interface{}, schema *PrettyObject) (*PrettyData, error)

ParseDataWithSchema parses data into PrettyData using a predefined schema

func (*StructParser) ParseStructSchema

func (p *StructParser) ParseStructSchema(val reflect.Value) (*PrettyObject, error)

ParseStructSchema creates a PrettyObject schema from struct tags

func (*StructParser) ParseValue

func (p *StructParser) ParseValue(value interface{}, field PrettyField) (FieldValue, error)

ParseValue creates a FieldValue from a raw value and PrettyField definition

func (*StructParser) ParseWithSchema

func (p *StructParser) ParseWithSchema(data interface{}, schema *PrettyObject) (*PrettyObject, error)

ParseWithSchema parses data using a predefined schema with heuristics

func (*StructParser) ProcessFieldValue

func (p *StructParser) ProcessFieldValue(fieldVal reflect.Value) TypedValue

ProcessFieldValue processes a field value, handling pointers and returning the appropriate value This is the central normalization function that converts all values to simple types: - Pointers are dereferenced (nil pointers return nil) - Pretty implementations are converted to Text objects - Structs are converted to maps recursively - Slices and maps are processed recursively - Circular references are detected and returned as "[circular reference]"

func (*StructParser) StructToRow

func (p *StructParser) StructToRow(val reflect.Value) (PrettyDataRow, error)

StructToRow converts a struct to a PrettyDataRow

func (*StructParser) StructToRowWithOptions

func (p *StructParser) StructToRowWithOptions(val reflect.Value, opts interface{}) (PrettyDataRow, error)

StructToRowWithOptions converts a struct to a PrettyDataRow, checking for PrettyRow interface first

type StyleBuilder

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

StyleBuilder accumulates CSS classes into a space-separated style string.

func NewStyle

func NewStyle() *StyleBuilder

func (*StyleBuilder) Background

func (sb *StyleBuilder) Background(color string) *StyleBuilder

func (*StyleBuilder) Bold

func (sb *StyleBuilder) Bold() *StyleBuilder

func (*StyleBuilder) Build

func (sb *StyleBuilder) Build() string

func (*StyleBuilder) Capitalize

func (sb *StyleBuilder) Capitalize() *StyleBuilder

func (*StyleBuilder) Color

func (sb *StyleBuilder) Color(color string) *StyleBuilder

func (*StyleBuilder) Custom

func (sb *StyleBuilder) Custom(style string) *StyleBuilder

func (*StyleBuilder) Error

func (sb *StyleBuilder) Error() *StyleBuilder

func (*StyleBuilder) Faint

func (sb *StyleBuilder) Faint() *StyleBuilder

func (*StyleBuilder) Info

func (sb *StyleBuilder) Info() *StyleBuilder

func (*StyleBuilder) Italic

func (sb *StyleBuilder) Italic() *StyleBuilder

func (*StyleBuilder) Lowercase

func (sb *StyleBuilder) Lowercase() *StyleBuilder

func (*StyleBuilder) Muted

func (sb *StyleBuilder) Muted() *StyleBuilder

func (*StyleBuilder) Strikethrough

func (sb *StyleBuilder) Strikethrough() *StyleBuilder

func (*StyleBuilder) Success

func (sb *StyleBuilder) Success() *StyleBuilder

func (*StyleBuilder) Underline

func (sb *StyleBuilder) Underline() *StyleBuilder

func (*StyleBuilder) Uppercase

func (sb *StyleBuilder) Uppercase() *StyleBuilder

func (*StyleBuilder) Warning

func (sb *StyleBuilder) Warning() *StyleBuilder

type TableHeaderMixin

type TableHeaderMixin interface {
	TableHeaders() TextList
}

type TableMixin

type TableMixin interface {
	TableHeaderMixin
	TableRowMixin
}

type TableOptions

type TableOptions struct {
	Title         string                   `json:"title,omitempty" yaml:"title,omitempty"`
	Columns       []PrettyField            `json:"fields" yaml:"fields"`
	Rows          []map[string]interface{} `json:"rows,omitempty" yaml:"rows,omitempty"`
	SortField     string                   `json:"sort_field,omitempty" yaml:"sort_field,omitempty"`
	SortDirection string                   `json:"sort_direction,omitempty" yaml:"sort_direction,omitempty"`
	HeaderStyle   string                   `json:"header_style,omitempty" yaml:"header_style,omitempty"`
	RowStyle      string                   `json:"row_style,omitempty" yaml:"row_style,omitempty"`
}

TableOptions configures tabular data presentation including column definitions, sorting behavior, and styling options for headers and rows.

type TableProvider

type TableProvider interface {
	// Columns returns the column schema in display order.
	Columns() []ColumnDef

	// Row returns the raw data for this item as a map of column name to value.
	// Values are rendered using Text{}.Add(value).
	Row() map[string]any
}

TableProvider is the interface for types that can represent themselves as table rows. Column order is determined by the slice order returned from Columns().

type TableRow

type TableRow map[string]TypedValue

type TableRowMixin

type TableRowMixin interface {
	TableCells() TableRow
}

type TableRowMixin2

type TableRowMixin2 interface {
	PrettyRow(opt any) PrettyDataRow
}

type TailwindStyle

type TailwindStyle struct {
	Foreground    string
	Background    string
	Font          Font
	Bold          bool
	Faint         bool
	Italic        bool
	Underline     bool
	Strikethrough bool
	TextTransform string
}

TailwindStyle contains parsed CSS styling information extracted from Tailwind classes.

func ApplyTailwindStyle

func ApplyTailwindStyle(text, styleStr string) (string, TailwindStyle)

ApplyTailwindStyle processes Tailwind CSS classes and applies text transformations, returning both the transformed text and parsed style information.

type Text

type Text struct {
	Content  string
	Class    Class
	Style    string
	Children []Textable
	Tooltip  Textable
	// contains filtered or unexported fields
}

Text represents styled content that can be rendered to multiple output formats. It supports hierarchical structure through Children, CSS-compatible styling, and format-specific rendering (ANSI, HTML, Markdown).

func BoldText

func BoldText(content string) Text

func ErrorText

func ErrorText(content string) Text

ErrorText creates a red-styled text for error states.

func Human

func Human(content any, styles ...string) Text

func HumanDate

func HumanDate(d any, format string) Text

func HumanNumber

func HumanNumber(value int64, styles ...string) Text

func HumanizeBytes

func HumanizeBytes(bytes int64) Text

func InfoText

func InfoText(content string) Text

InfoText creates a blue-styled text for informational content.

func ItalicText

func ItalicText(content string) Text

func MutedText

func MutedText(content string) Text

MutedText creates a gray-styled text for secondary content.

func StatusText

func StatusText(status, content string) Text

StatusText applies semantic styling based on status keywords (PASS/SUCCESS/OK -> green, FAIL/ERROR -> red, WARN -> yellow, etc.).

func SuccessText

func SuccessText(content string) Text

SuccessText creates a green-styled text for positive states.

func TimeAgo

func TimeAgo(t *time.Time) Text

func WarningText

func WarningText(content string) Text

WarningText creates a yellow-styled text for warning states.

func (Text) ANSI

func (t Text) ANSI() string

func (Text) Add

func (t Text) Add(child Textable) Text

func (Text) AddIcon

func (t Text) AddIcon(icon Textable, styles ...string) Text

AddIcon convenience method for adding icons as children

func (Text) AddText

func (t Text) AddText(content string, styles ...string) Text

AddText convenience method for adding Text content as a child

func (Text) Append

func (t Text) Append(text any, styles ...string) Text

Append adds a new child Text with the specified content and styles.

func (Text) AppendStyle

func (t Text) AppendStyle(classes ...string) Text

AppendStyle merges the given Tailwind class names into t.Style without duplicating classes that are already present.

func (Text) Appendf

func (t Text) Appendf(format string, args ...interface{}) Text

Append adds a new child Text with the specified content and styles.

func (Text) Format

func (t Text) Format(f fmt.State, verb rune)

Format implements fmt.Formatter to ensure sensitive values are redacted in all format verbs

func (Text) HR

func (t Text) HR() Text

func (Text) HTML

func (t Text) HTML() string

func (Text) Human

func (t Text) Human(o any, styles ...string) Text

func (Text) Indent

func (t Text) Indent(spaces int) Text

Indent adds spaces before every line in content and recursively indents children with additional spacing, creating proper hierarchical indentation.

func (Text) IsEmpty

func (t Text) IsEmpty() bool

func (Text) IsSpace

func (t Text) IsSpace() bool

func (Text) Markdown

func (t Text) Markdown() string

func (Text) MarkdownSlack

func (t Text) MarkdownSlack() string

func (Text) MarshalJSON

func (t Text) MarshalJSON() ([]byte, error)

func (Text) NewLine

func (t Text) NewLine() Text

func (Text) Prefix

func (t Text) Prefix(prefix string) Text

func (Text) Printf

func (t Text) Printf(format string, args ...interface{}) Text

func (Text) PrintfWithStyle

func (t Text) PrintfWithStyle(format, style string, args ...interface{}) Text

PrintfWithStyle formats arguments with special handling for float64 (2 decimal places) and time.Duration (human-readable format), appending the result as a styled child.

func (Text) Space

func (t Text) Space() Text

func (Text) String

func (t Text) String() string

func (Text) Styles

func (t Text) Styles(classes ...string) Text

func (Text) Suffix

func (t Text) Suffix(suffix string) Text

func (Text) Tab

func (t Text) Tab() Text

func (Text) Text

func (t Text) Text(text string, styles ...string) Text

Text adds a new child Text with the specified content and styles.

func (Text) WithStyles

func (t Text) WithStyles(styles ...string) Text

func (Text) WithTooltip

func (t Text) WithTooltip(tooltip Textable) Text

func (Text) Wrap

func (t Text) Wrap(prefix, suffix string, style ...string) Text

Wrap adds a prefix and suffix to the content Wrap returns a new Text consisting of `prefix`, the receiver `t`, and `suffix`. When a style is supplied, the prefix and suffix are placed in dedicated child Text nodes carrying that style; the receiver `t` is left untouched. (The earlier implementation called `t.Add(t)` after appending the prefix, which doubled the receiver in the output.)

func (Text) WrapSpace

func (t Text) WrapSpace() Text

WrapSpace adds a space before and after the content

type TextBuilder

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

TextBuilder constructs Text objects using a fluent interface with chained styling methods.

func NewText

func NewText(content string) *TextBuilder

func (*TextBuilder) Background

func (tb *TextBuilder) Background(color string) *TextBuilder

Background accepts both hex colors (#FF0000) and named colors (red-600).

func (*TextBuilder) Bold

func (tb *TextBuilder) Bold() *TextBuilder

func (*TextBuilder) Build

func (tb *TextBuilder) Build() Text

func (*TextBuilder) Capitalize

func (tb *TextBuilder) Capitalize() *TextBuilder

func (*TextBuilder) Child

func (tb *TextBuilder) Child(child Text) *TextBuilder

func (*TextBuilder) ChildBuilder

func (tb *TextBuilder) ChildBuilder(childBuilder *TextBuilder) *TextBuilder

func (*TextBuilder) Color

func (tb *TextBuilder) Color(color string) *TextBuilder

Color accepts both hex colors (#FF0000) and named colors (red-600).

func (*TextBuilder) Content

func (tb *TextBuilder) Content(content string) *TextBuilder

func (*TextBuilder) Error

func (tb *TextBuilder) Error() *TextBuilder

func (*TextBuilder) Faint

func (tb *TextBuilder) Faint() *TextBuilder

func (*TextBuilder) Info

func (tb *TextBuilder) Info() *TextBuilder

func (*TextBuilder) Italic

func (tb *TextBuilder) Italic() *TextBuilder

func (*TextBuilder) Lowercase

func (tb *TextBuilder) Lowercase() *TextBuilder

func (*TextBuilder) Muted

func (tb *TextBuilder) Muted() *TextBuilder

func (*TextBuilder) Strikethrough

func (tb *TextBuilder) Strikethrough() *TextBuilder

func (*TextBuilder) Style

func (tb *TextBuilder) Style(style string) *TextBuilder

func (*TextBuilder) Success

func (tb *TextBuilder) Success() *TextBuilder

func (*TextBuilder) Underline

func (tb *TextBuilder) Underline() *TextBuilder

func (*TextBuilder) Uppercase

func (tb *TextBuilder) Uppercase() *TextBuilder

func (*TextBuilder) Warning

func (tb *TextBuilder) Warning() *TextBuilder

type TextList

type TextList []Textable

TextList is a list of Textable items that can be rendered to multiple formats. Use JoinNewlines() to create a single Textable that joins all items with newlines.

func (TextList) ANSI

func (tl TextList) ANSI() string

func (TextList) AsANSI

func (tl TextList) AsANSI() []string

func (TextList) AsHTML

func (tl TextList) AsHTML() []string

func (TextList) AsMarkdown

func (tl TextList) AsMarkdown() []string

func (TextList) AsString

func (tl TextList) AsString() []string

func (TextList) HTML

func (tl TextList) HTML() string

func (TextList) Indent

func (tl TextList) Indent() TextList

Indent returns a new TextList with all items indented by one level (one tab). The indentation is prepended to the beginning of each item when rendered.

func (TextList) Join

func (tl TextList) Join(sep ...Textable) Text

func (TextList) JoinNewlines

func (tl TextList) JoinNewlines() Text

JoinNewlines joins all items with newlines and returns a single Textable. This is the primary method for rendering a TextList - call .ANSI(), .HTML(), or .Markdown() on the result.

func (TextList) Markdown

func (tl TextList) Markdown() string

func (TextList) MarkdownSlack

func (tl TextList) MarkdownSlack() string

func (TextList) String

func (tl TextList) String() string

func (TextList) Strings

func (tl TextList) Strings() []string

type TextMap

type TextMap map[string]Textable

func (TextMap) ANSI

func (tm TextMap) ANSI() string

func (TextMap) HTML

func (tm TextMap) HTML() string

func (TextMap) Markdown

func (tm TextMap) Markdown() string

func (TextMap) MarkdownSlack

func (tm TextMap) MarkdownSlack() string

func (TextMap) String

func (tm TextMap) String() string

func (TextMap) Value

func (tm TextMap) Value() Textable

type TextTable

type TextTable struct {
	Headers     TextList
	FieldNames  []string // Maps header index to field name for row lookups
	Columns     []PrettyField
	Rows        []TableRow
	RowDetail   []Textable // Per-row detail content shown on expand (nil entry = no detail)
	Interactive bool
}

func NewEmptyTable

func NewEmptyTable(columns []ColumnDef) TextTable

NewEmptyTable builds a header-only TextTable from column definitions, with no rows. It is the shared schema-building step for NewTableFrom, and lets empty result sets still render the table chrome (headers) instead of collapsing to a "No data" placeholder.

func NewTable

func NewTable[T TableMixin](o []T) TextTable

func NewTableFrom

func NewTableFrom[T TableProvider](items []T) TextTable

NewTableFrom creates a TextTable from a slice of TableProvider items.

func NewTableFromMixin

func NewTableFromMixin[T TableRowMixin2](o []T) TextTable

func NewTableFromRows

func NewTableFromRows(o []PrettyDataRow) TextTable

func (TextTable) ANSI

func (t TextTable) ANSI() string

func (TextTable) AsString

func (tt TextTable) AsString(row TableRow) []string

func (TextTable) CompactHTML

func (table TextTable) CompactHTML() string

func (TextTable) HTML

func (table TextTable) HTML() string

func (TextTable) Markdown

func (t TextTable) Markdown() string

func (TextTable) MarshalJSON

func (tt TextTable) MarshalJSON() ([]byte, error)

MarshalJSON serializes TextTable as an array of row objects

func (TextTable) MarshalYAML

func (tt TextTable) MarshalYAML() (interface{}, error)

MarshalYAML serializes TextTable as an array of row objects

func (TextTable) PrintableHTML

func (table TextTable) PrintableHTML() string

func (TextTable) StaticHTML

func (table TextTable) StaticHTML() string

StaticHTML renders a pure HTML table without JavaScript (Grid.js). This is suitable for PDF output where JavaScript may not execute.

func (TextTable) String

func (t TextTable) String() string

func (TextTable) WithoutEmptyColumns

func (t TextTable) WithoutEmptyColumns() TextTable

WithoutEmptyColumns returns a copy of the table with columns removed where every row has an empty value. Used by display renderers (ANSI, HTML, PDF) but not by data formats (CSV, Excel, JSON, YAML).

type TextTransformer

type TextTransformer func(t Textable) string
var TransformerANSI TextTransformer = func(t Textable) string {
	return t.ANSI()
}
var TransformerHTML TextTransformer = func(t Textable) string {
	return t.HTML()
}
var TransformerMarkdown TextTransformer = func(t Textable) string {
	return t.Markdown()
}
var TransformerString TextTransformer = func(t Textable) string {
	return t.String()
}

type TextTree

type TextTree struct {
	Node     Textable
	Children []TextTree
	// contains filtered or unexported fields
}

func NewTree

func NewTree[T TreeNode](nodes ...T) TextTree

func (TextTree) ANSI

func (tt TextTree) ANSI() string

func (TextTree) HTML

func (tt TextTree) HTML() string

func (TextTree) Markdown

func (tt TextTree) Markdown() string

func (TextTree) StaticHTML

func (tt TextTree) StaticHTML() string

StaticHTML renders the tree as static HTML without JavaScript. This is suitable for PDF output where JavaScript may not execute.

func (TextTree) String

func (tt TextTree) String() string

func (TextTree) Visit

func (tt TextTree) Visit(visitor VisitorFunc) bool

type Textable

type Textable interface {
	String() string   // Plain text representation
	ANSI() string     // ANSI colored terminal output
	HTML() string     // HTML formatted output
	Markdown() string // Markdown formatted output
}

Textable interface defines the standard text rendering methods for any type that can be rendered to multiple output formats

func Badge

func Badge(label string, classes ...string) Textable

func CompactList

func CompactList[T any](items []T) Textable

type Theme

type Theme struct {
	Primary   lipgloss.Color
	Secondary lipgloss.Color
	Success   lipgloss.Color
	Warning   lipgloss.Color
	Error     lipgloss.Color
	Info      lipgloss.Color
	Muted     lipgloss.Color
}

Theme provides a consistent color palette for semantic styling across different UI states (success, error, warning, etc.).

func AutoTheme

func AutoTheme() Theme

AutoTheme selects an appropriate theme by detecting terminal capabilities and background color, falling back to NoTTYTheme for non-interactive output.

func DarkTheme

func DarkTheme() Theme

func DefaultTheme

func DefaultTheme() Theme

func LightTheme

func LightTheme() Theme

func NoTTYTheme

func NoTTYTheme() Theme

NoTTYTheme provides colorless output suitable for pipes and non-interactive contexts.

type TreeMixin

type TreeMixin interface {
	Tree() TreeNode
}

TreeMixin allows types to provide tree representation without being TreeNodes themselves. This is useful for data types that need tree formatting but aren't primarily tree structures.

type TreeNode

type TreeNode interface {
	Pretty() Text
	GetChildren() []TreeNode
}

TreeNode defines the interface for hierarchical tree structures. Implementations provide formatted content and child relationships for tree rendering.

func FilterTreeNode

func FilterTreeNode(node TreeNode, filterExpr string) (TreeNode, error)

FilterTreeNode recursively filters tree nodes using a CEL expression. Field values from node content are injected directly into the CEL context. Returns filtered tree or error if CEL expression is invalid.

func NewConcreteTree

func NewConcreteTree(nodes ...TreeNode) TreeNode

type TreeOptions

type TreeOptions struct {
	ShowIcons      bool            `json:"show_icons,omitempty" yaml:"show_icons,omitempty"`
	IndentSize     int             `json:"indent_size,omitempty" yaml:"indent_size,omitempty"`
	UseUnicode     bool            `json:"use_unicode,omitempty" yaml:"use_unicode,omitempty"`
	Compact        bool            `json:"compact,omitempty" yaml:"compact,omitempty"`
	MaxDepth       int             `json:"max_depth,omitempty" yaml:"max_depth,omitempty"`
	CollapsedNodes map[string]bool `json:"collapsed_nodes,omitempty" yaml:"collapsed_nodes,omitempty"`
	// Prefix characters for tree rendering
	BranchPrefix   string `json:"branch_prefix,omitempty" yaml:"branch_prefix,omitempty"`
	LastPrefix     string `json:"last_prefix,omitempty" yaml:"last_prefix,omitempty"`
	IndentPrefix   string `json:"indent_prefix,omitempty" yaml:"indent_prefix,omitempty"`
	ContinuePrefix string `json:"continue_prefix,omitempty" yaml:"continue_prefix,omitempty"`
}

TreeOptions controls tree rendering behavior including visual styling, depth limits, and character sets for drawing tree connections.

func ASCIITreeOptions

func ASCIITreeOptions() *TreeOptions

ASCIITreeOptions creates configuration for ASCII-only tree rendering, suitable for environments without Unicode support.

func DefaultTreeOptions

func DefaultTreeOptions() *TreeOptions

DefaultTreeOptions creates configuration for Unicode tree rendering with standard indentation and unlimited depth.

type TypedList

type TypedList []TypedValue

func NewTypedList

func NewTypedList(items ...TypedValue) TypedList

NewTypedList creates a new TypedList from a variadic list of TypedValues

func (TypedList) ANSI

func (tl TypedList) ANSI() string

func (TypedList) HTML

func (tl TypedList) HTML() string

func (TypedList) Markdown

func (tl TypedList) Markdown() string

func (TypedList) MarkdownSlack

func (tl TypedList) MarkdownSlack() string

func (TypedList) String

func (tl TypedList) String() string

func (TypedList) Value

func (tl TypedList) Value() Textable

type TypedMap

type TypedMap map[string]TypedValue

func NewTypedMap

func NewTypedMap(pairs map[string]TypedValue) TypedMap

NewTypedMap creates a new TypedMap from key-value pairs

func (TypedMap) ANSI

func (tm TypedMap) ANSI() string

func (TypedMap) HTML

func (tm TypedMap) HTML() string

func (TypedMap) Markdown

func (tm TypedMap) Markdown() string

func (TypedMap) MarkdownSlack

func (tm TypedMap) MarkdownSlack() string

func (TypedMap) String

func (tm TypedMap) String() string

func (TypedMap) Value

func (tm TypedMap) Value() Textable

type TypedValue

type TypedValue struct {
	Textable   Textable
	Slice      *TextList
	Map        *TextMap
	TypedMap   *TypedMap
	TypedList  *TypedList
	Table      *TextTable
	Tree       *TextTree
	IsCircular bool
	FieldMeta  *FieldMeta // Metadata for rendering hints
}

func NewTypedValue

func NewTypedValue(o any) TypedValue

func TryTypedValue

func TryTypedValue(o any) *TypedValue

func (TypedValue) ANSI

func (tv TypedValue) ANSI() string

func (TypedValue) FirstTable

func (tv TypedValue) FirstTable() *TextTable

func (TypedValue) HTML

func (tv TypedValue) HTML() string

func (TypedValue) Markdown

func (tv TypedValue) Markdown() string

func (TypedValue) MarkdownSlack

func (tv TypedValue) MarkdownSlack() string

func (TypedValue) String

func (tv TypedValue) String() string

func (TypedValue) Value

func (tv TypedValue) Value() Textable

func (TypedValue) Visit

func (tv TypedValue) Visit(visitor VisitorFunc) bool

type VisitorFunc

type VisitorFunc func(TypedValue) bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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