1
0
mirror of https://github.com/gizak/termui.git synced 2025-04-24 13:48:50 +08:00

New input widget

Same as `Paragraph`, but for input :)
This commit is contained in:
Szymon Błaszczyński 2021-05-02 15:25:54 +02:00
parent f976fe697a
commit ea93b82af1
2 changed files with 93 additions and 0 deletions

View File

@ -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,
},

84
widgets/input.go Normal file
View File

@ -0,0 +1,84 @@
// Copyright 2021 Szymon Błaszczyński <museyoucoulduse@gmail.com>. 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 "<Backspace>":
if len(i.Text) > 0 {
i.Text = i.Text[:len(i.Text)-1]
Render(i)
}
case "<Escape>", "C-c", "<Enter>":
i.focusing = false
break Loop
case "<Space>":
i.Text = i.Text + " "
Render(i)
case "<Tab>":
i.Text = i.Text + "\t"
Render(i)
default:
i.Text = i.Text + e.ID
Render(i)
}
}
}
}