From ea93b82af1bca656f18d50f03f82c3a18e1c77ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szymon=20B=C5=82aszczy=C5=84ski?= Date: Sun, 2 May 2021 15:25:54 +0200 Subject: [PATCH] New input widget Same as `Paragraph`, but for input :) --- theme.go | 9 ++++++ widgets/input.go | 84 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 widgets/input.go diff --git a/theme.go b/theme.go index 60745f4..f068604 100644 --- a/theme.go +++ b/theme.go @@ -35,6 +35,7 @@ type RootTheme struct { List ListTheme Tree TreeTheme Paragraph ParagraphTheme + Input InputTheme PieChart PieChartTheme Sparkline SparklineTheme StackedBarChart StackedBarChartTheme @@ -77,6 +78,10 @@ type ParagraphTheme struct { Text Style } +type InputTheme struct { + Text Style +} + type PieChartTheme struct { Slices []Color } @@ -121,6 +126,10 @@ var Theme = RootTheme{ Text: NewStyle(ColorWhite), }, + Input: InputTheme{ + Text: NewStyle(ColorWhite), + }, + PieChart: PieChartTheme{ Slices: StandardColors, }, diff --git a/widgets/input.go b/widgets/input.go new file mode 100644 index 0000000..0c6da69 --- /dev/null +++ b/widgets/input.go @@ -0,0 +1,84 @@ +// Copyright 2021 Szymon Błaszczyński . All rights reserved. +// Use of this source code is governed by a MIT license that can +// be found in the LICENSE file. + +package widgets + +import ( + "image" + + . "github.com/gizak/termui/v3" +) + +type Input struct { + Block + Text string + TextStyle Style + WrapText bool + focusing bool +} + +// Create new Input widget. Somehow similar to Paragraph. +func NewInput() *Input { + return &Input{ + Block: *NewBlock(), + TextStyle: Theme.Input.Text, + WrapText: true, + focusing: false, + Text: "", + } +} + +func (self *Input) Draw(buf *Buffer) { + self.Block.Draw(buf) + + cells := ParseStyles(self.Text, self.TextStyle) + if self.WrapText { + cells = WrapCells(cells, uint(self.Inner.Dx())) + } + + rows := SplitCells(cells, '\n') + + for y, row := range rows { + if y+self.Inner.Min.Y >= self.Inner.Max.Y { + break + } + row = TrimCells(row, self.Inner.Dx()) + for _, cx := range BuildCellWithXArray(row) { + x, cell := cx.X, cx.Cell + buf.SetCell(cell, image.Pt(x, y).Add(self.Inner.Min)) + } + } +} + +// Focus on input field and start typing. +// Best used with go routine 'go inputField.Focus()' +func (i *Input) Focus() { + i.focusing = true +Loop: + for { + events := PollEvents() + e := <-events + if e.Type == KeyboardEvent { + switch e.ID { + case "": + if len(i.Text) > 0 { + i.Text = i.Text[:len(i.Text)-1] + Render(i) + } + case "", "C-c", "": + i.focusing = false + break Loop + case "": + i.Text = i.Text + " " + Render(i) + case "": + i.Text = i.Text + "\t" + Render(i) + default: + i.Text = i.Text + e.ID + Render(i) + } + } + } +}