21 Commits
Author SHA1 Message Date
selimaj-dev 553804ec51 a few more changes 2024-10-13 16:32:05 +02:00
selimaj-dev 905bb6711e updated structure 2024-10-12 22:36:20 +02:00
selimaj-dev 8ea250c1b1 updated structure 2024-10-12 22:36:09 +02:00
selimaj-dev 039bc27999 updated structure 2024-10-12 17:49:55 +02:00
selimaj-dev d4f6c4104d fixed flickering on all platforms 2024-10-04 22:55:30 +02:00
selimaj-dev 0f052d7652 perfomance boost 2024-10-03 20:02:56 +02:00
selimaj-dev f2f7e51750 small performance increase 2024-10-03 19:29:18 +02:00
selimaj-dev 7e714abddf fixed color bug 2024-10-03 13:19:43 +02:00
selimaj-dev 3ceaa13b3f fixed color bug 2024-10-03 13:10:43 +02:00
selimaj-dev 8165e80b05 fixed ui when horizontal but color bug 2024-10-01 19:53:19 +02:00
selimaj-dev f77c04c908 fixed ui when horizontal 2024-10-01 16:37:54 +02:00
selimaj-dev 27530fe8cc fixed ui when horizontal 2024-10-01 16:34:50 +02:00
selimaj-dev 705bd8d61b ids and classes 2024-09-30 14:10:00 +02:00
RudideC bf70ceacf1 this seems to fix an issue i was facing 2024-09-30 10:10:32 +02:00
selimaj-dev 6cdb685eb5 small change 2024-09-29 22:13:54 +02:00
selimaj-dev cdb8576cc4 readme update 2024-09-29 22:11:05 +02:00
selimaj-dev b2b5c9c00d windows bug fix 02 2024-09-29 21:52:17 +02:00
selimaj-dev dd8f1fbc1f bug fixes and clean code 2024-09-29 21:22:25 +02:00
Rudi e873c01e50 wow 2024-09-29 17:35:30 +02:00
selimaj-dev 3bab6d3cd6 readme update 2024-09-29 14:39:33 +02:00
selimaj-dev 06f9e4577c readme update 2024-09-29 14:39:25 +02:00
20 changed files with 598 additions and 560 deletions
+19 -11
View File
@@ -1,22 +1,30 @@
# osui <div style="text-align: center;">
A Component-based TUI library written in go! <img src="assets/osui.png" width="170px" />
<h1>A Component-based TUI library written in Go</h1>
<img src="assets/osui.gif" />
</div>
# Hello World
```go ```go
package main package main
import ( import (
"github.com/orus-dev/osui/osui" "github.com/orus-dev/osui"
"github.com/orus-dev/osui/osui/ui" "github.com/orus-dev/osui/ui"
) )
func main() { func main() {
app := ui.Div(
ui.Text("Hello, World!")
)
app := ui.Div( screen := osui.NewScreen(app)
ui.Text("Hello, World!") screen.Run()
)
screen := osui.NewScreen(app)
screen.Run()
} }
``` ```
# [Documentation](https://github.com/orus-dev/osui/wiki)
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 270 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

-1
View File
@@ -39,7 +39,6 @@ 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
@@ -0,0 +1,126 @@
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
}
+34 -43
View File
@@ -2,54 +2,45 @@ 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(App()) // screen := osui.NewScreen()
screen.Run() // my_btn := ui.Button(osui.Param{},
} // "Button",
// )
// screen.Run(my_btn)
func App() *PaginatorComponent { // var menu ui.Id[*ui.MenuComponent]
w, h := osui.GetTerminalSize() // screen := osui.NewScreen()
return Paginator( // screen.Run(ui.Div(osui.Param{},
// Page 1
Div( // menu.Id(ui.Menu(osui.Param{OnClick: func() {
Text("Welcome to the example! The blue text on the bottom show the keybindings"), // screen.SetComponent(ui.Text(osui.Param{}, menu.Component.Items[menu.Component.SelectedItem]))
WithPosition(0, h-2, Text(colors.Blue+"Next Page: Tab. Previous Page: shift + tab")), // screen.Exit()
// }},
// "Item 1", "Item 24324322", "Item 366",
// )),
// ))
// screen := osui.NewScreen()
// my_btn := ui.InputBox(osui.Param{},
// 24,
// )
// 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{},
// Page 2 ui.Text(osui.Param{}, "Page 2"),
Div(
WithPosition(0, 0, Text("This blue square is a div. A div stores multiple components into one")),
WithPosition((w-30)/2, (h-4)/2,
WithSize(30, 5,
WithStyle(&DivStyle{Outline: colors.Blue},
Div(WithPosition(4, 1, Button("Hello, World!", BtnParams{Width: 19}))),
))),
WithPosition(0, h-2, Text(colors.Blue+"Navigate: Ctrl+(W/A/S/D)")),
),
// Page 3
Div(
WithPosition(0, 0, Text("This is a InputBox. It takes user input just like a GUI. "+colors.Red+colors.Bold+"NOTE: This InputBox is inside a div")),
WithPosition((w-32)/2, (h-3)/2, InputBox(30)),
WithPosition(0, h-2, Text(colors.Blue+"Navigate: W/S. Select: Enter. Exit Menu: Q. ")),
),
// Page 4
Div(
WithPosition(0, 0, Text("This is a Button. To click it press Enter. "+colors.Red+colors.Bold+"NOTE: This Button is inside a div")),
WithPosition((w-20)/2, (h-3)/2, Button("This is a button", BtnParams{OnClick: func(bc *ButtonComponent) bool { return false }})),
WithPosition(0, h-2, Text(colors.Blue+"Navigate: Ctrl+(W/A/S/D). Click Button: Enter")),
),
// Page 5
Div(
WithPosition(0, 0, Text("This is a Menu. It prompts you to select a item. "+colors.Red+colors.Bold+"NOTE: This Menu is inside a div")),
WithPosition(0, 2, Menu("Item 1", "Item 2", "Item 3", "Item 4", "Item 5").OnSelected(func(m *MenuComponent, b bool) {})),
WithPosition(0, h-2, Text(colors.Blue+"Navigate: Ctrl+(W/A/S/D). Navigate Menu: W/S. Select: Enter. Exit Menu: Q. ")),
), ),
) )
screen.Run(my_btn)
} }
+3 -1
View File
@@ -2,7 +2,9 @@ module github.com/orus-dev/osui
go 1.23.1 go 1.23.1
require golang.org/x/term v0.24.0 // direct
require ( require (
github.com/nathan-fiscaletti/consolesize-go v0.0.0-20220204101620-317176b6684d
golang.org/x/sys v0.25.0 // indirect golang.org/x/sys v0.25.0 // indirect
golang.org/x/term v0.24.0 // direct
) )
+2
View File
@@ -1,3 +1,5 @@
github.com/nathan-fiscaletti/consolesize-go v0.0.0-20220204101620-317176b6684d h1:NqRhLdNVlozULwM1B3VaHhcXYSgrOAv8V5BE65om+1Q=
github.com/nathan-fiscaletti/consolesize-go v0.0.0-20220204101620-317176b6684d/go.mod h1:cxIIfNMTwff8f/ZvRouvWYF6wOoO7nj99neWSx2q/Es=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.24.0 h1:Mh5cbb+Zk2hqqXNO7S1iTjEphVL+jb8ZWaqh/g+JWkM= golang.org/x/term v0.24.0 h1:Mh5cbb+Zk2hqqXNO7S1iTjEphVL+jb8ZWaqh/g+JWkM=
-53
View File
@@ -1,53 +0,0 @@
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
@@ -0,0 +1,55 @@
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)
}
}
+71 -30
View File
@@ -2,43 +2,89 @@ package osui
import ( import (
"fmt" "fmt"
"os"
"strings" "strings"
"time"
"github.com/orus-dev/osui/colors" "github.com/orus-dev/osui/colors"
"golang.org/x/term"
) )
type ComponentData struct { type Key struct {
X int Chars [3]rune
Y int Name string
Width int }
Height int
DefaultColor string type UpdateContext struct {
IsActive bool UpdateKind uint8
Screen *Screen Tick uint8
Key Key
} }
type Component interface { type Component interface {
Render() string Render() string
GetComponentData() *ComponentData GetComponentData() *ComponentData
Update(string) bool Update(UpdateContext) bool
SetStyle(interface{})
} }
type Screen struct { type Screen struct {
component Component Component Component
tickRate uint8
running bool
} }
func NewScreen(c Component) *Screen { func NewScreen() *Screen {
HideCursor() s := Screen{}
s := &Screen{component: c} s.tickRate = 1
return s return &s
} }
func (s *Screen) Render() { func (s *Screen) Render() {
Clear()
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)
data := s.component.GetComponentData() 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()
if data.Height == 0 { if data.Height == 0 {
data.Height = height data.Height = height
} }
@@ -48,19 +94,14 @@ func (s *Screen) Render() {
data.Screen = s data.Screen = s
data.IsActive = true data.IsActive = true
data.DefaultColor = colors.Reset data.DefaultColor = colors.Reset
RenderOnFrame(s.component, &frame)
fmt.Print(strings.Join(frame, "\n"))
} }
func (s *Screen) Run() { func (s *Screen) Exit() {
data := s.component.GetComponentData() s.running = false
data.Screen = s ShowCursor()
for {
s.Render()
k, _ := ReadKey()
if s.component.Update(k) {
ShowCursor()
return
}
}
} }
const (
UpdateKindKey = uint8(iota)
UpdateKindTick
)
-37
View File
@@ -1,37 +0,0 @@
# 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 (h *HelloComponent) SetStyle(c interface{}) {
h.Style = osui.SetDefaults(c.(*HelloStyle)).(*HelloStyle)
}
func Hello(name string) *HelloComponent {
return osui.NewComponent(&HelloComponent{
Name: name,
Style: osui.SetDefaults(&HelloStyle{}).(*HelloStyle),
}).(*HelloComponent)
}
```
+34 -67
View File
@@ -7,77 +7,64 @@ 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/isKey" "github.com/orus-dev/osui/keys"
) )
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
Style *ButtonStyle
Text string Text string
Toggle bool clicked bool
Clicked bool
OnClick func(*ButtonComponent) bool
} }
func (b *ButtonComponent) Render() string { func (b *ButtonComponent) Render() string {
osui.UseStyle(b.Style) b.Data.Style.UseStyle()
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.Style.ClickedOutline+strings.Repeat("_", b.Data.Width)+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, colors.Reset+b.Data.Style.ClickedOutline,
colors.Reset+colors.Combine(b.Style.ClickedBackground, b.Style.ClickedForeground)+centerText(b.Text, b.Data.Width)+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+b.Data.DefaultColor, colors.Reset+b.Data.DefaultColor,
colors.Reset+b.Style.ClickedOutline+strings.Repeat("‾", b.Data.Width)+colors.Reset+b.Data.DefaultColor, colors.Reset+b.Data.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.Style.ActiveOutline+strings.Repeat("_", b.Data.Width)+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, colors.Reset+b.Data.Style.ActiveOutline,
colors.Reset+colors.Combine(b.Style.ActiveBackground, b.Style.ActiveForeground)+centerText(b.Text, b.Data.Width)+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+b.Data.DefaultColor, colors.Reset+b.Data.DefaultColor,
colors.Reset+b.Style.ActiveOutline+strings.Repeat("‾", b.Data.Width)+colors.Reset+b.Data.DefaultColor, colors.Reset+b.Data.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.Style.Outline+strings.Repeat("_", b.Data.Width)+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, colors.Reset+b.Data.Style.Outline,
colors.Reset+colors.Combine(b.Style.Background, b.Style.Foreground)+centerText(b.Text, b.Data.Width)+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+b.Data.DefaultColor, colors.Reset+b.Data.DefaultColor,
colors.Reset+b.Style.Outline+strings.Repeat("‾", b.Data.Width)+colors.Reset+b.Data.DefaultColor, colors.Reset+b.Data.Style.Outline+strings.Repeat("‾", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
) )
} }
func (b *ButtonComponent) Update(key string) bool { func (b *ButtonComponent) Update(ctx osui.UpdateContext) bool {
if isKey.Enter(key) { if ctx.UpdateKind == osui.UpdateKindKey {
if !b.OnClick(b) { switch b.Data.Keys[ctx.Key.Name] {
if b.Toggle { case "click":
b.Clicked = !b.Clicked b.Data.OnClick()
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
} }
@@ -85,35 +72,15 @@ func (b *ButtonComponent) GetComponentData() *osui.ComponentData {
return &b.Data return &b.Data
} }
func (b *ButtonComponent) SetStyle(style interface{}) { func Button(param osui.Param, text string) *ButtonComponent {
b.Style = osui.SetDefaults(style).(*ButtonStyle) param.SetDefaultBindings(map[string]string{
} keys.Enter: "click",
})
type BtnParams struct { return param.UseParam(&ButtonComponent{Text: text,
Style ButtonStyle
Toggle bool
OnClick func(*ButtonComponent) bool
Width int
}
func Button(text string, p ...BtnParams) *ButtonComponent {
if len(p) > 0 {
param := p[0]
return &ButtonComponent{Text: text, Style: osui.SetDefaults(&param.Style).(*ButtonStyle),
Data: osui.ComponentData{
Width: osui.LogicValueInt(param.Width == 0, 20, param.Width),
Height: 1,
},
OnClick: fnLogicValue(param.OnClick),
}
}
return &ButtonComponent{Text: text,
Style: osui.SetDefaults(&ButtonStyle{}).(*ButtonStyle),
Data: osui.ComponentData{ Data: osui.ComponentData{
Width: 20, Width: 20,
Height: 1, Height: 1,
}, },
OnClick: func(bc *ButtonComponent) bool { return false }, clicked: false,
} }).(*ButtonComponent)
} }
+39 -47
View File
@@ -5,18 +5,11 @@ 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/isKey" "github.com/orus-dev/osui/keys"
) )
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
} }
@@ -26,8 +19,8 @@ func (d *DivComponent) GetComponentData() *osui.ComponentData {
} }
func (d *DivComponent) Render() string { func (d *DivComponent) Render() string {
osui.UseStyle(d.Style) d.Data.Style.UseStyle()
frame := osui.NewFrame(d.Data.Width, d.Data.Height) 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()
if i == d.ActiveComponent { if i == d.ActiveComponent {
@@ -36,54 +29,53 @@ func (d *DivComponent) Render() string {
data.IsActive = false data.IsActive = false
} }
if data.Width == 0 { if data.Width == 0 {
data.Width = d.Data.Width data.Width = d.Data.Width - 2
} }
if data.Height == 0 { if data.Height == 0 {
data.Height = d.Data.Height data.Height = d.Data.Height - 2
} }
data.DefaultColor = colors.Combine(d.Style.Background, d.Style.Foreground) data.DefaultColor = colors.Combine(d.Data.Style.Background, d.Data.Style.Foreground)
data.Screen = d.Data.Screen data.Screen = d.Data.Screen
osui.RenderOnFrame(c, &frame) osui.RenderOnFrame(c, &frame)
} }
if d.Style.Outline == "" { if d.Data.Style.Outline == "" {
for i, f := range frame { for i, f := range frame {
frame[i] = colors.Combine(d.Style.Foreground, d.Style.Background) + f + colors.Reset frame[i] = colors.Combine(d.Data.Style.Foreground, d.Data.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.Style.Outline + "│" + colors.Combine(d.Style.Foreground, d.Style.Background) + f + colors.Reset + d.Style.Outline + "│" + colors.Reset 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
} }
} }
return " " + d.Style.Outline + strings.Repeat("_", d.Data.Width) + colors.Reset + "\n" + strings.Join(frame, "\n") + "\n " + d.Style.Outline + strings.Repeat("‾", d.Data.Width) + 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
} }
func (d *DivComponent) Update(key string) bool { func (d *DivComponent) Update(ctx osui.UpdateContext) bool {
if isKey.CtrlW(key) { if ctx.UpdateKind == osui.UpdateKindKey {
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "up")) switch d.Data.Keys[ctx.Key.Name] {
} else if isKey.CtrlS(key) { case "up":
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "down")) d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "up"))
} else if isKey.CtrlA(key) { case "down":
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "left")) d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "down"))
} else if isKey.CtrlD(key) { case "left":
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "right")) d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "left"))
} else { case "right":
if len(d.Components) > 0 { d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "right"))
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(key) { if d.Components[d.ActiveComponent].Update(ctx) {
if d.ActiveComponent < len(d.Components)-1 { d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "down"))
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
}
func (d *DivComponent) SetStyle(c interface{}) { return false
d.Style = osui.SetDefaults(c.(*DivStyle)).(*DivStyle)
} }
func (d *DivComponent) updateActive(newIndex int) { func (d *DivComponent) updateActive(newIndex int) {
@@ -92,14 +84,14 @@ func (d *DivComponent) updateActive(newIndex int) {
} }
} }
func (d *DivComponent) AddTo(c *DivComponent) *DivComponent { func Div(param osui.Param, components ...osui.Component) *DivComponent {
*c = *d param.SetDefaultBindings(map[string]string{
return d keys.CtrlW: "up",
} keys.CtrlS: "down",
keys.CtrlA: "left",
func Div(components ...osui.Component) *DivComponent { keys.CtrlD: "right",
return &DivComponent{ })
return param.UseParam(&DivComponent{
Components: components, Components: components,
Style: osui.SetDefaults(&DivStyle{}).(*DivStyle), }).(*DivComponent)
}
} }
+43 -44
View File
@@ -6,19 +6,11 @@ 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/isKey" "github.com/orus-dev/osui/keys"
) )
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
@@ -29,58 +21,65 @@ func (s *InputBoxComponent) GetComponentData() *osui.ComponentData {
} }
func (s InputBoxComponent) Render() string { func (s InputBoxComponent) Render() string {
osui.UseStyle(s.Style) s.Data.Style.UseStyle()
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.Style.Outline+strings.Repeat("_", int(s.max_size))+colors.Reset, colors.Reset+s.Data.Style.Outline+strings.Repeat("_", int(s.max_size))+colors.Reset,
colors.Reset+s.Style.Outline, colors.Reset+s.Data.Style.Outline,
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), ""), 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), ""),
strings.Repeat(" ", int(s.max_size)-len(s.InputData)-osui.LogicValueInt(s.Data.IsActive, 1, 0))+colors.Reset+s.Style.Outline, strings.Repeat(" ", int(s.max_size)-len(s.InputData)-osui.LogicValueInt(s.Data.IsActive, 1, 0))+colors.Reset+s.Data.Style.Outline,
colors.Reset+s.Data.DefaultColor, colors.Reset+s.Data.DefaultColor,
s.Style.Outline+strings.Repeat("‾", int(s.max_size))+colors.Reset+s.Data.DefaultColor, s.Data.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.Style.Outline+strings.Repeat("_", int(s.max_size))+colors.Reset, colors.Reset+s.Data.Style.Outline+strings.Repeat("_", int(s.max_size))+colors.Reset,
colors.Reset+s.Style.Outline, colors.Reset+s.Data.Style.Outline,
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.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.Reset+s.Data.DefaultColor, colors.Reset+s.Data.DefaultColor,
colors.Reset+s.Style.Outline+strings.Repeat("‾", int(s.max_size))+colors.Reset+s.Data.DefaultColor, colors.Reset+s.Data.Style.Outline+strings.Repeat("‾", int(s.max_size))+colors.Reset+s.Data.DefaultColor,
) )
} }
func (s *InputBoxComponent) Update(key string) bool { func (s *InputBoxComponent) Update(ctx osui.UpdateContext) bool {
if isKey.Enter(key) { if ctx.UpdateKind == osui.UpdateKindKey {
return true switch s.Data.Keys[ctx.Key.Name] {
} else if isKey.Backspace(key) { case "done":
if len(s.InputData) > 0 { s.Data.OnClick()
s.InputData = s.InputData[:len(s.InputData)-1] return true
} case "remove":
} else if isKey.Left(key) { if len(s.InputData) > 0 {
if s.cursor > 0 { s.InputData = s.InputData[:len(s.InputData)-1]
s.cursor-- }
} case "left":
} else if isKey.Right(key) { if s.cursor > 0 {
if s.cursor < s.max_size { s.cursor--
s.cursor++ }
} case "right":
} else { if s.cursor < s.max_size {
if len(key) == 1 { s.cursor++
if int(s.max_size) > len(s.InputData) { }
s.InputData += key default:
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 (d *InputBoxComponent) SetStyle(c interface{}) { func InputBox(param osui.Param, max_size uint) *InputBoxComponent {
d.Style = osui.SetDefaults(c.(*InputBoxStyle)).(*InputBoxStyle) param.SetDefaultBindings(map[string]string{
} keys.Enter: "done",
keys.Backspace: "remove",
func InputBox(max_size uint) *InputBoxComponent { keys.Left: "left",
return &InputBoxComponent{max_size: max_size, Style: osui.SetDefaults(&InputBoxStyle{}).(*InputBoxStyle)} keys.Right: "right",
})
return param.UseParam(&InputBoxComponent{max_size: max_size, Data: osui.ComponentData{}}).(*InputBoxComponent)
} }
+36 -49
View File
@@ -5,24 +5,13 @@ 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/isKey" "github.com/orus-dev/osui/keys"
) )
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 {
@@ -30,62 +19,60 @@ func (m *MenuComponent) GetComponentData() *osui.ComponentData {
} }
func (m *MenuComponent) Render() string { func (m *MenuComponent) Render() string {
osui.UseStyle(m.Style) m.Data.Style.UseStyle()
res := []string{} res := []string{}
cursor := m.Style.Cursor cursor := m.Data.Style.Cursor
if !m.Data.IsActive { if !m.Data.IsActive {
cursor = m.Style.CursorInactive cursor = m.Data.Style.InactiveCursor
} }
d, _ := osui.CompressString(m.Style.Cursor, "") d, _ := osui.CompressString(m.Data.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, cursor+colors.Combine(m.Style.SelectedFg, m.Style.SelectedBg)+item+colors.Reset+m.Data.DefaultColor) res = append(res, colors.Reset+cursor+m.Data.Style.SelectedBackground+m.Data.Style.SelectedForeground+item+"\x1b[0m ")
} else { } else {
res = append(res, empty+colors.Combine(m.Style.Fg, m.Style.Bg)+item+colors.Reset+m.Data.DefaultColor) res = append(res, colors.Reset+empty+m.Data.Style.Foreground+m.Data.Style.Background+item)
} }
} }
return strings.Join(res, "\n") return strings.Join(res, "\n")
} }
func (m *MenuComponent) Update(key string) bool { func (m *MenuComponent) Update(ctx osui.UpdateContext) bool {
if isKey.Char(key, "s") { if ctx.UpdateKind == osui.UpdateKindKey {
if m.SelectedItem+1 < len(m.Items) { switch m.Data.Keys[ctx.Key.Name] {
m.SelectedItem++ case "up":
} else { if m.SelectedItem > 0 {
m.SelectedItem = 0 m.SelectedItem--
} 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 (m *MenuComponent) SetStyle(c interface{}) { func Menu(param osui.Param, items ...string) *MenuComponent {
m.Style = osui.SetDefaults(c.(*MenuStyle)).(*MenuStyle) param.SetDefaultBindings(map[string]string{
} keys.Up: "up",
keys.Down: "down",
func (m *MenuComponent) OnSelected(f func(*MenuComponent, bool)) *MenuComponent { keys.Enter: "select",
m.onSelected = f })
return m return param.UseParam(&MenuComponent{
}
func Menu(items ...string) *MenuComponent {
return &MenuComponent{
Items: items, Items: items,
Style: osui.SetDefaults(&MenuStyle{}).(*MenuStyle), }).(*MenuComponent)
}
} }
+41 -43
View File
@@ -6,17 +6,11 @@ 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/isKey" "github.com/orus-dev/osui/keys"
) )
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
} }
@@ -28,15 +22,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)
osui.UseStyle(p.Style) p.Data.Style.UseStyle()
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.Style.Active + "•" + colors.Reset pgs += p.Data.Style.SelectedForeground + data.Style.SelectedBackground + "•" + colors.Reset
data.IsActive = true data.IsActive = true
} else { } else {
pgs += colors.Reset + p.Style.Inactive + "•" pgs += colors.Reset + p.Data.Style.Foreground + data.Style.Background + "•"
data.IsActive = false data.IsActive = false
} }
if data.Width == 0 { if data.Width == 0 {
@@ -52,33 +46,37 @@ 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(key string) bool { func (p *PaginatorComponent) Update(ctx osui.UpdateContext) bool {
if key == "\x1b[Z" { if ctx.UpdateKind == osui.UpdateKindKey {
if p.ActiveComponent > 0 { switch p.Data.Keys[ctx.Key.Name] {
p.updateActive(p.ActiveComponent - 1) case "previous":
} else { if p.ActiveComponent > 0 {
p.updateActive(len(p.Components) - 1) p.updateActive(p.ActiveComponent - 1)
} } else {
} else if isKey.Tab(key) { p.updateActive(len(p.Components) - 1)
if p.ActiveComponent < len(p.Components)-1 { }
p.updateActive(p.ActiveComponent + 1) case "next":
} else { if p.ActiveComponent < len(p.Components)-1 {
p.updateActive(0) p.updateActive(p.ActiveComponent + 1)
} } else {
} else if isKey.Escape(key) { p.updateActive(0)
fmt.Print("\n\n") }
return true case "exit":
} else { p.Data.OnClick()
if len(p.Components) > 0 { fmt.Print("\n\n")
p.Components[p.ActiveComponent].GetComponentData().IsActive = p.Data.IsActive return true
if p.Components[p.ActiveComponent].Update(key) { default:
if p.ActiveComponent < len(p.Components)-1 { if len(p.Components) > 0 {
p.updateActive(p.ActiveComponent + 1) p.Components[p.ActiveComponent].GetComponentData().IsActive = p.Data.IsActive
} else { if p.Components[p.ActiveComponent].Update(ctx) {
p.updateActive(0) if p.ActiveComponent < len(p.Components)-1 {
p.updateActive(p.ActiveComponent + 1)
} else {
p.updateActive(0)
}
} }
} }
} }
@@ -92,13 +90,13 @@ func (p *PaginatorComponent) updateActive(newIndex int) {
} }
} }
func (p *PaginatorComponent) SetStyle(c interface{}) { func Paginator(param osui.Param, pages ...osui.Component) *PaginatorComponent {
p.Style = osui.SetDefaults(c.(*PaginatorStyle)).(*PaginatorStyle) param.SetDefaultBindings(map[string]string{
} keys.ShiftTab: "previous",
keys.Tab: "next",
func Paginator(pages ...osui.Component) *PaginatorComponent { keys.Escape: "exit",
return &PaginatorComponent{ })
return param.UseParam(&PaginatorComponent{
Components: pages, Components: pages,
Style: osui.SetDefaults(&PaginatorStyle{}).(*PaginatorStyle), }).(*PaginatorComponent)
}
} }
+4 -5
View File
@@ -9,7 +9,7 @@ type TextComponent struct {
Text string Text string
} }
func (t *TextComponent) Update(string) bool { func (t *TextComponent) Update(ctx osui.UpdateContext) bool {
return false return false
} }
@@ -21,8 +21,7 @@ func (t TextComponent) Render() string {
return t.Text return t.Text
} }
func (t *TextComponent) SetStyle(interface{}) {} func Text(param osui.Param, text string) *TextComponent {
param.SetDefaultBindings(map[string]string{})
func Text(text string) *TextComponent { return param.UseParam(&TextComponent{Text: text}).(*TextComponent)
return &TextComponent{Text: text}
} }
+46 -27
View File
@@ -8,6 +8,20 @@ import (
"github.com/orus-dev/osui" "github.com/orus-dev/osui"
) )
func WithPosition(x, y int, c osui.Component) osui.Component {
data := c.GetComponentData()
data.X = x
data.Y = y
return c
}
func WithSize(width, height int, c osui.Component) osui.Component {
data := c.GetComponentData()
data.Width = width
data.Height = height
return c
}
func centerText(text string, width int) string { func centerText(text string, width int) string {
if len(text) > width { if len(text) > width {
return text[:width] return text[:width]
@@ -19,33 +33,6 @@ func centerText(text string, width int) string {
return fmt.Sprintf("%s%s%s", leftPadding, text, rightPadding) return fmt.Sprintf("%s%s%s", leftPadding, text, rightPadding)
} }
func fnLogicValue(f func(*ButtonComponent) bool) func(*ButtonComponent) bool {
if f == nil {
return func(*ButtonComponent) bool { return false }
} else {
return f
}
}
func WithPosition(x, y int, c osui.Component) osui.Component {
data := c.GetComponentData()
data.X = x
data.Y = y
return c
}
func WithStyle(style interface{}, c osui.Component) osui.Component {
c.SetStyle(style)
return c
}
func WithSize(width, height int, c osui.Component) osui.Component {
data := c.GetComponentData()
data.Width = width
data.Height = height
return c
}
func findClosestComponent(a []osui.Component, i int, d string) int { func findClosestComponent(a []osui.Component, i int, d string) int {
if len(a) == 0 || i < 0 || i >= len(a) { if len(a) == 0 || i < 0 || i >= len(a) {
return -1 // Invalid input return -1 // Invalid input
@@ -94,3 +81,35 @@ func findClosestComponent(a []osui.Component, i int, d string) int {
return closestIndex return closestIndex
} }
type Id[T osui.Component] struct {
changer func(T) T
Component T
}
func (i *Id[T]) Id(c T) T {
i.Component = c
if i.changer != nil {
return i.changer(i.Component)
}
return i.Component
}
func (i *Id[T]) SetProperties(c func(T) T) {
i.changer = c
}
type Class[T osui.Component] struct {
changer func(T) T
}
func (c *Class[T]) Class(co T) T {
if c.changer != nil {
return c.changer(co)
}
return co
}
func (c *Class[T]) SetProperties(ch func(T) T) {
c.changer = ch
}
+45 -102
View File
@@ -4,81 +4,77 @@ import (
"fmt" "fmt"
"os" "os"
"os/exec" "os/exec"
"reflect"
"regexp" "regexp"
"runtime" "runtime"
"strings" "strings"
"github.com/orus-dev/osui/colors" "github.com/nathan-fiscaletti/consolesize-go"
"golang.org/x/term" "github.com/orus-dev/osui/keys"
) )
func renderLine(frameLine, line_ string, x int) string { var re = regexp.MustCompile(`(\x1b\[([0-9;]*)[a-zA-Z])+`)
frame := []rune(frameLine)
func RenderLine(frame_, line_ string, x int, fm, lm map[int]string) string {
var res strings.Builder
frame := []rune(frame_)
line := []rune(line_) line := []rune(line_)
i := 0 flen, llen := len(frame), len(line)
v := 0 for i := 0; i < flen; i++ {
for j, c := range frame { if i >= x && i-x < llen {
if i+j >= x && v < len(line) { if v, ok := lm[i-x]; ok {
if c != '\b' && line[v] == '\t' { res.WriteString(v)
frame = append(frame[:i+j], append([]rune{' '}, frame[i+j:]...)...)
} }
frame[i+j] = line[v] res.WriteRune(line[i-x])
v++ } else {
if v, ok := fm[i]; ok {
res.WriteString(v)
}
res.WriteRune(frame[i])
} }
if c == '\b' { }
return res.String()
}
func CompressString(input string) (string, map[int]string) {
matchesMap := make(map[int]string)
res := []rune{}
i := 0
for i < len([]rune(input)) {
loc := re.FindStringIndex(string([]rune(input)[i:]))
if loc != nil && loc[0] == 0 {
ansiSeq := re.FindString(string([]rune(input)[i:]))
matchesMap[len(res)] = ansiSeq
i += len([]rune(ansiSeq))
} else {
res = append(res, []rune(input)[i])
i++ i++
} }
} }
return string(frame) return string(res), matchesMap
} }
func RenderOnFrame(c Component, frame *[]string) { func RenderOnFrame(c Component, frame *[]string) {
componentData := c.GetComponentData() componentData := c.GetComponentData()
for i, lo := range strings.Split(c.Render(), "\n") { for i, line := range strings.Split(c.Render(), "\n") {
if int(componentData.Y)+i < len(*frame) { if int(componentData.Y)+i < len(*frame) {
fo := (*frame)[int(componentData.Y)+i] fo, fm := CompressString((*frame)[int(componentData.Y)+i])
f, fa := CompressString(fo, "\b") lo, lm := CompressString(line)
line, la := CompressString(lo, "\t") (*frame)[int(componentData.Y)+i] = RenderLine(fo, lo, componentData.X, fm, lm)
r := renderLine(f, line, int(componentData.X))
(*frame)[int(componentData.Y)+i] = DecompressString(DecompressString(r, la, "\t"), fa, "\b")
} }
} }
} }
func CompressString(input, repl string) (string, []string) { func ReadKey() Key {
pattern := `\x1b\[([0-9;]*)[a-zA-Z]`
re := regexp.MustCompile(pattern)
matches := re.FindAllString(input, -1)
return re.ReplaceAllString(input, repl), matches
}
func DecompressString(modified string, outputArray []string, c string) string {
parts := strings.Split(modified, c)
reconstructed := ""
for i, part := range parts {
reconstructed += part
if i < len(outputArray) {
reconstructed += outputArray[i]
}
}
return reconstructed
}
func ReadKey() (string, error) {
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil {
return "", err
}
defer term.Restore(int(os.Stdin.Fd()), oldState)
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 "", err return Key{Chars: [3]rune{'E', 'r', 'r'}, Name: err.Error()}
} }
return string(b[:n]), nil return Key{Chars: [3]rune{rune(b[0]), rune(b[1]), rune(b[2])}, Name: keys.GetKeyName(string(b[:n]))}
} }
func NewFrame(width, height int) []string { func NewFrame(width, height int) []string {
@@ -102,55 +98,6 @@ 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")
} }
@@ -174,9 +121,5 @@ func LogicValueInt(b bool, _if, _else int) int {
} }
func GetTerminalSize() (int, int) { func GetTerminalSize() (int, int) {
w, h, err := term.GetSize(0) return consolesize.GetConsoleSize()
if err != nil {
panic(err)
}
return w, h
} }