1 Commits
Author SHA1 Message Date
selimaj-dev 9cd88b0350 screen update 2024-10-05 15:28:25 +02:00
14 changed files with 494 additions and 479 deletions
+1
View File
@@ -39,6 +39,7 @@ func AsBg(s string) string {
}) })
} }
func AsFg(s string) string { func AsFg(s string) string {
re, _ := regexp.Compile(`\x1b\[4([0-9]+)`) re, _ := regexp.Compile(`\x1b\[4([0-9]+)`)
return re.ReplaceAllStringFunc(s, func(match string) string { return re.ReplaceAllStringFunc(s, func(match string) string {
-126
View File
@@ -1,126 +0,0 @@
package osui
import (
"github.com/orus-dev/osui/colors"
)
type Style struct {
Background string `json:"background"`
Foreground string `json:"foreground"`
Outline string `json:"outline"`
ActiveBackground string `json:"activeBackground"`
ActiveForeground string `json:"activeForeground"`
ActiveOutline string `json:"activeOutline"`
ClickedBackground string `json:"clickedBackground"`
ClickedForeground string `json:"clickedForeground"`
ClickedOutline string `json:"clickedOutline"`
SelectedBackground string `json:"selectedBackground"`
SelectedForeground string `json:"selectedForeground"`
SelectedOutline string `json:"selectedOutline"`
Cursor string `json:"cursor"`
CursorColor string `json:"cursorColor"`
InactiveCursor string `json:"inactiveCursor"`
}
func (s *Style) SetDefaults() {
defaultValue(&s.Cursor, "> ")
defaultValue(&s.SelectedForeground, colors.Black)
defaultValue(&s.SelectedBackground, colors.Magenta)
defaultValue(&s.ActiveOutline, colors.Blue)
defaultValue(&s.ClickedForeground, colors.Blue)
defaultValue(&s.ClickedOutline, colors.Blue)
s.UseStyle()
}
func (s *Style) UseStyle() {
s.Foreground = colors.AsFg(s.Foreground)
s.Background = colors.AsBg(s.Background)
s.Outline = colors.AsFg(s.Outline)
s.ActiveForeground = colors.AsFg(s.ActiveForeground)
s.ActiveBackground = colors.AsBg(s.ActiveBackground)
s.ActiveOutline = colors.AsFg(s.ActiveOutline)
s.ClickedForeground = colors.AsFg(s.ClickedForeground)
s.ClickedBackground = colors.AsBg(s.ClickedBackground)
s.ClickedOutline = colors.AsFg(s.ClickedOutline)
s.SelectedForeground = colors.AsFg(s.SelectedForeground)
s.SelectedBackground = colors.AsBg(s.SelectedBackground)
s.SelectedOutline = colors.AsFg(s.SelectedOutline)
}
func defaultValue(sd *string, s string) {
if *sd == "" {
*sd = s
}
}
type Param struct {
Style Style `json:"style"`
X int `json:"y"`
Y int `json:"x"`
Width int `json:"width"`
Height int `json:"height"`
OnClick func()
Keys map[string]string
Toggle bool `json:"useToggle"`
}
func (p *Param) SetDefaultBindings(keys map[string]string) {
p.Style.SetDefaults()
if p.Keys == nil {
p.Keys = keys
return
}
for k, f := range keys {
if _, ok := p.Keys[k]; !ok {
p.Keys[k] = f
}
}
}
func (p *Param) UseParam(c Component) Component {
data := c.GetComponentData()
p.Style.SetDefaults()
data.Style = p.Style
data.X = p.X
data.Y = p.Y
if p.Height != 0 {
data.Height = p.Height
}
if p.Width != 0 {
data.Width = p.Width
}
if p.OnClick != nil {
data.OnClick = p.OnClick
} else {
data.OnClick = func() {}
}
data.Toggle = p.Toggle
data.Keys = p.Keys
return c
}
type ComponentData struct {
X int
Y int
Width int
Height int
DefaultColor string
IsActive bool
Style Style
OnClick func()
Keys map[string]string
Toggle bool
Screen *Screen
}
+47 -31
View File
@@ -2,45 +2,61 @@ package main
import ( import (
"github.com/orus-dev/osui" "github.com/orus-dev/osui"
"github.com/orus-dev/osui/colors"
"github.com/orus-dev/osui/ui" "github.com/orus-dev/osui/ui"
) )
func main() { func main() {
// screen := osui.NewScreen() screen := osui.NewScreen(App())
// my_btn := ui.Button(osui.Param{}, screen.Run()
// "Button", }
// )
// screen.Run(my_btn)
// var menu ui.Id[*ui.MenuComponent] func App() *ui.PaginatorComponent {
// screen := osui.NewScreen() w, h := osui.GetTerminalSize()
// screen.Run(ui.Div(osui.Param{},
// menu.Id(ui.Menu(osui.Param{OnClick: func() { var keybindings ui.Class[*ui.TextComponent]
// screen.SetComponent(ui.Text(osui.Param{}, menu.Component.Items[menu.Component.SelectedItem])) keybindings.SetProperties(func(tc *ui.TextComponent) *ui.TextComponent {
// screen.Exit() tc.Text = colors.Blue + tc.Text
// }}, tc.Data.Y = h - 3
// "Item 1", "Item 24324322", "Item 366", return tc
// )), })
// )) return ui.Paginator(
// Page 1
// screen := osui.NewScreen() ui.Div(
// my_btn := ui.InputBox(osui.Param{}, ui.Text("Welcome to the example! The blue text on the bottom show the keybindings"),
// 24, keybindings.Class(ui.Text("Next Page: Tab. Previous Page: shift + tab")),
// )
// screen.Run(my_btn)
screen := osui.NewScreen()
my_btn := ui.Paginator(osui.Param{OnClick: func() {screen.Exit()}},
ui.Div(osui.Param{},
ui.Text(osui.Param{}, "Page 1"),
), ),
ui.Div(osui.Param{},
ui.Text(osui.Param{}, "Page 2"), // Page 2
ui.Div(
ui.WithPosition(0, 0, ui.Text("This blue square is a div. A div stores multiple components into one")),
ui.WithPosition((w-30)/2, (h-4)/2,
ui.WithSize(32, 7,
ui.Div(ui.WithPosition(2, 2, ui.Text("This text is inside a div!"))).Params(ui.DivParams{Style: ui.DivStyle{Outline: colors.Blue, Foreground: colors.Red}}),
)),
keybindings.Class(ui.Text("Navigate: Ctrl+(W/A/S/D)")),
),
// Page 3
ui.Div(
ui.WithPosition(0, 0, ui.Text("This is a InputBox. It takes user input just like a GUI. "+colors.Red+colors.Bold+"NOTE: This InputBox is inside a div")),
ui.WithPosition((w-32)/2, (h-3)/2, ui.InputBox(30)),
keybindings.Class(ui.Text("Navigate: Ctrl+(W/A/S/D). Finish: Enter.")),
),
// Page 4
ui.Div(
ui.WithPosition(0, 0, ui.Text("This is a Button. To click it press Enter. "+colors.Red+colors.Bold+"NOTE: This Button is inside a div")),
ui.WithPosition((w-20)/2, (h-3)/2, ui.Button("This is a button")),
keybindings.Class(ui.Text("Navigate: Ctrl+(W/A/S/D). Click Button: Enter")),
),
// Page 5
ui.Div(
ui.WithPosition(0, 0, ui.Text("This is a Menu. It prompts you to select an item. "+colors.Red+colors.Bold+"NOTE: This Menu is inside a div")),
ui.WithPosition(0, 2, ui.Menu("Item 1", "Item 2", "Item 3", "Item 4", "Item 5").Params(ui.MenuParams{OnSelected: func(mc *ui.MenuComponent, b bool) {}})),
keybindings.Class(ui.Text("Navigate: Ctrl+(W/A/S/D). Navigate Menu: W/S. Select: Enter. Exit Menu: Q. ")),
), ),
) )
screen.Run(my_btn)
} }
+53
View File
@@ -0,0 +1,53 @@
package isKey
func Enter(s string) bool {
return s == "\r" || s == "\n"
}
func Tab(s string) bool {
return s == "\t"
}
func Backspace(s string) bool {
return s == "\x7f" || s == "\b"
}
func Escape(s string) bool {
return s == "\x1b"
}
func Up(s string) bool {
return s == "\x1b[A"
}
func Down(s string) bool {
return s == "\x1b[B"
}
func Right(s string) bool {
return s == "\x1b[C"
}
func Left(s string) bool {
return s == "\x1b[D"
}
func Char(s string, s1 string) bool {
return s == s1
}
func CtrlW(s string) bool {
return s == "\x17"
}
func CtrlS(s string) bool {
return s == "\x13"
}
func CtrlA(s string) bool {
return s == "\x01"
}
func CtrlD(s string) bool {
return s == "\x04"
}
-55
View File
@@ -1,55 +0,0 @@
package keys
const (
Enter = "Enter"
Tab = "Tab"
ShiftTab = "ShiftTab"
Backspace = "Backspace"
Escape = "Escape"
Up = "Up"
Down = "Down"
Left = "Left"
Right = "Right"
CtrlW = "CtrlW"
CtrlS = "CtrlS"
CtrlA = "CtrlA"
CtrlD = "CtrlD"
Error = "Error"
)
func Char(key string) string {
return "Char(" + key + ")"
}
func GetKeyName(key string) string {
switch key {
case "\r", "\n":
return Enter
case "\x7f", "\b":
return Backspace
case "\t":
return Tab
case "\x1b[Z":
return ShiftTab
case "\x1b":
return Escape
case "\x1b[A":
return Up
case "\x1b[B":
return Down
case "\x1b[C":
return Right
case "\x1b[D":
return Left
case "\x17":
return CtrlW
case "\x13":
return CtrlS
case "\x01":
return CtrlA
case "\x04":
return CtrlD
default:
return Char(key)
}
}
+32 -67
View File
@@ -4,86 +4,40 @@ import (
"fmt" "fmt"
"os" "os"
"strings" "strings"
"time"
"github.com/orus-dev/osui/colors" "github.com/orus-dev/osui/colors"
"golang.org/x/term" "golang.org/x/term"
) )
type Key struct { type ComponentData struct {
Chars [3]rune X int
Name string Y int
} Width int
Height int
type UpdateContext struct { DefaultColor string
UpdateKind uint8 IsActive bool
Tick uint8 Screen *Screen
Key Key
} }
type Component interface { type Component interface {
Render() string Render() string
GetComponentData() *ComponentData GetComponentData() *ComponentData
Update(UpdateContext) bool Update(string) bool
} }
type Screen struct { type Screen struct {
Component Component Component Component
tickRate uint8
running bool
} }
func NewScreen() *Screen { func NewScreen(c Component) *Screen {
s := Screen{} HideCursor()
s.tickRate = 1 s := &Screen{Component: c}
return &s return s
} }
func (s *Screen) Render() { func (s *Screen) Render() {
width, height := GetTerminalSize() width, height := GetTerminalSize()
data := s.Component.GetComponentData()
if data.Height == 0 {
data.Height = height
}
if data.Width == 0 {
data.Width = width
}
frame := NewFrame(width, height) frame := NewFrame(width, height)
RenderOnFrame(s.Component, &frame)
Clear()
fmt.Print(strings.Join(frame, ""))
}
func (s *Screen) Run(c Component) {
s.SetComponent(c)
HideCursor()
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil {
panic(err)
}
defer term.Restore(int(os.Stdin.Fd()), oldState)
s.running = true
for s.running {
s.Render()
s.Component.Update(UpdateContext{UpdateKind: UpdateKindKey, Key: ReadKey()})
}
defer term.Restore(int(os.Stdin.Fd()), oldState)
}
func (s *Screen) _() {
var tick uint8 = 0
for s.running {
s.Component.Update(UpdateContext{UpdateKind: UpdateKindTick, Tick: tick})
if tick == 255 {
tick = 0
}
time.Sleep(time.Duration(1000/int(s.tickRate)) * time.Millisecond)
}
}
func (s *Screen) SetComponent(c Component) {
s.Component = c
width, height := GetTerminalSize()
data := s.Component.GetComponentData() data := s.Component.GetComponentData()
if data.Height == 0 { if data.Height == 0 {
data.Height = height data.Height = height
@@ -94,14 +48,25 @@ func (s *Screen) SetComponent(c Component) {
data.Screen = s data.Screen = s
data.IsActive = true data.IsActive = true
data.DefaultColor = colors.Reset data.DefaultColor = colors.Reset
RenderOnFrame(s.Component, &frame)
Clear()
fmt.Print(strings.Join(frame, ""))
} }
func (s *Screen) Exit() { func (s *Screen) Run() {
s.running = false oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
ShowCursor() if err != nil {
panic(err)
}
defer term.Restore(int(os.Stdin.Fd()), oldState)
data := s.Component.GetComponentData()
data.Screen = s
for {
s.Render()
k, _ := ReadKey()
if s.Component.Update(k) {
ShowCursor()
return
}
}
} }
const (
UpdateKindKey = uint8(iota)
UpdateKindTick
)
+38
View File
@@ -0,0 +1,38 @@
# Component template (use rename symbol)
```go
type HelloStyle struct {
Fg string `defaults:"" type:"fg"`
}
type HelloComponent struct {
Data osui.ComponentData
Style *HelloStyle
Name string
}
func (h *HelloComponent) GetComponentData() *osui.ComponentData {
return &h.Data
}
func (h *HelloComponent) Render() string {
osui.UseStyle(h.Style)
return "Hello " + h.Style.Fg + h.Name + colors.Reset + "!"
}
func (h *HelloComponent) Update(key string) bool {
return false
}
func (b *MenuComponent) Params(param MenuParams) *MenuComponent {
b.Style = osui.SetDefaults(&param.Style).(*MenuStyle)
return b
}
func Hello(name string) *HelloComponent {
return osui.NewComponent(&HelloComponent{
Name: name,
Style: osui.SetDefaults(&HelloStyle{}).(*HelloStyle),
}).(*HelloComponent)
}
```
+63 -36
View File
@@ -7,64 +7,84 @@ import (
"github.com/orus-dev/osui" "github.com/orus-dev/osui"
"github.com/orus-dev/osui/colors" "github.com/orus-dev/osui/colors"
"github.com/orus-dev/osui/keys" "github.com/orus-dev/osui/isKey"
) )
type ButtonParams struct {
Style ButtonStyle
Toggle bool
OnClick func(*ButtonComponent) bool
Width int
}
type ButtonStyle struct {
Background string `default:"" type:"bg"`
Foreground string `default:"" type:"fg"`
Outline string `default:"" type:"fg"`
ActiveBackground string `default:"" type:"bg"`
ActiveForeground string `default:"\x1b[34m" type:"fg"`
ActiveOutline string `default:"" type:"fg"`
ClickedBackground string `default:"" type:"bg"`
ClickedForeground string `default:"\x1b[32m" type:"fg"`
ClickedOutline string `default:"" type:"fg"`
}
type ButtonComponent struct { type ButtonComponent struct {
Data osui.ComponentData Data osui.ComponentData
Text string Style *ButtonStyle
clicked bool Text string
Toggle bool
Clicked bool
on_click func(*ButtonComponent) bool
} }
func (b *ButtonComponent) Render() string { func (b *ButtonComponent) Render() string {
b.Data.Style.UseStyle() osui.UseStyle(b.Style)
if b.clicked { if b.Clicked {
return fmt.Sprintf(" %s\n%s│%s│%s\n %s", return fmt.Sprintf(" %s\n%s│%s│%s\n %s",
colors.Reset+b.Data.Style.ClickedOutline+strings.Repeat("_", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor, colors.Reset+b.Style.ClickedOutline+strings.Repeat("_", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
colors.Reset+b.Data.Style.ClickedOutline, colors.Reset+b.Style.ClickedOutline,
colors.Reset+colors.Combine(b.Data.Style.ClickedBackground, b.Data.Style.ClickedForeground)+centerText(b.Text, b.Data.Width-2)+colors.Reset+b.Data.Style.ClickedOutline, colors.Reset+colors.Combine(b.Style.ClickedBackground, b.Style.ClickedForeground)+centerText(b.Text, b.Data.Width-2)+colors.Reset+b.Style.ClickedOutline,
colors.Reset+b.Data.DefaultColor, colors.Reset+b.Data.DefaultColor,
colors.Reset+b.Data.Style.ClickedOutline+strings.Repeat("‾", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor, colors.Reset+b.Style.ClickedOutline+strings.Repeat("‾", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
) )
} }
if b.Data.IsActive { if b.Data.IsActive {
return fmt.Sprintf(" %s\n%s│%s│%s\n %s", return fmt.Sprintf(" %s\n%s│%s│%s\n %s",
colors.Reset+b.Data.Style.ActiveOutline+strings.Repeat("_", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor, colors.Reset+b.Style.ActiveOutline+strings.Repeat("_", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
colors.Reset+b.Data.Style.ActiveOutline, colors.Reset+b.Style.ActiveOutline,
colors.Reset+colors.Combine(b.Data.Style.ActiveBackground, b.Data.Style.ActiveForeground)+centerText(b.Text, b.Data.Width-2)+colors.Reset+b.Data.Style.ActiveOutline, colors.Reset+colors.Combine(b.Style.ActiveBackground, b.Style.ActiveForeground)+centerText(b.Text, b.Data.Width-2)+colors.Reset+b.Style.ActiveOutline,
colors.Reset+b.Data.DefaultColor, colors.Reset+b.Data.DefaultColor,
colors.Reset+b.Data.Style.ActiveOutline+strings.Repeat("‾", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor, colors.Reset+b.Style.ActiveOutline+strings.Repeat("‾", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
) )
} }
return fmt.Sprintf(" %s\n%s│%s│%s\n %s", return fmt.Sprintf(" %s\n%s│%s│%s\n %s",
colors.Reset+b.Data.Style.Outline+strings.Repeat("_", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor, colors.Reset+b.Style.Outline+strings.Repeat("_", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
colors.Reset+b.Data.Style.Outline, colors.Reset+b.Style.Outline,
colors.Reset+colors.Combine(b.Data.Style.Background, b.Data.Style.Foreground)+centerText(b.Text, b.Data.Width-2)+colors.Reset+b.Data.Style.Outline, colors.Reset+colors.Combine(b.Style.Background, b.Style.Foreground)+centerText(b.Text, b.Data.Width-2)+colors.Reset+b.Style.Outline,
colors.Reset+b.Data.DefaultColor, colors.Reset+b.Data.DefaultColor,
colors.Reset+b.Data.Style.Outline+strings.Repeat("‾", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor, colors.Reset+b.Style.Outline+strings.Repeat("‾", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
) )
} }
func (b *ButtonComponent) Update(ctx osui.UpdateContext) bool { func (b *ButtonComponent) Update(key string) bool {
if ctx.UpdateKind == osui.UpdateKindKey { if isKey.Enter(key) {
switch b.Data.Keys[ctx.Key.Name] { if !b.on_click(b) {
case "click": if b.Toggle {
b.Data.OnClick() b.Clicked = !b.Clicked
if b.Data.Toggle {
b.clicked = !b.clicked
return false return false
} }
b.clicked = true b.Clicked = true
b.Data.Screen.Render() b.Data.Screen.Render()
time.Sleep(time.Millisecond * 120) time.Sleep(time.Millisecond * 120)
b.clicked = false b.Clicked = false
} }
} else if ctx.UpdateKind == osui.UpdateKindTick {
} }
return false return false
} }
@@ -72,15 +92,22 @@ func (b *ButtonComponent) GetComponentData() *osui.ComponentData {
return &b.Data return &b.Data
} }
func Button(param osui.Param, text string) *ButtonComponent { func (b *ButtonComponent) Params(param ButtonParams) *ButtonComponent {
param.SetDefaultBindings(map[string]string{ b.Style = osui.SetDefaults(&param.Style).(*ButtonStyle)
keys.Enter: "click", if param.OnClick != nil {
}) b.on_click = param.OnClick
return param.UseParam(&ButtonComponent{Text: text, }
b.Data.Width = osui.LogicValueInt(param.Width == 0, 20, param.Width)
return b
}
func Button(text string) *ButtonComponent {
return &ButtonComponent{Text: text,
Style: osui.SetDefaults(&ButtonStyle{}).(*ButtonStyle),
Data: osui.ComponentData{ Data: osui.ComponentData{
Width: 20, Width: 20,
Height: 1, Height: 1,
}, },
clicked: false, on_click: func(bc *ButtonComponent) bool { return false },
}).(*ButtonComponent) }
} }
+47 -36
View File
@@ -5,11 +5,24 @@ import (
"github.com/orus-dev/osui" "github.com/orus-dev/osui"
"github.com/orus-dev/osui/colors" "github.com/orus-dev/osui/colors"
"github.com/orus-dev/osui/keys" "github.com/orus-dev/osui/isKey"
) )
type DivParams struct {
Style DivStyle
Width int
Height int
}
type DivStyle struct {
Background string `default:"" type:"bg"`
Foreground string `default:"" type:"fg"`
Outline string `default:"" type:"fg"`
}
type DivComponent struct { type DivComponent struct {
Data osui.ComponentData Data osui.ComponentData
Style *DivStyle
Components []osui.Component Components []osui.Component
ActiveComponent int ActiveComponent int
} }
@@ -19,7 +32,7 @@ func (d *DivComponent) GetComponentData() *osui.ComponentData {
} }
func (d *DivComponent) Render() string { func (d *DivComponent) Render() string {
d.Data.Style.UseStyle() osui.UseStyle(d.Style)
frame := osui.NewFrame(d.Data.Width-2, d.Data.Height-2) frame := osui.NewFrame(d.Data.Width-2, d.Data.Height-2)
for i, c := range d.Components { for i, c := range d.Components {
data := c.GetComponentData() data := c.GetComponentData()
@@ -34,64 +47,62 @@ func (d *DivComponent) Render() string {
if data.Height == 0 { if data.Height == 0 {
data.Height = d.Data.Height - 2 data.Height = d.Data.Height - 2
} }
data.DefaultColor = colors.Combine(d.Data.Style.Background, d.Data.Style.Foreground) data.DefaultColor = colors.Combine(d.Style.Background, d.Style.Foreground)
data.Screen = d.Data.Screen data.Screen = d.Data.Screen
osui.RenderOnFrame(c, &frame) osui.RenderOnFrame(c, &frame)
} }
if d.Data.Style.Outline == "" { if d.Style.Outline == "" {
for i, f := range frame { for i, f := range frame {
frame[i] = colors.Combine(d.Data.Style.Foreground, d.Data.Style.Background) + f + colors.Reset frame[i] = colors.Combine(d.Style.Foreground, d.Style.Background) + f + colors.Reset
} }
return strings.Join(frame, "\n") return strings.Join(frame, "\n")
} else { } else {
for i, f := range frame { for i, f := range frame {
frame[i] = d.Data.Style.Outline + "│" + colors.Reset + colors.Combine(d.Data.Style.Foreground, d.Data.Style.Background) + f + colors.Reset + d.Data.Style.Outline + "│" + colors.Reset frame[i] = d.Style.Outline + "│" + colors.Reset + colors.Combine(d.Style.Foreground, d.Style.Background) + f + colors.Reset + d.Style.Outline + "│" + colors.Reset
} }
} }
return " " + d.Data.Style.Outline + strings.Repeat("_", d.Data.Width-2) + colors.Reset + "\n" + strings.Join(frame, "\n") + "\n " + d.Data.Style.Outline + strings.Repeat("‾", d.Data.Width-2) + colors.Reset return " " + d.Style.Outline + strings.Repeat("_", d.Data.Width-2) + colors.Reset + "\n" + strings.Join(frame, "\n") + "\n " + d.Style.Outline + strings.Repeat("‾", d.Data.Width-2) + colors.Reset
} }
func (d *DivComponent) Update(ctx osui.UpdateContext) bool { func (d *DivComponent) Update(key string) bool {
if ctx.UpdateKind == osui.UpdateKindKey { if isKey.CtrlW(key) {
switch d.Data.Keys[ctx.Key.Name] { d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "up"))
case "up": } else if isKey.CtrlS(key) {
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "up")) d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "down"))
case "down": } else if isKey.CtrlA(key) {
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "down")) d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "left"))
case "left": } else if isKey.CtrlD(key) {
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "left")) d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "right"))
case "right": } else {
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "right")) if len(d.Components) > 0 {
default:
d.Components[d.ActiveComponent].GetComponentData().IsActive = d.Data.IsActive d.Components[d.ActiveComponent].GetComponentData().IsActive = d.Data.IsActive
if d.Components[d.ActiveComponent].Update(ctx) { if d.Components[d.ActiveComponent].Update(key) {
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "down")) if d.ActiveComponent < len(d.Components)-1 {
d.updateActive(d.ActiveComponent + 1)
} else {
return true
}
} }
} }
} else if ctx.UpdateKind == osui.UpdateKindTick {
d.Components[d.ActiveComponent].GetComponentData().IsActive = d.Data.IsActive
if d.Components[d.ActiveComponent].Update(ctx) {
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "down"))
}
} }
return false return false
} }
func (b *DivComponent) Params(param DivParams) *DivComponent {
b.Style = osui.SetDefaults(&param.Style).(*DivStyle)
b.Data.Width = osui.LogicValueInt(param.Width == 0, 20, param.Width)
return b
}
func (d *DivComponent) updateActive(newIndex int) { func (d *DivComponent) updateActive(newIndex int) {
if newIndex >= 0 && newIndex < len(d.Components) && len(d.Components) > 0 { if newIndex >= 0 && newIndex < len(d.Components) && len(d.Components) > 0 {
d.ActiveComponent = newIndex d.ActiveComponent = newIndex
} }
} }
func Div(param osui.Param, components ...osui.Component) *DivComponent { func Div(components ...osui.Component) *DivComponent {
param.SetDefaultBindings(map[string]string{ return &DivComponent{
keys.CtrlW: "up",
keys.CtrlS: "down",
keys.CtrlA: "left",
keys.CtrlD: "right",
})
return param.UseParam(&DivComponent{
Components: components, Components: components,
}).(*DivComponent) Style: osui.SetDefaults(&DivStyle{}).(*DivStyle),
}
} }
+53 -43
View File
@@ -6,11 +6,25 @@ import (
"github.com/orus-dev/osui" "github.com/orus-dev/osui"
"github.com/orus-dev/osui/colors" "github.com/orus-dev/osui/colors"
"github.com/orus-dev/osui/keys" "github.com/orus-dev/osui/isKey"
) )
type InputBoxParams struct {
Style DivStyle
Width int
Height int
}
type InputBoxStyle struct {
Background string `default:"" type:"bg"`
Foreground string `default:"" type:"fg"`
Outline string `default:"" type:"fg"`
Cursor string `default:"" type:"fg"`
}
type InputBoxComponent struct { type InputBoxComponent struct {
Data osui.ComponentData Data osui.ComponentData
Style *InputBoxStyle
max_size uint max_size uint
cursor uint cursor uint
InputData string InputData string
@@ -21,65 +35,61 @@ func (s *InputBoxComponent) GetComponentData() *osui.ComponentData {
} }
func (s InputBoxComponent) Render() string { func (s InputBoxComponent) Render() string {
s.Data.Style.UseStyle() osui.UseStyle(s.Style)
if s.max_size > uint(len(s.InputData)) { if s.max_size > uint(len(s.InputData)) {
return fmt.Sprintf( return fmt.Sprintf(
" %s\n%s│%s%s│%s\n %s", " %s\n%s│%s%s│%s\n %s",
colors.Reset+s.Data.Style.Outline+strings.Repeat("_", int(s.max_size))+colors.Reset, colors.Reset+s.Style.Outline+strings.Repeat("_", int(s.max_size))+colors.Reset,
colors.Reset+s.Data.Style.Outline, colors.Reset+s.Style.Outline,
colors.Combine(s.Data.Style.Foreground, s.Data.Style.Background)+s.InputData+osui.LogicValue(s.Data.IsActive, s.Data.Style.CursorColor+"█"+colors.Combine(s.Data.Style.Foreground, s.Data.Style.Background), ""), colors.Combine(s.Style.Foreground, s.Style.Background)+s.InputData+osui.LogicValue(s.Data.IsActive, s.Style.Cursor+"█"+colors.Combine(s.Style.Foreground, s.Style.Background), ""),
strings.Repeat(" ", int(s.max_size)-len(s.InputData)-osui.LogicValueInt(s.Data.IsActive, 1, 0))+colors.Reset+s.Data.Style.Outline, strings.Repeat(" ", int(s.max_size)-len(s.InputData)-osui.LogicValueInt(s.Data.IsActive, 1, 0))+colors.Reset+s.Style.Outline,
colors.Reset+s.Data.DefaultColor, colors.Reset+s.Data.DefaultColor,
s.Data.Style.Outline+strings.Repeat("‾", int(s.max_size))+colors.Reset+s.Data.DefaultColor, s.Style.Outline+strings.Repeat("‾", int(s.max_size))+colors.Reset+s.Data.DefaultColor,
) )
} }
return fmt.Sprintf( return fmt.Sprintf(
" %s\n%s│%s%s\n %s", " %s\n%s│%s%s\n %s",
colors.Reset+s.Data.Style.Outline+strings.Repeat("_", int(s.max_size))+colors.Reset, colors.Reset+s.Style.Outline+strings.Repeat("_", int(s.max_size))+colors.Reset,
colors.Reset+s.Data.Style.Outline, colors.Reset+s.Style.Outline,
colors.Combine(s.Data.Style.Foreground, s.Data.Style.Background)+s.InputData+osui.LogicValue(s.Data.IsActive, s.Data.Style.CursorColor+"█"+colors.Reset, s.Data.Style.Outline+"|"+colors.Reset), colors.Combine(s.Style.Foreground, s.Style.Background)+s.InputData+osui.LogicValue(s.Data.IsActive, s.Style.Cursor+"█"+colors.Reset, s.Style.Outline+"|"+colors.Reset),
colors.Reset+s.Data.DefaultColor, colors.Reset+s.Data.DefaultColor,
colors.Reset+s.Data.Style.Outline+strings.Repeat("‾", int(s.max_size))+colors.Reset+s.Data.DefaultColor, colors.Reset+s.Style.Outline+strings.Repeat("‾", int(s.max_size))+colors.Reset+s.Data.DefaultColor,
) )
} }
func (s *InputBoxComponent) Update(ctx osui.UpdateContext) bool { func (s *InputBoxComponent) Update(key string) bool {
if ctx.UpdateKind == osui.UpdateKindKey { if isKey.Enter(key) {
switch s.Data.Keys[ctx.Key.Name] { return true
case "done": } else if isKey.Backspace(key) {
s.Data.OnClick() if len(s.InputData) > 0 {
return true s.InputData = s.InputData[:len(s.InputData)-1]
case "remove": }
if len(s.InputData) > 0 { } else if isKey.Left(key) {
s.InputData = s.InputData[:len(s.InputData)-1] if s.cursor > 0 {
} s.cursor--
case "left": }
if s.cursor > 0 { } else if isKey.Right(key) {
s.cursor-- if s.cursor < s.max_size {
} s.cursor++
case "right": }
if s.cursor < s.max_size { } else {
s.cursor++ if len(key) == 1 {
} if int(s.max_size) > len(s.InputData) {
default: s.InputData += key
if ctx.Key.Chars[1] == '\x00' {
if int(s.max_size) > len(s.InputData) {
s.InputData += string(ctx.Key.Chars[0])
}
} }
} }
} }
return false return false
} }
func InputBox(param osui.Param, max_size uint) *InputBoxComponent { func (b *InputBoxComponent) Params(p interface{}) *InputBoxComponent {
param.SetDefaultBindings(map[string]string{ param := p.(InputBoxParams)
keys.Enter: "done", b.Style = osui.SetDefaults(&param.Style).(*InputBoxStyle)
keys.Backspace: "remove", b.Data.Width = osui.LogicValueInt(param.Width == 0, 20, param.Width)
keys.Left: "left", return b
keys.Right: "right", }
})
return param.UseParam(&InputBoxComponent{max_size: max_size, Data: osui.ComponentData{}}).(*InputBoxComponent) func InputBox(max_size uint) *InputBoxComponent {
return &InputBoxComponent{max_size: max_size, Style: osui.SetDefaults(&InputBoxStyle{}).(*InputBoxStyle)}
} }
+51 -36
View File
@@ -5,13 +5,29 @@ import (
"github.com/orus-dev/osui" "github.com/orus-dev/osui"
"github.com/orus-dev/osui/colors" "github.com/orus-dev/osui/colors"
"github.com/orus-dev/osui/keys" "github.com/orus-dev/osui/isKey"
) )
type MenuParams struct {
Style MenuStyle
OnSelected func(*MenuComponent, bool)
}
type MenuStyle struct {
Fg string `default:"" type:"fg"`
Bg string `default:"" type:"bg"`
SelectedFg string `default:"\x1b[34m" type:"fg"`
SelectedBg string `default:"" type:"bg"`
Cursor string `default:"> " type:"fg"`
CursorInactive string `default:" " type:"fg"`
}
type MenuComponent struct { type MenuComponent struct {
Data osui.ComponentData Data osui.ComponentData
Style *MenuStyle
Items []string Items []string
SelectedItem int SelectedItem int
OnSelected func(*MenuComponent, bool)
} }
func (m *MenuComponent) GetComponentData() *osui.ComponentData { func (m *MenuComponent) GetComponentData() *osui.ComponentData {
@@ -19,60 +35,59 @@ func (m *MenuComponent) GetComponentData() *osui.ComponentData {
} }
func (m *MenuComponent) Render() string { func (m *MenuComponent) Render() string {
m.Data.Style.UseStyle() osui.UseStyle(m.Style)
res := []string{} res := []string{}
cursor := m.Data.Style.Cursor cursor := m.Style.Cursor
if !m.Data.IsActive { if !m.Data.IsActive {
cursor = m.Data.Style.InactiveCursor cursor = m.Style.CursorInactive
} }
d, _ := osui.CompressString(m.Data.Style.Cursor) d, _ := osui.CompressString(m.Style.Cursor)
empty := strings.Repeat(" ", len(d)) empty := strings.Repeat(" ", len(d))
for i, item := range m.Items { for i, item := range m.Items {
if i == m.SelectedItem { if i == m.SelectedItem {
res = append(res, colors.Reset+cursor+m.Data.Style.SelectedBackground+m.Data.Style.SelectedForeground+item+"\x1b[0m ") res = append(res, cursor+colors.Combine(m.Style.SelectedFg, m.Style.SelectedBg)+item+colors.Reset+m.Data.DefaultColor)
} else { } else {
res = append(res, colors.Reset+empty+m.Data.Style.Foreground+m.Data.Style.Background+item) res = append(res, empty+colors.Combine(m.Style.Fg, m.Style.Bg)+item+colors.Reset+m.Data.DefaultColor)
} }
} }
return strings.Join(res, "\n") return strings.Join(res, "\n")
} }
func (m *MenuComponent) Update(ctx osui.UpdateContext) bool { func (m *MenuComponent) Update(key string) bool {
if ctx.UpdateKind == osui.UpdateKindKey { if isKey.Char(key, "s") {
switch m.Data.Keys[ctx.Key.Name] { if m.SelectedItem+1 < len(m.Items) {
case "up": m.SelectedItem++
if m.SelectedItem > 0 { } else {
m.SelectedItem-- m.SelectedItem = 0
} else {
m.SelectedItem = len(m.Items) - 1
}
case "down":
if m.SelectedItem+1 < len(m.Items) {
m.SelectedItem++
} else {
m.SelectedItem = 0
}
case "select":
m.Data.OnClick()
return true
case "exit":
return true
} }
} else if isKey.Char(key, "w") {
if m.SelectedItem > 0 {
m.SelectedItem--
} else {
m.SelectedItem = len(m.Items) - 1
}
} else if isKey.Enter(key) {
m.OnSelected(m, true)
return true
} else if isKey.Char(key, "q") {
m.OnSelected(m, false)
return true
} }
return false return false
} }
func Menu(param osui.Param, items ...string) *MenuComponent { func (b *MenuComponent) Params(param MenuParams) *MenuComponent {
param.SetDefaultBindings(map[string]string{ b.Style = osui.SetDefaults(&param.Style).(*MenuStyle)
keys.Up: "up", b.OnSelected = param.OnSelected
keys.Down: "down", return b
keys.Enter: "select", }
})
return param.UseParam(&MenuComponent{ func Menu(items ...string) *MenuComponent {
return &MenuComponent{
Items: items, Items: items,
}).(*MenuComponent) Style: osui.SetDefaults(&MenuStyle{}).(*MenuStyle),
}
} }
+51 -41
View File
@@ -6,11 +6,23 @@ import (
"github.com/orus-dev/osui" "github.com/orus-dev/osui"
"github.com/orus-dev/osui/colors" "github.com/orus-dev/osui/colors"
"github.com/orus-dev/osui/keys" "github.com/orus-dev/osui/isKey"
) )
type PaginatorParams struct {
Style DivStyle
Width int
Height int
}
type PaginatorStyle struct {
Active string `default:"\033[32m"`
Inactive string `default:""`
}
type PaginatorComponent struct { type PaginatorComponent struct {
Data osui.ComponentData Data osui.ComponentData
Style *PaginatorStyle
Components []osui.Component Components []osui.Component
ActiveComponent int ActiveComponent int
} }
@@ -22,15 +34,15 @@ func (p *PaginatorComponent) GetComponentData() *osui.ComponentData {
func (p *PaginatorComponent) Render() string { func (p *PaginatorComponent) Render() string {
width, _ := osui.GetTerminalSize() width, _ := osui.GetTerminalSize()
pgs := strings.Repeat(" ", (width-len(p.Components))/2) pgs := strings.Repeat(" ", (width-len(p.Components))/2)
p.Data.Style.UseStyle() osui.UseStyle(p.Style)
frame := osui.NewFrame(p.Data.Width, p.Data.Height) frame := osui.NewFrame(p.Data.Width, p.Data.Height)
for i, c := range p.Components { for i, c := range p.Components {
data := c.GetComponentData() data := c.GetComponentData()
if i == p.ActiveComponent { if i == p.ActiveComponent {
pgs += p.Data.Style.SelectedForeground + data.Style.SelectedBackground + "•" + colors.Reset pgs += p.Style.Active + "•" + colors.Reset
data.IsActive = true data.IsActive = true
} else { } else {
pgs += colors.Reset + p.Data.Style.Foreground + data.Style.Background + "•" pgs += colors.Reset + p.Style.Inactive + "•"
data.IsActive = false data.IsActive = false
} }
if data.Width == 0 { if data.Width == 0 {
@@ -46,37 +58,33 @@ func (p *PaginatorComponent) Render() string {
for i, f := range frame { for i, f := range frame {
frame[i] = colors.Reset + p.Data.DefaultColor + f + colors.Reset frame[i] = colors.Reset + p.Data.DefaultColor + f + colors.Reset
} }
return fmt.Sprintf("%s\n%s", pgs+" ", colors.Reset+strings.Join(frame, "\n")) return fmt.Sprintf("%s\n%s", pgs, colors.Reset+strings.Join(frame, "\n"))
} }
func (p *PaginatorComponent) Update(ctx osui.UpdateContext) bool { func (p *PaginatorComponent) Update(key string) bool {
if ctx.UpdateKind == osui.UpdateKindKey { if key == "\x1b[Z" {
switch p.Data.Keys[ctx.Key.Name] { if p.ActiveComponent > 0 {
case "previous": p.updateActive(p.ActiveComponent - 1)
if p.ActiveComponent > 0 { } else {
p.updateActive(p.ActiveComponent - 1) p.updateActive(len(p.Components) - 1)
} else { }
p.updateActive(len(p.Components) - 1) } else if isKey.Tab(key) {
} if p.ActiveComponent < len(p.Components)-1 {
case "next": p.updateActive(p.ActiveComponent + 1)
if p.ActiveComponent < len(p.Components)-1 { } else {
p.updateActive(p.ActiveComponent + 1) p.updateActive(0)
} else { }
p.updateActive(0) } else if isKey.Escape(key) {
} fmt.Print("\n\n")
case "exit": return true
p.Data.OnClick() } else {
fmt.Print("\n\n") if len(p.Components) > 0 {
return true p.Components[p.ActiveComponent].GetComponentData().IsActive = p.Data.IsActive
default: if p.Components[p.ActiveComponent].Update(key) {
if len(p.Components) > 0 { if p.ActiveComponent < len(p.Components)-1 {
p.Components[p.ActiveComponent].GetComponentData().IsActive = p.Data.IsActive p.updateActive(p.ActiveComponent + 1)
if p.Components[p.ActiveComponent].Update(ctx) { } else {
if p.ActiveComponent < len(p.Components)-1 { p.updateActive(0)
p.updateActive(p.ActiveComponent + 1)
} else {
p.updateActive(0)
}
} }
} }
} }
@@ -90,13 +98,15 @@ func (p *PaginatorComponent) updateActive(newIndex int) {
} }
} }
func Paginator(param osui.Param, pages ...osui.Component) *PaginatorComponent { func (b *PaginatorComponent) Params(p interface{}) *PaginatorComponent {
param.SetDefaultBindings(map[string]string{ param := p.(PaginatorParams)
keys.ShiftTab: "previous", b.Style = osui.SetDefaults(&param.Style).(*PaginatorStyle)
keys.Tab: "next", return b
keys.Escape: "exit", }
})
return param.UseParam(&PaginatorComponent{ func Paginator(pages ...osui.Component) *PaginatorComponent {
return &PaginatorComponent{
Components: pages, Components: pages,
}).(*PaginatorComponent) Style: osui.SetDefaults(&PaginatorStyle{}).(*PaginatorStyle),
}
} }
+3 -4
View File
@@ -9,7 +9,7 @@ type TextComponent struct {
Text string Text string
} }
func (t *TextComponent) Update(ctx osui.UpdateContext) bool { func (t *TextComponent) Update(string) bool {
return false return false
} }
@@ -21,7 +21,6 @@ func (t TextComponent) Render() string {
return t.Text return t.Text
} }
func Text(param osui.Param, text string) *TextComponent { func Text(text string) *TextComponent {
param.SetDefaultBindings(map[string]string{}) return &TextComponent{Text: text}
return param.UseParam(&TextComponent{Text: text}).(*TextComponent)
} }
+55 -4
View File
@@ -4,12 +4,13 @@ import (
"fmt" "fmt"
"os" "os"
"os/exec" "os/exec"
"reflect"
"regexp" "regexp"
"runtime" "runtime"
"strings" "strings"
"github.com/nathan-fiscaletti/consolesize-go" "github.com/nathan-fiscaletti/consolesize-go"
"github.com/orus-dev/osui/keys" "github.com/orus-dev/osui/colors"
) )
var re = regexp.MustCompile(`(\x1b\[([0-9;]*)[a-zA-Z])+`) var re = regexp.MustCompile(`(\x1b\[([0-9;]*)[a-zA-Z])+`)
@@ -68,13 +69,13 @@ func RenderOnFrame(c Component, frame *[]string) {
} }
} }
func ReadKey() Key { func ReadKey() (string, error) {
var b [3]byte var b [3]byte
n, err := os.Stdin.Read(b[:]) n, err := os.Stdin.Read(b[:])
if err != nil { if err != nil {
return Key{Chars: [3]rune{'E', 'r', 'r'}, Name: err.Error()} return "", err
} }
return Key{Chars: [3]rune{rune(b[0]), rune(b[1]), rune(b[2])}, Name: keys.GetKeyName(string(b[:n]))} return string(b[:n]), nil
} }
func NewFrame(width, height int) []string { func NewFrame(width, height int) []string {
@@ -98,6 +99,55 @@ func Clear() {
} }
} }
func SetDefaults(p interface{}) interface{} {
v := reflect.ValueOf(p)
if v.Kind() != reflect.Ptr {
panic("SetDefaults: expected a pointer to a struct")
}
val := v.Elem()
if val.Kind() != reflect.Struct {
panic("SetDefaults: expected a pointer to a struct")
}
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
structField := typ.Field(i)
if defaultValue, ok := structField.Tag.Lookup("default"); ok {
if field.Kind() == reflect.String && field.String() == "" {
field.SetString(defaultValue)
}
}
}
return p
}
func UseStyle(p interface{}) {
SetDefaults(p)
v := reflect.ValueOf(p)
if v.Kind() != reflect.Ptr {
panic("SetStyle: expected a pointer to a struct")
}
val := v.Elem()
if val.Kind() != reflect.Struct {
panic("SetStyle: expected a pointer to a struct")
}
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
structField := typ.Field(i)
if styleType, ok := structField.Tag.Lookup("type"); ok {
if field.Kind() == reflect.String {
if styleType == "bg" || styleType == "background" {
field.SetString(colors.AsBg(field.String()))
} else {
field.SetString(colors.AsFg(field.String()))
}
}
}
}
}
func ShowCursor() { func ShowCursor() {
fmt.Print("\033[?25h") fmt.Print("\033[?25h")
} }
@@ -120,6 +170,7 @@ func LogicValueInt(b bool, _if, _else int) int {
return _else return _else
} }
// Get the terminal size
func GetTerminalSize() (int, int) { func GetTerminalSize() (int, int) {
return consolesize.GetConsoleSize() return consolesize.GetConsoleSize()
} }