items.go

  1package list
  2
  3import "strings"
  4
  5// RenderedItem represents a rendered item as a string.
  6type RenderedItem interface {
  7	Item
  8	// Height returns the height of the rendered item in lines.
  9	Height() int
 10}
 11
 12// Item represents a single item in the [List] component.
 13type Item interface {
 14	// ID returns the unique identifier of the item.
 15	ID() string
 16	// Render returns the rendered string representation of the item.
 17	Render() string
 18}
 19
 20// StringItem is a simple implementation of the [Item] interface that holds a
 21// string.
 22type StringItem struct {
 23	ItemID  string
 24	Content string
 25}
 26
 27// NewStringItem creates a new StringItem with the given ID and content.
 28func NewStringItem(id, content string) StringItem {
 29	return StringItem{
 30		ItemID:  id,
 31		Content: content,
 32	}
 33}
 34
 35// ID returns the unique identifier of the string item.
 36func (s StringItem) ID() string {
 37	return s.ItemID
 38}
 39
 40// Render returns the rendered string representation of the string item.
 41func (s StringItem) Render() string {
 42	return s.Content
 43}
 44
 45// Gap is [GapItem] to be used as a vertical gap in the list.
 46var Gap = GapItem{}
 47
 48// GapItem is a one-line vertical gap in the list.
 49type GapItem struct{}
 50
 51// ID returns the unique identifier of the gap.
 52func (g GapItem) ID() string {
 53	return "gap"
 54}
 55
 56// Render returns the rendered string representation of the gap.
 57func (g GapItem) Render() string {
 58	return "\n"
 59}
 60
 61// Height returns the height of the rendered gap in lines.
 62func (g GapItem) Height() int {
 63	return 1
 64}
 65
 66// CachedItem wraps an Item and caches its rendered string representation and height.
 67type CachedItem struct {
 68	item     Item
 69	rendered string
 70	height   int
 71}
 72
 73// NewCachedItem creates a new CachedItem from the given Item.
 74func NewCachedItem(item Item, rendered string) CachedItem {
 75	height := 1 + strings.Count(rendered, "\n")
 76	return CachedItem{
 77		item:     item,
 78		rendered: rendered,
 79		height:   height,
 80	}
 81}
 82
 83// ID returns the unique identifier of the cached item.
 84func (c CachedItem) ID() string {
 85	return c.item.ID()
 86}
 87
 88// Item returns the underlying Item.
 89func (c CachedItem) Item() Item {
 90	return c.item
 91}
 92
 93// Render returns the cached rendered string representation of the item.
 94func (c CachedItem) Render() string {
 95	return c.rendered
 96}
 97
 98// Height returns the cached height of the rendered item in lines.
 99func (c CachedItem) Height() int {
100	return c.height
101}