Author SHA1 Message Date
selimaj-dev 9cd88b0350 screen update 2024-10-05 15:28:25 +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
selimaj-dev 716d1d4a08 First version 2024-09-29 13:40:46 +02:00
selimaj-dev 8592b1cc50 menus 2024-09-28 19:29:01 +02:00
selimaj-dev 90f106f127 buttons and styles 2024-09-28 17:12:45 +02:00
selimaj-dev 5a94fc34ad bugs fixed 2024-09-27 21:48:28 +02:00
selimaj-dev fdbb54a557 renderLine fine length 2024-09-27 20:51:22 +02:00
selimaj-dev 5024087358 renderLine fine length 2024-09-27 20:50:15 +02:00
selimaj-dev cf93b3383f bug fix (There is a small bug on inputBox again) 2024-09-27 14:38:39 +02:00
selimaj-dev 3b2ff24c1f bug fix but still a new one :( 2024-09-26 23:03:24 +02:00
selimaj-dev 4214f96c61 bug fix but still a new one :( 2024-09-26 23:03:17 +02:00
RudideC 3b3e92fae5 fix bug but now new bug hehe
fixed the bug where the "some text here" example would have spaces inserted inside when typing in a textbox
2024-09-26 19:57:20 +02:00
selimaj-dev 179de20dba styling 2024-09-26 17:49:03 +02:00
selimaj-dev 8f375efe41 divs and paginators 2024-09-25 12:29:03 +02:00
selimaj-dev 905a77f8b0 paginator and styles 2024-09-24 20:42:44 +02:00
selimaj-dev 3529f3dcc5 structure change 2024-09-24 07:24:53 +02:00
selimaj-dev 7546933e81 bug fix and Run all components 2024-09-23 16:42:40 +02:00
21 changed files with 1122 additions and 230 deletions
+3
View File
@@ -23,3 +23,6 @@ go.work.sum
# env file
.env
# macOS
.DS_Store
+19 -7
View File
@@ -1,18 +1,30 @@
# osui
A Component-based TUI library written in go!
<div style="text-align: center;">
<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
package main
import (
"github.com/orus-dev/osui/osui"
"github.com/orus-dev/osui/osui/ui"
"github.com/orus-dev/osui"
"github.com/orus-dev/osui/ui"
)
func main() {
components := osui.NewRender()
components.Add(ui.Text("Hello, World!"))
components.Render()
app := ui.Div(
ui.Text("Hello, World!")
)
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

+60
View File
@@ -0,0 +1,60 @@
package colors
import (
"fmt"
"regexp"
"strings"
)
const (
Reset = "\x1b[0m"
Bold = "\x1b[1m"
Underline = "\x1b[4m"
Italic = "\x1b[3m"
Reverse = "\x1b[7m"
Strike = "\x1b[9m"
Black = "\x1b[30m"
Red = "\x1b[31m"
Green = "\x1b[32m"
Yellow = "\x1b[33m"
Blue = "\x1b[34m"
Magenta = "\x1b[35m"
Cyan = "\x1b[36m"
White = "\x1b[37m"
)
func Rgb(r, g, b uint8) string {
return fmt.Sprintf("\x1b[38;2;%d;%d;%dm", r, g, b)
}
func AsBg(s string) string {
re, _ := regexp.Compile(`\x1b\[3([0-9]+)`)
return re.ReplaceAllStringFunc(s, func(match string) string {
groups := re.FindStringSubmatch(match)
if len(groups) >= 2 {
return fmt.Sprintf("\x1b[4%s", groups[1])
}
return match
})
}
func AsFg(s string) string {
re, _ := regexp.Compile(`\x1b\[4([0-9]+)`)
return re.ReplaceAllStringFunc(s, func(match string) string {
groups := re.FindStringSubmatch(match)
if len(groups) >= 2 {
return fmt.Sprintf("\x1b[3%s", groups[1])
}
return match
})
}
func Combine(s, s1 string) string {
if strings.Contains(s, Reset) {
return s + s1
} else {
return s1 + s
}
}
+62
View File
@@ -0,0 +1,62 @@
package main
import (
"github.com/orus-dev/osui"
"github.com/orus-dev/osui/colors"
"github.com/orus-dev/osui/ui"
)
func main() {
screen := osui.NewScreen(App())
screen.Run()
}
func App() *ui.PaginatorComponent {
w, h := osui.GetTerminalSize()
var keybindings ui.Class[*ui.TextComponent]
keybindings.SetProperties(func(tc *ui.TextComponent) *ui.TextComponent {
tc.Text = colors.Blue + tc.Text
tc.Data.Y = h - 3
return tc
})
return ui.Paginator(
// Page 1
ui.Div(
ui.Text("Welcome to the example! The blue text on the bottom show the keybindings"),
keybindings.Class(ui.Text("Next Page: Tab. Previous Page: shift + tab")),
),
// 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. ")),
),
)
}
+3 -1
View File
@@ -2,7 +2,9 @@ module github.com/orus-dev/osui
go 1.23.1
require golang.org/x/term v0.24.0 // direct
require (
github.com/nathan-fiscaletti/consolesize-go v0.0.0-20220204101620-317176b6684d
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/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.24.0 h1:Mh5cbb+Zk2hqqXNO7S1iTjEphVL+jb8ZWaqh/g+JWkM=
+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"
}
+43 -135
View File
@@ -5,160 +5,68 @@ import (
"os"
"strings"
"github.com/orus-dev/osui/colors"
"golang.org/x/term"
)
type ComponentData struct {
X int
Y int
Width int
Height int
DefaultColor string
IsActive bool
Screen *Screen
}
type Component interface {
Render(*ComponentWrapper) string
Run(*ComponentWrapper) error
Render() string
GetComponentData() *ComponentData
Update(string) bool
}
type ComponentWrapper struct {
type Screen struct {
Component Component
X uint16
Y uint16
render *Render
Update func(*ComponentWrapper, any) UpdateOutput_
}
func (c *ComponentWrapper) Run() {
c.Component.Run(c)
func NewScreen(c Component) *Screen {
HideCursor()
s := &Screen{Component: c}
return s
}
func (cw *ComponentWrapper) Render(c Component) error {
cw.Component = c
return cw.render.Render()
}
func (c *ComponentWrapper) SetRender(r *Render) {
c.render = r
}
func NewComponent(c Component) *ComponentWrapper {
return &ComponentWrapper{
Component: c,
Update: func(cw *ComponentWrapper, a any) UpdateOutput_ { return UpdateOutput.Continue },
func (s *Screen) Render() {
width, height := GetTerminalSize()
frame := NewFrame(width, height)
data := s.Component.GetComponentData()
if data.Height == 0 {
data.Height = height
}
}
type Render struct {
components []*ComponentWrapper
}
func NewRender() *Render {
return &Render{components: []*ComponentWrapper{}}
}
func (r *Render) Add(c *ComponentWrapper) *ComponentWrapper {
c.SetRender(r)
r.components = append(r.components, c)
return c
}
func (r *Render) Render() error {
if data.Width == 0 {
data.Width = width
}
data.Screen = s
data.IsActive = true
data.DefaultColor = colors.Reset
RenderOnFrame(s.Component, &frame)
Clear()
width, height, err := term.GetSize(0)
if err != nil {
return fmt.Errorf("error getting the terminal size: %s", err)
}
frame := make([]string, height)
for i := 0; i < height; i++ {
frame[i] = strings.Repeat(" ", width)
}
for _, c := range r.components {
for i, line := range strings.Split(c.Component.Render(c), "\n") {
if int(c.Y)+i < len(frame) {
frame[int(c.Y)+i] = renderLine(frame[int(c.Y)+i], line, int(c.X))
}
}
}
fmt.Print(strings.Join(frame, "\n"))
return nil
fmt.Print(strings.Join(frame, ""))
}
func Clear() {
fmt.Print("\x1b[H\x1b[2J\x1b[3J")
}
func renderLine(frameLine, line string, x int) string {
result := ""
if x >= len(frameLine) {
return result
}
lChars := []rune(line)
for i, c := range frameLine {
if i >= x && len(lChars) > i-x {
result += string(lChars[i-x])
} else {
result += string(c)
}
}
return result
}
func ReadKey() (string, error) {
func (s *Screen) Run() {
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil {
return "", err
panic(err)
}
defer term.Restore(int(os.Stdin.Fd()), oldState)
var b [3]byte
n, err := os.Stdin.Read(b[:])
if err != nil {
return "", err
}
return string(b[:n]), nil
}
func KeyUpdate(keys map[string]UpdateOutput_) func(c *ComponentWrapper, key any) UpdateOutput_ {
return func(c *ComponentWrapper, k any) UpdateOutput_ {
action, ok := keys[fmt.Sprint(k)]
if ok {
return action
} else {
return UpdateOutput.Continue
data := s.Component.GetComponentData()
data.Screen = s
for {
s.Render()
k, _ := ReadKey()
if s.Component.Update(k) {
ShowCursor()
return
}
}
}
type UpdateOutput_ = int
type updateOutput struct {
/*Continue the default check*/
Continue UpdateOutput_
/*Jump to the next check*/
Jmp UpdateOutput_
/*Leave the loop and stop the function*/
Exit UpdateOutput_
}
var UpdateOutput = updateOutput{Continue: 0, Jmp: 1, Exit: 2}
/*
Keys
*/
type Key_ = string
type key struct {
Enter Key_
Tab Key_
Backspace Key_
Escape Key_
Up Key_
Down Key_
Right Key_
Left Key_
}
var Key = key{
Enter: "\r",
Tab: "\t",
Backspace: "\x7f",
Escape: "\x1b",
Up: "\x1b[A",
Down: "\x1b[B",
Right: "\x1b[C",
Left: "\x1b[D",
}
+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)
}
```
+113
View File
@@ -0,0 +1,113 @@
package ui
import (
"fmt"
"strings"
"time"
"github.com/orus-dev/osui"
"github.com/orus-dev/osui/colors"
"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 {
Data osui.ComponentData
Style *ButtonStyle
Text string
Toggle bool
Clicked bool
on_click func(*ButtonComponent) bool
}
func (b *ButtonComponent) Render() string {
osui.UseStyle(b.Style)
if b.Clicked {
return fmt.Sprintf(" %s\n%s│%s│%s\n %s",
colors.Reset+b.Style.ClickedOutline+strings.Repeat("_", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
colors.Reset+b.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.Style.ClickedOutline+strings.Repeat("‾", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
)
}
if b.Data.IsActive {
return fmt.Sprintf(" %s\n%s│%s│%s\n %s",
colors.Reset+b.Style.ActiveOutline+strings.Repeat("_", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
colors.Reset+b.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.Style.ActiveOutline+strings.Repeat("‾", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
)
}
return fmt.Sprintf(" %s\n%s│%s│%s\n %s",
colors.Reset+b.Style.Outline+strings.Repeat("_", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
colors.Reset+b.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.Style.Outline+strings.Repeat("‾", b.Data.Width-2)+colors.Reset+b.Data.DefaultColor,
)
}
func (b *ButtonComponent) Update(key string) bool {
if isKey.Enter(key) {
if !b.on_click(b) {
if b.Toggle {
b.Clicked = !b.Clicked
return false
}
b.Clicked = true
b.Data.Screen.Render()
time.Sleep(time.Millisecond * 120)
b.Clicked = false
}
}
return false
}
func (b *ButtonComponent) GetComponentData() *osui.ComponentData {
return &b.Data
}
func (b *ButtonComponent) Params(param ButtonParams) *ButtonComponent {
b.Style = osui.SetDefaults(&param.Style).(*ButtonStyle)
if param.OnClick != nil {
b.on_click = param.OnClick
}
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{
Width: 20,
Height: 1,
},
on_click: func(bc *ButtonComponent) bool { return false },
}
}
-73
View File
@@ -1,73 +0,0 @@
package ui
import (
"fmt"
"strings"
"github.com/orus-dev/osui"
)
type ComponentText struct {
Text string
}
func (t ComponentText) Render(cw *osui.ComponentWrapper) string {
return t.Text
}
func (t ComponentText) Run(cw *osui.ComponentWrapper) error {
return nil
}
type ComponentInputBox struct {
max_size uint
data string
}
func (s ComponentInputBox) Render(cw *osui.ComponentWrapper) string {
return fmt.Sprintf(
" %s\n|%s%s|\n %s",
strings.Repeat("_", int(s.max_size)),
s.data,
strings.Repeat(" ", int(s.max_size)-len(s.data)),
strings.Repeat("‾", int(s.max_size)),
)
}
func (s ComponentInputBox) Run(cw *osui.ComponentWrapper) error {
for {
fmt.Printf("\x1B[%d;%dH", cw.Y+2, int(cw.X+2)+len(s.data))
key, err := osui.ReadKey()
if err != nil {
fmt.Println(err)
break
}
switch cw.Update(cw, key) {
case osui.UpdateOutput.Jmp:
continue
case osui.UpdateOutput.Exit:
fmt.Print("\n\n")
return nil
}
switch key {
case osui.Key.Enter:
fmt.Print("\n\n")
return nil
case osui.Key.Backspace:
if len(s.data) > 0 {
s.data = s.data[:len(s.data)-1]
}
default:
if int(s.max_size) > len(s.data) {
s.data += key
}
}
cw.Render(s)
}
return nil
}
+108
View File
@@ -0,0 +1,108 @@
package ui
import (
"strings"
"github.com/orus-dev/osui"
"github.com/orus-dev/osui/colors"
"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 {
Data osui.ComponentData
Style *DivStyle
Components []osui.Component
ActiveComponent int
}
func (d *DivComponent) GetComponentData() *osui.ComponentData {
return &d.Data
}
func (d *DivComponent) Render() string {
osui.UseStyle(d.Style)
frame := osui.NewFrame(d.Data.Width-2, d.Data.Height-2)
for i, c := range d.Components {
data := c.GetComponentData()
if i == d.ActiveComponent {
data.IsActive = d.Data.IsActive
} else {
data.IsActive = false
}
if data.Width == 0 {
data.Width = d.Data.Width - 2
}
if data.Height == 0 {
data.Height = d.Data.Height - 2
}
data.DefaultColor = colors.Combine(d.Style.Background, d.Style.Foreground)
data.Screen = d.Data.Screen
osui.RenderOnFrame(c, &frame)
}
if d.Style.Outline == "" {
for i, f := range frame {
frame[i] = colors.Combine(d.Style.Foreground, d.Style.Background) + f + colors.Reset
}
return strings.Join(frame, "\n")
} else {
for i, f := range frame {
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.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(key string) bool {
if isKey.CtrlW(key) {
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "up"))
} else if isKey.CtrlS(key) {
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "down"))
} else if isKey.CtrlA(key) {
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "left"))
} else if isKey.CtrlD(key) {
d.updateActive(findClosestComponent(d.Components, d.ActiveComponent, "right"))
} else {
if len(d.Components) > 0 {
d.Components[d.ActiveComponent].GetComponentData().IsActive = d.Data.IsActive
if d.Components[d.ActiveComponent].Update(key) {
if d.ActiveComponent < len(d.Components)-1 {
d.updateActive(d.ActiveComponent + 1)
} else {
return true
}
}
}
}
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) {
if newIndex >= 0 && newIndex < len(d.Components) && len(d.Components) > 0 {
d.ActiveComponent = newIndex
}
}
func Div(components ...osui.Component) *DivComponent {
return &DivComponent{
Components: components,
Style: osui.SetDefaults(&DivStyle{}).(*DivStyle),
}
}
+95
View File
@@ -0,0 +1,95 @@
package ui
import (
"fmt"
"strings"
"github.com/orus-dev/osui"
"github.com/orus-dev/osui/colors"
"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 {
Data osui.ComponentData
Style *InputBoxStyle
max_size uint
cursor uint
InputData string
}
func (s *InputBoxComponent) GetComponentData() *osui.ComponentData {
return &s.Data
}
func (s InputBoxComponent) Render() string {
osui.UseStyle(s.Style)
if s.max_size > uint(len(s.InputData)) {
return fmt.Sprintf(
" %s\n%s│%s%s│%s\n %s",
colors.Reset+s.Style.Outline+strings.Repeat("_", int(s.max_size))+colors.Reset,
colors.Reset+s.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), ""),
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,
s.Style.Outline+strings.Repeat("‾", int(s.max_size))+colors.Reset+s.Data.DefaultColor,
)
}
return fmt.Sprintf(
" %s\n%s│%s%s\n %s",
colors.Reset+s.Style.Outline+strings.Repeat("_", int(s.max_size))+colors.Reset,
colors.Reset+s.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.Reset+s.Data.DefaultColor,
colors.Reset+s.Style.Outline+strings.Repeat("‾", int(s.max_size))+colors.Reset+s.Data.DefaultColor,
)
}
func (s *InputBoxComponent) Update(key string) bool {
if isKey.Enter(key) {
return true
} else if isKey.Backspace(key) {
if len(s.InputData) > 0 {
s.InputData = s.InputData[:len(s.InputData)-1]
}
} else if isKey.Left(key) {
if s.cursor > 0 {
s.cursor--
}
} else if isKey.Right(key) {
if s.cursor < s.max_size {
s.cursor++
}
} else {
if len(key) == 1 {
if int(s.max_size) > len(s.InputData) {
s.InputData += key
}
}
}
return false
}
func (b *InputBoxComponent) Params(p interface{}) *InputBoxComponent {
param := p.(InputBoxParams)
b.Style = osui.SetDefaults(&param.Style).(*InputBoxStyle)
b.Data.Width = osui.LogicValueInt(param.Width == 0, 20, param.Width)
return b
}
func InputBox(max_size uint) *InputBoxComponent {
return &InputBoxComponent{max_size: max_size, Style: osui.SetDefaults(&InputBoxStyle{}).(*InputBoxStyle)}
}
+93
View File
@@ -0,0 +1,93 @@
package ui
import (
"strings"
"github.com/orus-dev/osui"
"github.com/orus-dev/osui/colors"
"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 {
Data osui.ComponentData
Style *MenuStyle
Items []string
SelectedItem int
OnSelected func(*MenuComponent, bool)
}
func (m *MenuComponent) GetComponentData() *osui.ComponentData {
return &m.Data
}
func (m *MenuComponent) Render() string {
osui.UseStyle(m.Style)
res := []string{}
cursor := m.Style.Cursor
if !m.Data.IsActive {
cursor = m.Style.CursorInactive
}
d, _ := osui.CompressString(m.Style.Cursor)
empty := strings.Repeat(" ", len(d))
for i, item := range m.Items {
if i == m.SelectedItem {
res = append(res, cursor+colors.Combine(m.Style.SelectedFg, m.Style.SelectedBg)+item+colors.Reset+m.Data.DefaultColor)
} else {
res = append(res, empty+colors.Combine(m.Style.Fg, m.Style.Bg)+item+colors.Reset+m.Data.DefaultColor)
}
}
return strings.Join(res, "\n")
}
func (m *MenuComponent) Update(key string) bool {
if isKey.Char(key, "s") {
if m.SelectedItem+1 < len(m.Items) {
m.SelectedItem++
} else {
m.SelectedItem = 0
}
} 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
}
func (b *MenuComponent) Params(param MenuParams) *MenuComponent {
b.Style = osui.SetDefaults(&param.Style).(*MenuStyle)
b.OnSelected = param.OnSelected
return b
}
func Menu(items ...string) *MenuComponent {
return &MenuComponent{
Items: items,
Style: osui.SetDefaults(&MenuStyle{}).(*MenuStyle),
}
}
+112
View File
@@ -0,0 +1,112 @@
package ui
import (
"fmt"
"strings"
"github.com/orus-dev/osui"
"github.com/orus-dev/osui/colors"
"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 {
Data osui.ComponentData
Style *PaginatorStyle
Components []osui.Component
ActiveComponent int
}
func (p *PaginatorComponent) GetComponentData() *osui.ComponentData {
return &p.Data
}
func (p *PaginatorComponent) Render() string {
width, _ := osui.GetTerminalSize()
pgs := strings.Repeat(" ", (width-len(p.Components))/2)
osui.UseStyle(p.Style)
frame := osui.NewFrame(p.Data.Width, p.Data.Height)
for i, c := range p.Components {
data := c.GetComponentData()
if i == p.ActiveComponent {
pgs += p.Style.Active + "•" + colors.Reset
data.IsActive = true
} else {
pgs += colors.Reset + p.Style.Inactive + "•"
data.IsActive = false
}
if data.Width == 0 {
data.Width = p.Data.Width
}
if data.Height == 0 {
data.Height = p.Data.Height
}
data.DefaultColor = p.Data.DefaultColor
data.Screen = p.Data.Screen
}
osui.RenderOnFrame(p.Components[p.ActiveComponent], &frame)
for i, f := range frame {
frame[i] = colors.Reset + p.Data.DefaultColor + f + colors.Reset
}
return fmt.Sprintf("%s\n%s", pgs, colors.Reset+strings.Join(frame, "\n"))
}
func (p *PaginatorComponent) Update(key string) bool {
if key == "\x1b[Z" {
if p.ActiveComponent > 0 {
p.updateActive(p.ActiveComponent - 1)
} else {
p.updateActive(len(p.Components) - 1)
}
} else if isKey.Tab(key) {
if p.ActiveComponent < len(p.Components)-1 {
p.updateActive(p.ActiveComponent + 1)
} else {
p.updateActive(0)
}
} else if isKey.Escape(key) {
fmt.Print("\n\n")
return true
} else {
if len(p.Components) > 0 {
p.Components[p.ActiveComponent].GetComponentData().IsActive = p.Data.IsActive
if p.Components[p.ActiveComponent].Update(key) {
if p.ActiveComponent < len(p.Components)-1 {
p.updateActive(p.ActiveComponent + 1)
} else {
p.updateActive(0)
}
}
}
}
return false
}
func (p *PaginatorComponent) updateActive(newIndex int) {
if newIndex >= 0 && newIndex < len(p.Components) && len(p.Components) > 0 {
p.ActiveComponent = newIndex
}
}
func (b *PaginatorComponent) Params(p interface{}) *PaginatorComponent {
param := p.(PaginatorParams)
b.Style = osui.SetDefaults(&param.Style).(*PaginatorStyle)
return b
}
func Paginator(pages ...osui.Component) *PaginatorComponent {
return &PaginatorComponent{
Components: pages,
Style: osui.SetDefaults(&PaginatorStyle{}).(*PaginatorStyle),
}
}
+26
View File
@@ -0,0 +1,26 @@
package ui
import (
"github.com/orus-dev/osui"
)
type TextComponent struct {
Data osui.ComponentData
Text string
}
func (t *TextComponent) Update(string) bool {
return false
}
func (t *TextComponent) GetComponentData() *osui.ComponentData {
return &t.Data
}
func (t TextComponent) Render() string {
return t.Text
}
func Text(text string) *TextComponent {
return &TextComponent{Text: text}
}
-13
View File
@@ -1,13 +0,0 @@
package ui
import (
"github.com/orus-dev/osui"
)
func InputBox(max_size uint) *osui.ComponentWrapper {
return osui.NewComponent(ComponentInputBox{max_size: max_size})
}
func Text(text string) *osui.ComponentWrapper {
return osui.NewComponent(ComponentText{Text: text})
}
+115
View File
@@ -0,0 +1,115 @@
package ui
import (
"fmt"
"math"
"strings"
"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 {
if len(text) > width {
return text[:width]
}
padding := (width - len(text)) / 2
leftPadding := strings.Repeat(" ", padding)
rightPadding := strings.Repeat(" ", padding)
return fmt.Sprintf("%s%s%s", leftPadding, text, rightPadding)
}
func findClosestComponent(a []osui.Component, i int, d string) int {
if len(a) == 0 || i < 0 || i >= len(a) {
return -1 // Invalid input
}
current := a[i].GetComponentData()
closestIndex := -1
minDistance := math.MaxFloat64
for j, c := range a {
component := c.GetComponentData()
if i == j {
continue // Skip the current component
}
// Check if the component is in the correct direction
isValidDirection := false
switch d {
case "up":
if component.Y < current.Y {
isValidDirection = true
}
case "down":
if component.Y > current.Y {
isValidDirection = true
}
case "left":
if component.X < current.X {
isValidDirection = true
}
case "right":
if component.X > current.X {
isValidDirection = true
}
}
// If the direction is valid, calculate distance
if isValidDirection {
distance := math.Hypot(float64(component.X-current.X), float64(component.Y-current.Y))
if distance < minDistance {
minDistance = distance
closestIndex = j
}
}
}
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
}
+176
View File
@@ -0,0 +1,176 @@
package osui
import (
"fmt"
"os"
"os/exec"
"reflect"
"regexp"
"runtime"
"strings"
"github.com/nathan-fiscaletti/consolesize-go"
"github.com/orus-dev/osui/colors"
)
var re = regexp.MustCompile(`(\x1b\[([0-9;]*)[a-zA-Z])+`)
func RenderLine(frame_, line_ string, x int, fm, lm map[int]string) string {
var res strings.Builder
frame := []rune(frame_)
line := []rune(line_)
flen, llen := len(frame), len(line)
for i := 0; i < flen; i++ {
if i >= x && i-x < llen {
if v, ok := lm[i-x]; ok {
res.WriteString(v)
}
res.WriteRune(line[i-x])
} else {
if v, ok := fm[i]; ok {
res.WriteString(v)
}
res.WriteRune(frame[i])
}
}
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++
}
}
return string(res), matchesMap
}
func RenderOnFrame(c Component, frame *[]string) {
componentData := c.GetComponentData()
for i, line := range strings.Split(c.Render(), "\n") {
if int(componentData.Y)+i < len(*frame) {
fo, fm := CompressString((*frame)[int(componentData.Y)+i])
lo, lm := CompressString(line)
(*frame)[int(componentData.Y)+i] = RenderLine(fo, lo, componentData.X, fm, lm)
}
}
}
func ReadKey() (string, error) {
var b [3]byte
n, err := os.Stdin.Read(b[:])
if err != nil {
return "", err
}
return string(b[:n]), nil
}
func NewFrame(width, height int) []string {
frame := make([]string, height)
for i := 0; i < height; i++ {
frame[i] = strings.Repeat(" ", width)
}
return frame
}
func Clear() {
switch runtime.GOOS {
case "windows":
cmd := exec.Command("cmd", "/c", "cls")
cmd.Stdout = os.Stdout
cmd.Run()
default:
cmd := exec.Command("clear")
cmd.Stdout = os.Stdout
cmd.Run()
}
}
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() {
fmt.Print("\033[?25h")
}
func HideCursor() {
fmt.Print("\033[?25l")
}
func LogicValue(b bool, _if, _else string) string {
if b {
return _if
}
return _else
}
func LogicValueInt(b bool, _if, _else int) int {
if b {
return _if
}
return _else
}
// Get the terminal size
func GetTerminalSize() (int, int) {
return consolesize.GetConsoleSize()
}