tarang

package module
v0.0.0-...-edd724d Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 8 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

Tarang

Tarang is a Go library for animating text in terminals.
Give it a string and an effect, then draw each frame from your own loop or a Bubble Tea v2 app.

Install

Use Go 1.24 or later. Run this in your Go module.

go get github.com/vyrx-dev/tarang

Quick start

Save this as main.go and run go run . in an ANSI-capable terminal.

package main

import (
	"fmt"
	"time"

	"github.com/vyrx-dev/tarang"
	"github.com/vyrx-dev/tarang/effects"
)

func main() {
	const step = time.Second / 30
	p := tarang.New("Hello, Tarang!", effects.Typewriter(), tarang.FromEnv())
	fmt.Print(p.View())
	for !p.Done() {
		time.Sleep(step)
		p.Advance(step)
		fmt.Printf("\r%s", p.View())
	}
	fmt.Println()
}

Showcase

See every effect in an interactive terminal gallery:

cd adapters/bubbletea && go run ./examples/showcase

Documentation

Credits and licenses

TerminalTextEffects inspired many of the visuals. Tarang implements them independently. The easing curves follow Robert Penner's equations.

Tarang is MIT-licensed. See LICENSE and the dependency license notices.

Documentation

Overview

Package tarang animates text inside terminal user interfaces.

Core types are pure, deterministic, and host-agnostic: advance time via Player.Advance and render into any TUI loop with Player.View, Player.AppendANSI, or Player.Frame.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Attr

type Attr uint8

Attr is a bit set of text attributes emitted as SGR parameters.

const (
	// AttrBold renders bold text (SGR 1).
	AttrBold Attr = 1 << iota
	// AttrDim renders faint text (SGR 2).
	AttrDim
	// AttrItalic renders italic text (SGR 3).
	AttrItalic
	// AttrUnderline renders underlined text (SGR 4).
	AttrUnderline
	// AttrReverse swaps foreground and background (SGR 7).
	AttrReverse
)

type Cell

type Cell struct {
	Rune  rune
	Extra string
	Width uint8 // 0 = wide continuation, 1 = narrow, 2 = wide
	Style Style
}

Cell is one grid position in a Frame.

Width is 1 for a normal cell, 2 for the leading half of a wide glyph, and 0 for the continuation cell that a wide glyph owns at the next column.

type Color

type Color struct {
	R, G, B uint8
	Set     bool
}

Color is an RGB color with an explicit set flag.

The zero Color is unset and renders as the terminal default. Use RGB or Hex to construct a set color.

func Hex

func Hex(s string) (Color, bool)

Hex parses a color written as six hexadecimal digits with an optional leading "#". Any other length, an extra prefix, whitespace, or a non-hex digit yields the zero Color and false.

func MustHex

func MustHex(s string) Color

MustHex parses s like Hex and panics when s is not a valid hex color.

func RGB

func RGB(r, g, b uint8) Color

RGB returns a set Color from its red, green, and blue channels.

func (Color) Lerp

func (c Color) Lerp(to Color, t float64) Color

Lerp interpolates from c to to by t, clamped to [0, 1].

An unset side is treated as opaque black. When both sides are unset the result is unset; otherwise the result is always set.

func (Color) ToANSI16

func (c Color) ToANSI16() uint8

ToANSI16 returns the nearest standard 16-color palette index (0..15) by squared Euclidean distance. The lowest index wins ties.

func (Color) ToANSI256

func (c Color) ToANSI256() uint8

ToANSI256 returns the nearest XTerm 256-color palette index.

The nearest entry of the 6x6x6 color cube and the nearest entry of the 24-step grayscale ramp are compared by squared Euclidean distance; the cube wins ties. The result is in the range 16..255.

type ColorProfile

type ColorProfile uint8

ColorProfile selects how a Frame converts colors to SGR sequences.

const (
	// ProfileTrueColor emits 24-bit SGR sequences (38;2;r;g;b / 48;2;r;g;b).
	ProfileTrueColor ColorProfile = iota
	// ProfileANSI256 emits 8-bit SGR sequences (38;5;n / 48;5;n).
	ProfileANSI256
	// ProfileANSI16 emits 4-bit SGR sequences (30-37, 90-97 / 40-47, 100-107).
	ProfileANSI16
	// ProfileNone suppresses colors while preserving text attributes.
	ProfileNone
)

type Effect

type Effect interface {
	// Init prepares the effect for target with a deterministic seed.
	Init(target Target, seed uint64)
	// Step advances the effect by dt and draws into dst, reporting whether the
	// frame changed and whether the effect has finished.
	Step(dt time.Duration, dst *Frame) (changed, done bool)
	// Reset rewinds the effect to its post-Init state.
	Reset()
}

Effect animates a Target over time by drawing into frames.

An Effect is a single-goroutine state machine. Init prepares it for a target and seed, Step advances it by dt, and Reset rewinds it to its post-Init state without reallocating.

func Parallel

func Parallel(effects ...Effect) Effect

Parallel returns an effect that advances effects concurrently and composites their frames in argument order.

Each child draws into a reusable scratch frame, so steady-state steps do not allocate. Cells that are empty or styled as blank are transparent, letting later children draw over earlier ones. Nil effects are ignored.

Example
package main

import (
	"fmt"
	"time"

	"github.com/vyrx-dev/tarang"
	"github.com/vyrx-dev/tarang/effects"
)

// advance runs a player to completion with a fixed step.
func advance(p *tarang.Player) {
	for !p.Done() {
		p.Advance(100 * time.Millisecond)
	}
}

func main() {
	p := tarang.New("go",
		tarang.Parallel(
			effects.Waves(),
			effects.ColorShift(),
		),
		tarang.WithColorProfile(tarang.ProfileNone),
		tarang.WithSeed(42),
	)
	advance(p)
	fmt.Println(p.View())
}
Output:
go

func Sequence

func Sequence(effects ...Effect) Effect

Sequence returns an effect that plays effects one after another.

Each child is initialized with the parent seed plus its index. A finished child immediately hands over to the next one, which renders its starting state in the same step. Nil effects are ignored.

Example
package main

import (
	"fmt"
	"time"

	"github.com/vyrx-dev/tarang"
	"github.com/vyrx-dev/tarang/effects"
)

// advance runs a player to completion with a fixed step.
func advance(p *tarang.Player) {
	for !p.Done() {
		p.Advance(100 * time.Millisecond)
	}
}

func main() {
	p := tarang.New("go",
		tarang.Sequence(
			effects.Wipe(effects.WithWipeDirection(effects.LeftToRight)),
			effects.Slide(effects.WithSlideDirection(effects.TopToBottom)),
		),
		tarang.WithColorProfile(tarang.ProfileNone),
		tarang.WithSeed(42),
	)
	advance(p)
	fmt.Println(p.View())
}
Output:
go

type Frame

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

Frame is a flat, reusable 2D cell grid that effects draw into and hosts render as ANSI.

A Frame is not safe for concurrent use. Its buffer stays valid until the next mutating call.

func NewFrame

func NewFrame(width, height int) *Frame

NewFrame returns a frame of width by height cells, cleared to spaces.

Negative dimensions clamp to zero.

func (*Frame) AppendANSI

func (f *Frame) AppendANSI(dst []byte, profile ColorProfile) []byte

AppendANSI appends the frame as ANSI text to dst and returns the result.

Each line is emitted without a trailing newline. Styles are tracked across cells so only changes are emitted, with a reset before each newline and at the end of the frame when a style is active. Under ProfileANSI256 and ProfileANSI16, colors that downgrade to the same palette index count as equal.

func (*Frame) At

func (f *Frame) At(x, y int) Cell

At returns the cell at x, y, or the zero Cell when out of bounds.

func (*Frame) Clear

func (f *Frame) Clear(style Style)

Clear fills every cell with a space in the given style.

func (*Frame) Height

func (f *Frame) Height() int

Height returns the frame height in cells.

func (*Frame) PlainString

func (f *Frame) PlainString() string

PlainString returns the frame as uncolored text, with lines separated by a newline and no trailing newline. Wide glyphs appear once and empty cells render as a space.

func (*Frame) Resize

func (f *Frame) Resize(width, height int)

Resize changes the frame dimensions, clearing all cells to spaces.

Negative dimensions clamp to zero. The cell buffer is reused when it has enough capacity.

func (*Frame) Set

func (f *Frame) Set(x, y int, c Cell)

Set writes c at x, y and keeps wide glyphs whole.

Out-of-bounds writes, zero-width cells, and wide cells that do not fit on the row are no-ops. Writing over either half of an existing wide glyph clears the other half to a space.

func (*Frame) SetGlyph

func (f *Frame) SetGlyph(x, y int, g Glyph, style Style)

SetGlyph writes g at x, y with the given style.

func (*Frame) SetRune

func (f *Frame) SetRune(x, y int, r rune, style Style)

SetRune writes a narrow single-rune cell at x, y.

func (*Frame) String

func (f *Frame) String(profile ColorProfile) string

String returns the frame as ANSI text.

func (*Frame) Width

func (f *Frame) Width() int

Width returns the frame width in cells.

func (*Frame) WriteANSI

func (f *Frame) WriteANSI(w io.Writer, profile ColorProfile) (int, error)

WriteANSI writes the frame as ANSI text to w.

type Glyph

type Glyph struct {
	X, Y  int
	Rune  rune   // non-zero for single-rune grapheme clusters
	Extra string // non-empty only for multi-rune grapheme clusters (Rune == 0)
	Width uint8  // 1 (narrow) or 2 (wide)
	Index int    // 0-based reading-order index among visible glyphs
}

Glyph is one visible grapheme cluster placed on a Target grid.

Single-rune clusters carry their rune in Rune and leave Extra empty. Multi-rune clusters (combining marks, ZWJ sequences) leave Rune zero and store the whole cluster in Extra.

type Gradient

type Gradient struct {
	Stops []Color
}

Gradient interpolates between ordered color stops.

func NewGradient

func NewGradient(stops ...Color) Gradient

NewGradient returns a Gradient over stops, copying the slice so later mutations of stops do not affect the gradient.

func (Gradient) At

func (g Gradient) At(t float64) Color

At returns the color at position t, clamped to [0, 1].

It returns the zero Color for no stops and the only stop for one stop.

type Option

type Option func(*playerConfig)

Option configures a Player at construction time.

Options apply left to right, so later options override earlier ones.

func EnvOptions

func EnvOptions(lookup func(string) (string, bool)) []Option

EnvOptions translates environment degradation hints into [Option]s.

A non-empty NO_COLOR disables color, a REDUCED_MOTION value other than "0" or "false" skips animation, and TERM=dumb disables both. The returned options apply in that order, so options appended after them take precedence.

func FromEnv

func FromEnv() Option

FromEnv returns an Option that applies EnvOptions using the process environment.

Place it first so explicit options that follow still win.

Example
package main

import (
	"fmt"
	"os"

	"github.com/vyrx-dev/tarang"
	"github.com/vyrx-dev/tarang/effects"
)

// setEnv applies key/value pairs and returns a restore function.
func setEnv(kv ...string) func() {
	type oldEnv struct {
		value string
		set   bool
	}
	old := make([]oldEnv, len(kv)/2)
	for i := range old {
		old[i].value, old[i].set = os.LookupEnv(kv[i*2])
		_ = os.Setenv(kv[i*2], kv[i*2+1])
	}
	return func() {
		for i, o := range old {
			if o.set {
				_ = os.Setenv(kv[i*2], o.value)
				continue
			}
			_ = os.Unsetenv(kv[i*2])
		}
	}
}

func main() {
	defer setEnv("NO_COLOR", "1", "TERM", "dumb")()

	p := tarang.New("ok", effects.Typewriter(), tarang.FromEnv())
	fmt.Println(p.Done())
	fmt.Println(p.View())
}
Output:
true
ok

func WithBaseStyle

func WithBaseStyle(s Style) Option

WithBaseStyle sets the style used for static and reduced-motion text.

func WithColorProfile

func WithColorProfile(p ColorProfile) Option

WithColorProfile sets the color profile used to render frames.

func WithMaxStep

func WithMaxStep(dt time.Duration) Option

WithMaxStep clamps the largest dt that Player.Advance applies in one call.

A non-positive dt is ignored, keeping the current clamp (100ms by default).

func WithReducedMotion

func WithReducedMotion(on bool) Option

WithReducedMotion renders the final text immediately instead of animating.

func WithSeed

func WithSeed(seed uint64) Option

WithSeed sets the deterministic seed passed to Effect.Init.

func WithSize

func WithSize(width, height int) Option

WithSize lays the text out on a width by height grid.

A non-positive dimension keeps the text's natural size on that axis.

type Player

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

Player drives an Effect over time and renders its frames as ANSI text.

A Player is a single-goroutine state machine with no internal timers. A finished or paused Player costs nothing per host frame: Advance returns immediately and View returns the cached string.

func New

func New(text string, fx Effect, opts ...Option) *Player

New returns a Player that animates text with fx.

A nil fx or reduced motion draws the final text immediately and starts done. Nil options are ignored.

Example
package main

import (
	"fmt"
	"time"

	"github.com/vyrx-dev/tarang"
	"github.com/vyrx-dev/tarang/effects"
)

// advance runs a player to completion with a fixed step.
func advance(p *tarang.Player) {
	for !p.Done() {
		p.Advance(100 * time.Millisecond)
	}
}

func main() {
	p := tarang.New("tarang", effects.Typewriter(),
		tarang.WithColorProfile(tarang.ProfileNone),
		tarang.WithSeed(42),
	)
	advance(p)
	fmt.Println(p.View())
}
Output:
tarang

func (*Player) Advance

func (p *Player) Advance(dt time.Duration) bool

Advance moves the animation forward by dt and reports whether the frame changed.

dt is clamped to the configured maximum step. Paused or finished players ignore the call and return false.

func (*Player) AppendANSI

func (p *Player) AppendANSI(dst []byte) []byte

AppendANSI appends the current frame as ANSI text to dst without allocating when dst has enough capacity.

func (*Player) Done

func (p *Player) Done() bool

Done reports whether the animation has finished or was never started.

func (*Player) Elapsed

func (p *Player) Elapsed() time.Duration

Elapsed returns the animation time accumulated by Advance.

func (*Player) Frame

func (p *Player) Frame() *Frame

Frame returns the player's cell grid.

The pointer is valid until the next mutating call.

func (*Player) Pause

func (p *Player) Pause()

Pause suspends Advance until Player.Resume.

func (*Player) Paused

func (p *Player) Paused() bool

Paused reports whether Advance is currently suspended.

func (*Player) Reset

func (p *Player) Reset()

Reset rewinds the effect and clears elapsed time, keeping text, size, and the paused state.

func (*Player) Resize

func (p *Player) Resize(width, height int)

Resize re-lays out the text on a width by height grid.

A non-positive dimension restores natural sizing on that axis. A finished or static player redraws the final text; a running player restarts its effect at the new size. The paused state is preserved.

func (*Player) Resume

func (p *Player) Resume()

Resume continues a paused player.

func (*Player) SetText

func (p *Player) SetText(text string)

SetText replaces the animated text and restarts the animation.

Size constraints and the paused state are preserved.

func (*Player) Size

func (p *Player) Size() (width, height int)

Size returns the current frame width and height in cells.

func (*Player) View

func (p *Player) View() string

View returns the current frame as ANSI text.

The string is rebuilt only when the frame changed, so repeated calls between advances allocate nothing.

func (*Player) WriteANSI

func (p *Player) WriteANSI(w io.Writer) (int, error)

WriteANSI writes the current frame as ANSI text to w.

type Style

type Style struct {
	FG, BG Color
	Attr   Attr
}

Style is the foreground color, background color, and attribute set of a cell. The zero Style means default colors and no attributes.

func (Style) IsZero

func (s Style) IsZero() bool

IsZero reports whether s sets no colors and no attributes.

func (Style) WithAttr

func (s Style) WithAttr(a Attr) Style

WithAttr returns a copy of s with attribute a added to the existing set.

func (Style) WithBG

func (s Style) WithBG(c Color) Style

WithBG returns a copy of s with background color c.

func (Style) WithFG

func (s Style) WithFG(c Color) Style

WithFG returns a copy of s with foreground color c.

type Target

type Target struct {
	Width, Height int
	Glyphs        []Glyph
	Text          string // original raw input passed to ParseTarget
}

Target is parsed text laid out on a fixed grid of glyphs.

Spaces, controls, and glyphs clipped by the grid bounds are not emitted, so Glyphs contains only cells an effect needs to draw.

func ParseTarget

func ParseTarget(text string, width, height int) Target

ParseTarget lays out text on a width by height grid using UAX #29 grapheme clusters and UAX #11 display widths.

Carriage returns are normalized to newlines, tabs expand to four spaces, and C0 controls and DEL are dropped. A non-positive width or height uses the text's natural bound on that axis. Text is only clipped, never wrapped.

Directories

Path Synopsis
Package ease provides standard easing curves for Tarang effects.
Package ease provides standard easing curves for Tarang effects.
Package effects provides ready-to-use text animation effects for tarang.
Package effects provides ready-to-use text animation effects for tarang.
examples
standalone command
Command standalone animates a multi-line banner in the terminal.
Command standalone animates a multi-line banner in the terminal.
scripts
gencasts command
Command gencasts renders asciinema v2 previews for every built-in effect.
Command gencasts renders asciinema v2 previews for every built-in effect.

Jump to

Keyboard shortcuts

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