Skip to content
Caleb Bassi edited this page Nov 29, 2018 · 15 revisions

Widgets

termui ships with quite a few widgets that can be used to present data. Each widgets has unique fields, and all widgets inherit from termui.Block which allows updating fields such as BorderFg and BorderLabel.

	p := ui.NewParagraph("I'm a Paragraph")
	p.TextFgColor = ui.ColorWhite
	p.BorderLabel = "Text Box"
	p.BorderFg = ui.ColorCyan

	g := ui.NewGauge()
	g.Percent = 50
	g.BarColor = ui.ColorRed
	g.BorderLabel = "Gauge"
	g.BorderFg = ui.ColorWhite
	g.BorderLabelFg = ui.ColorCyan

Layout

Absolute layout

To position widgets absolutely, modify the fields X, Y, Height, and Width inherited from termui.Block.

	p.Height = 3
	p.Width = 50

	g.Width = 50
	g.Height = 3
	g.Y = 11

	ui.Render(p, g) // feel free to call Render, it's async and non-block

Note that components can be overlapped (I'd rather call this a feature...) with components being rendered from left to right.

Grid layout

grid

Grid layout uses a 12 columns grid system inspired by Bootstrap. The Grid is used by building a widget tree consisting of Rows and Cols.

	// build
	ui.Body.AddRows(
		ui.NewRow(
			ui.NewCol(6, 0, widget0),
			ui.NewCol(6, 0, widget1)),
		ui.NewRow(
			ui.NewCol(3, 0, widget2),
			ui.NewCol(3, 0, widget30, widget31, widget32),
			ui.NewCol(6, 0, widget4)))

	// calculate layout
	ui.Body.Align()

	ui.Render(ui.Body)

Events

termui provides event handling for keypresses, mouse actions, and screen resizing. termui.PollEvents() returns a channel that propogates Events originating from termbox. Events are detailed in events.go.

	draw := func() {
		...
	}

	for {
		select {
		case e := <-ui.PollEvents():
			switch e.ID {
			// press 'q' or 'C-c' to quit
			case "q", "<C-c>":
				ui.StopLoop()
			case "<MouseLeft>":
				payload := e.Payload.(ui.Mouse)
				x, y := payload.X, payload.Y
			case "<Resize>":
				payload := e.Payload.(ui.Resize)
				width, height := payload.Width, payload.Height
			}
			switch e.Type {
			// handle all key presses
			case ui.KeyboardEvent:
				eventID = e.ID // keypress string
			}
		// use Go's built-in tickers for updating and drawing data
		case <- time.NewTicker(time.Second).C:
			draw()
		}
	}

Custom Widgets

TODO

Clone this wiki locally