table

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2025 License: MIT Imports: 5 Imported by: 286

Documentation

Index

Examples

Constants

View Source
const HeaderRow int = -1

HeaderRow denotes the header's row index used when rendering headers. Use this value when looking to customize header styles in StyleFunc.

Variables

This section is empty.

Functions

func DefaultStyles

func DefaultStyles(_, _ int) lipgloss.Style

DefaultStyles is a TableStyleFunc that returns a new Style with no attributes.

Types

type Data

type Data interface {
	// At returns the contents of the cell at the given index.
	At(row, cell int) string

	// Rows returns the number of rows in the table.
	Rows() int

	// Columns returns the number of columns in the table.
	Columns() int
}

Data is the interface that wraps the basic methods of a table model.

type Filter

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

Filter applies a filter on some data.

func NewFilter

func NewFilter(data Data) *Filter

NewFilter initializes a new Filter.

func (*Filter) At

func (m *Filter) At(row, cell int) string

At returns the row at the given index.

func (*Filter) Columns

func (m *Filter) Columns() int

Columns returns the number of columns in the table.

func (*Filter) Filter

func (m *Filter) Filter(f func(row int) bool) *Filter

Filter applies the given filter function to the data.

func (*Filter) Rows

func (m *Filter) Rows() int

Rows returns the number of rows in the table.

type StringData

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

StringData is a string-based implementation of the Data interface.

func NewStringData

func NewStringData(rows ...[]string) *StringData

NewStringData creates a new StringData with the given number of columns.

func (*StringData) Append

func (m *StringData) Append(row []string)

Append appends the given row to the table.

func (*StringData) At

func (m *StringData) At(row, cell int) string

At returns the contents of the cell at the given index.

func (*StringData) Columns

func (m *StringData) Columns() int

Columns returns the number of columns in the table.

func (*StringData) Item

func (m *StringData) Item(rows ...string) *StringData

Item appends the given row to the table.

func (*StringData) Rows

func (m *StringData) Rows() int

Rows returns the number of rows in the table.

type StyleFunc

type StyleFunc func(row, col int) lipgloss.Style

StyleFunc is the style function that determines the style of a Cell.

It takes the row and column of the cell as an input and determines the lipgloss Style to use for that cell position.

Example:

t := table.New().
    Headers("Name", "Age").
    Row("Kini", 4).
    Row("Eli", 1).
    Row("Iris", 102).
    StyleFunc(func(row, col int) lipgloss.Style {
        switch {
           case row == 0:
               return HeaderStyle
           case row%2 == 0:
               return EvenRowStyle
           default:
               return OddRowStyle
           }
    })

type Table

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

Table is a type for rendering tables.

func New

func New() *Table

New returns a new Table that can be modified through different attributes.

By default, a table has no border, no styling, and no rows.

func (*Table) Border

func (t *Table) Border(border lipgloss.Border) *Table

Border sets the table border.

func (*Table) BorderBottom

func (t *Table) BorderBottom(v bool) *Table

BorderBottom sets the bottom border.

func (*Table) BorderColumn

func (t *Table) BorderColumn(v bool) *Table

BorderColumn sets the column border separator.

func (*Table) BorderHeader

func (t *Table) BorderHeader(v bool) *Table

BorderHeader sets the header separator border.

func (*Table) BorderLeft

func (t *Table) BorderLeft(v bool) *Table

BorderLeft sets the left border.

func (*Table) BorderRight

func (t *Table) BorderRight(v bool) *Table

BorderRight sets the right border.

func (*Table) BorderRow

func (t *Table) BorderRow(v bool) *Table

BorderRow sets the row border separator.

func (*Table) BorderStyle

func (t *Table) BorderStyle(style lipgloss.Style) *Table

BorderStyle sets the style for the table border.

func (*Table) BorderTop

func (t *Table) BorderTop(v bool) *Table

BorderTop sets the top border.

func (*Table) ClearRows

func (t *Table) ClearRows() *Table

ClearRows clears the table rows.

func (*Table) Data

func (t *Table) Data(data Data) *Table

Data sets the table data.

func (*Table) Headers

func (t *Table) Headers(headers ...string) *Table

Headers sets the table headers.

func (*Table) Height

func (t *Table) Height(h int) *Table

Height sets the table height.

func (*Table) Offset

func (t *Table) Offset(o int) *Table

Offset sets the table rendering offset.

Warning: you may declare Offset only after setting Rows. Otherwise it will be ignored.

func (*Table) Render

func (t *Table) Render() string

Render returns the table as a string.

func (*Table) Row

func (t *Table) Row(row ...string) *Table

Row appends a row to the table data.

func (*Table) Rows

func (t *Table) Rows(rows ...[]string) *Table

Rows appends rows to the table data.

func (*Table) String

func (t *Table) String() string

String returns the table as a string.

func (*Table) StyleFunc

func (t *Table) StyleFunc(style StyleFunc) *Table

StyleFunc sets the style for a cell based on it's position (row, column).

func (*Table) Width

func (t *Table) Width(w int) *Table

Width sets the table width, this auto-sizes the columns to fit the width by either expanding or contracting the widths of each column as a best effort approach.

func (*Table) Wrap added in v1.1.0

func (t *Table) Wrap(w bool) *Table

Wrap dictates whether or not the table content should wrap.

Example
// LongTextDifferentLanguages
headers := []string{"Hello", "你好", "مرحبًا", "안녕하세요"}
data := [][]string{
	{
		"Lorem ipsum dolor sit amet, regione detracto eos an. Has ei quidam hendrerit intellegebat, id tamquam iudicabit necessitatibus ius, at errem officiis hendrerit mei. Exerci noster at has, sit id tota convenire, vel ex rebum inciderint liberavisse. Quaeque delectus corrumpit cu cum.",
		`耐許ヱヨカハ調出あゆ監件び理別よン國給災レホチ権輝モエフ会割もフ響3現エツ文時しだびほ経機ムイメフ敗文ヨク現義なさド請情ゆじょて憶主管州けでふく。排ゃわつげ美刊ヱミ出見ツ南者オ抜豆ハトロネ論索モネニイ任償スヲ話破リヤヨ秒止口イセソス止央のさ食周健でてつだ官送ト読聴遊容ひるべ。際ぐドらづ市居ネムヤ研校35岩6繹ごわク報拐イ革深52球ゃレスご究東スラ衝3間ラ録占たス。
禁にンご忘康ざほぎル騰般ねど事超スんいう真表何カモ自浩ヲシミ図客線るふ静王ぱーま写村月掛焼詐面ぞゃ。昇強ごントほ価保キ族85岡モテ恋困ひりこな刊並せご出来ぼぎむう点目ヲウ止環公ニレ事応タス必書タメムノ当84無信升ちひょ。価ーぐ中客テサ告覧ヨトハ極整ラ得95稿はかラせ江利ス宏丸霊ミ考整ス静将ず業巨職ノラホ収嗅ざな。`,
		"شيء قد للحكومة والكوري الأوروبيّون, بوابة تعديل واعتلاء ضرب بـ. إذ أسر اتّجة اعلان, ٣٠ اكتوبر العصبة استمرار ومن. أفاق للسيطرة التاريخ، مع بحث, كلّ اتّجة القوى مع. فبعد ايطاليا، تم حتى, لكل تم جسيمة الإحتفاظ وباستثناء, عل فرنسا وانتهاءً الإقتصادية عرض. ونتج دأبوا إحكام بال إذ. لغات عملية وتم مع, وصل بداية وبغطاء البرية بل, أي قررت بلاده فكانت حدى",
		"版応道潟部中幕爆営報門案名見壌府。博健必権次覧編仕断青場内凄新東深簿代供供。守聞書神秀同浜東波恋闘秀。未格打好作器来利阪持西焦朝三女。権幽問季負娘購合旧資健載員式活陸。未倍校朝遺続術吉迎暮広知角亡志不説空住。法省当死年勝絡聞方北投健。室分性山天態意画詳知浅方裁。変激伝阜中野品省載嗅闘額端反。中必台際造事寄民経能前作臓",
		"각급 선거관리위원회의 조직·직무범위 기타 필요한 사항은 법률로 정한다. 임시회의 회기는 30일을 초과할 수 없다. 국가는 여자의 복지와 권익의 향상을 위하여 노력하여야 한다. 국군의 조직과 편성은 법률로 정한다.",
	},
}

table := New().
	Headers(headers...).
	Rows(data...).
	StyleFunc(TableStyle).
	Width(80).
	Wrap(false)
fmt.Println(table.String())

table.Wrap(true)
fmt.Println(table.String())
Output:

╭──────────────┬───────────────┬───────────────┬───────────────┬───────────────╮
│    Hello     │     你好      │     مرحبًا     │  안녕하세요   │               │
├──────────────┼───────────────┼───────────────┼───────────────┼───────────────┤
│ Lorem ipsum… │ 耐許ヱヨカハ… │ شيء قد للحكو… │ 版応道潟部中… │ 각급 선거관…  │
╰──────────────┴───────────────┴───────────────┴───────────────┴───────────────╯
╭──────────────┬───────────────┬───────────────┬───────────────┬───────────────╮
│    Hello     │     你好      │     مرحبًا     │  안녕하세요   │               │
├──────────────┼───────────────┼───────────────┼───────────────┼───────────────┤
│ Lorem ipsum  │ 耐許ヱヨカハ  │ شيء قد        │ 版応道潟部中  │ 각급          │
│ dolor sit    │ 調出あゆ監件  │ للحكومة       │ 幕爆営報門案  │ 선거관리위원  │
│ amet,        │ び理別よン國  │ والكوري       │ 名見壌府。博  │ 회의          │
│ regione      │ 給災レホチ権  │ الأوروبيّون,   │ 健必権次覧編  │ 조직·직무범위 │
│ detracto eos │ 輝モエフ会割  │ بوابة تعديل   │ 仕断青場内凄  │ 기타 필요한   │
│ an. Has ei   │ もフ響3現エツ │ واعتلاء ضرب   │ 新東深簿代供  │ 사항은 법률로 │
│ quidam       │ 文時しだびほ  │ بـ. إذ أسر    │ 供。守聞書神  │ 정한다.       │
│ hendrerit    │ 経機ムイメフ  │ اتّجة اعلان,   │ 秀同浜東波恋  │ 임시회의      │
│ intellegebat │ 敗文ヨク現義  │ ٣٠ اكتوبر     │ 闘秀。未格打  │ 회기는 30일을 │
│ , id tamquam │ なさド請情ゆ  │ العصبة        │ 好作器来利阪  │ 초과할 수     │
│ iudicabit    │ じょて憶主管  │ استمرار ومن.  │ 持西焦朝三女  │ 없다. 국가는  │
│ necessitatib │ 州けでふく。  │ أفاق للسيطرة  │ 。権幽問季負  │ 여자의 복지와 │
│ us ius, at   │ 排ゃわつげ美  │ التاريخ، مع   │ 娘購合旧資健  │ 권익의 향상을 │
│ errem        │ 刊ヱミ出見ツ  │ بحث, كلّ اتّجة  │ 載員式活陸。  │ 위하여        │
│ officiis     │ 南者オ抜豆ハ  │ القوى مع.     │ 未倍校朝遺続  │ 노력하여야    │
│ hendrerit    │ トロネ論索モ  │ فبعد ايطاليا، │ 術吉迎暮広知  │ 한다. 국군의  │
│ mei. Exerci  │ ネニイ任償ス  │ تم حتى, لكل   │ 角亡志不説空  │ 조직과 편성은 │
│ noster at    │ ヲ話破リヤヨ  │ تم جسيمة      │ 住。法省当死  │ 법률로        │
│ has, sit id  │ 秒止口イセソ  │ الإحتفاظ      │ 年勝絡聞方北  │ 정한다.       │
│ tota         │ ス止央のさ食  │ وباستثناء, عل │ 投健。室分性  │               │
│ convenire,   │ 周健でてつだ  │ فرنسا وانتهاءً │ 山天態意画詳  │               │
│ vel ex rebum │ 官送ト読聴遊  │ الإقتصادية    │ 知浅方裁。変  │               │
│ inciderint   │ 容ひるべ。際  │ عرض. ونتج     │ 激伝阜中野品  │               │
│ liberavisse. │ ぐドらづ市居  │ دأبوا إحكام   │ 省載嗅闘額端  │               │
│ Quaeque      │ ネムヤ研校35  │ بال إذ. لغات  │ 反。中必台際  │               │
│ delectus     │ 岩6繹ごわク報 │ عملية وتم مع, │ 造事寄民経能  │               │
│ corrumpit cu │ 拐イ革深52球  │ وصل بداية     │ 前作臓        │               │
│ cum.         │ ゃレスご究東  │ وبغطاء البرية │               │               │
│              │ スラ衝3間ラ録 │ بل, أي قررت   │               │               │
│              │ 占たス。      │ بلاده فكانت   │               │               │
│              │ 禁にンご忘康  │ حدى           │               │               │
│              │ ざほぎル騰般  │               │               │               │
│              │ ねど事超スん  │               │               │               │
│              │ いう真表何カ  │               │               │               │
│              │ モ自浩ヲシミ  │               │               │               │
│              │ 図客線るふ静  │               │               │               │
│              │ 王ぱーま写村  │               │               │               │
│              │ 月掛焼詐面ぞ  │               │               │               │
│              │ ゃ。昇強ごン  │               │               │               │
│              │ トほ価保キ族8 │               │               │               │
│              │ 5岡モテ恋困ひ │               │               │               │
│              │ りこな刊並せ  │               │               │               │
│              │ ご出来ぼぎむ  │               │               │               │
│              │ う点目ヲウ止  │               │               │               │
│              │ 環公ニレ事応  │               │               │               │
│              │ タス必書タメ  │               │               │               │
│              │ ムノ当84無信  │               │               │               │
│              │ 升ちひょ。価  │               │               │               │
│              │ ーぐ中客テサ  │               │               │               │
│              │ 告覧ヨトハ極  │               │               │               │
│              │ 整ラ得95稿は  │               │               │               │
│              │ かラせ江利ス  │               │               │               │
│              │ 宏丸霊ミ考整  │               │               │               │
│              │ ス静将ず業巨  │               │               │               │
│              │ 職ノラホ収嗅  │               │               │               │
│              │ ざな。        │               │               │               │
╰──────────────┴───────────────┴───────────────┴───────────────┴───────────────╯

Jump to

Keyboard shortcuts

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