Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(rexctl): add terminal output, themes and error rendering

Hampus3db44f9c72cc
diff --git a/fluxer_rexctl/internal/ui/errors.go b/fluxer_rexctl/internal/ui/errors.go
new file mode 100644
index 000000000..0fe614a4c
--- /dev/null
+++ b/fluxer_rexctl/internal/ui/errors.go
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package ui
+
+import (
+ "errors"
+ "fmt"
+)
+
+const (
+ ExitOK = 0
+ ExitFailed = 1
+ ExitUsage = 2
+ ExitRefused = 3
+ ExitInterrupted = 130
+)
+
+type ExitError struct {
+ Code int
+ Msg string
+ Fix string
+ Err error
+}
+
+func (e *ExitError) Error() string {
+ if e.Msg != "" {
+ return e.Msg
+ }
+ if e.Err != nil {
+ return e.Err.Error()
+ }
+ return fmt.Sprintf("exit %d", e.Code)
+}
+
+func (e *ExitError) Unwrap() error { return e.Err }
+
+func Failed(msg, fix string) *ExitError { return &ExitError{Code: ExitFailed, Msg: msg, Fix: fix} }
+
+func Usage(msg string) *ExitError { return &ExitError{Code: ExitUsage, Msg: msg} }
+
+func Refused(msg, fix string) *ExitError { return &ExitError{Code: ExitRefused, Msg: msg, Fix: fix} }
+
+func MissingFlag(flag string) *ExitError {
+ return &ExitError{Code: ExitUsage, Msg: fmt.Sprintf("Pass --%s.", flag)}
+}
+
+func Wrap(err error, msg, fix string) *ExitError {
+ return &ExitError{Code: ExitFailed, Msg: msg, Fix: fix, Err: err}
+}
+
+func CodeOf(err error) int {
+ if err == nil {
+ return ExitOK
+ }
+ var ee *ExitError
+ if errors.As(err, &ee) {
+ return ee.Code
+ }
+ return ExitFailed
+}
diff --git a/fluxer_rexctl/internal/ui/theme.go b/fluxer_rexctl/internal/ui/theme.go
new file mode 100644
index 000000000..b1a7e1c99
--- /dev/null
+++ b/fluxer_rexctl/internal/ui/theme.go
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package ui
+
+import (
+ "image/color"
+
+ "charm.land/fang/v2"
+ "charm.land/huh/v2"
+ "charm.land/lipgloss/v2"
+)
+
+var (
+ Indigo = lipgloss.Color("#4641d9")
+ Lavender = lipgloss.Color("#b0adff")
+)
+
+type Theme struct {
+ Accent lipgloss.Style
+ Dim lipgloss.Style
+ OK lipgloss.Style
+ Warn lipgloss.Style
+ Fail lipgloss.Style
+ Heading lipgloss.Style
+}
+
+type Glyphs struct {
+ OK string
+ Warn string
+ Fail string
+}
+
+var (
+ RichGlyphs = Glyphs{OK: "✓", Warn: "!", Fail: "✗"}
+ PlainGlyphs = Glyphs{OK: "ok", Warn: "!", Fail: "x"}
+)
+
+func AccentColor(ld lipgloss.LightDarkFunc) color.Color {
+ return ld(Indigo, Lavender)
+}
+
+func NewTheme(dark bool) Theme {
+ ld := lipgloss.LightDark(dark)
+ return Theme{
+ Accent: lipgloss.NewStyle().Foreground(AccentColor(ld)),
+ Dim: lipgloss.NewStyle().Faint(true),
+ OK: lipgloss.NewStyle().Foreground(lipgloss.Green),
+ Warn: lipgloss.NewStyle().Foreground(lipgloss.Yellow),
+ Fail: lipgloss.NewStyle().Foreground(lipgloss.Red),
+ Heading: lipgloss.NewStyle().Bold(true).Foreground(AccentColor(ld)),
+ }
+}
+
+func plainTheme() Theme {
+ s := lipgloss.NewStyle()
+ return Theme{Accent: s, Dim: s, OK: s, Warn: s, Fail: s, Heading: s}
+}
+
+func FangColorScheme(ld lipgloss.LightDarkFunc) fang.ColorScheme {
+ accent := AccentColor(ld)
+ cs := fang.DefaultColorScheme(ld)
+ cs.Title = accent
+ cs.Codeblock = ld(lipgloss.Color("#eeedfb"), lipgloss.Color("#1e1c3a"))
+ cs.Program = accent
+ cs.Command = accent
+ cs.Flag = accent
+ cs.QuotedString = ld(lipgloss.Color("#3a3846"), lipgloss.Color("#d6d4e8"))
+ cs.ErrorHeader = [2]color.Color{lipgloss.Color("#ffffff"), lipgloss.Red}
+ return cs
+}
+
+func HuhTheme(dark bool) *huh.Styles {
+ t := huh.ThemeBase(dark)
+ ld := lipgloss.LightDark(dark)
+ accent := AccentColor(ld)
+ text := ld(lipgloss.Color("235"), lipgloss.Color("252"))
+ dim := ld(lipgloss.Color("243"), lipgloss.Color("246"))
+
+ t.Focused.Base = t.Focused.Base.BorderForeground(accent)
+ t.Focused.Card = t.Focused.Base
+ t.Focused.Title = t.Focused.Title.Foreground(accent).Bold(true)
+ t.Focused.NoteTitle = t.Focused.NoteTitle.Foreground(accent).Bold(true).MarginBottom(1)
+ t.Focused.Description = t.Focused.Description.Foreground(dim)
+ t.Focused.ErrorIndicator = t.Focused.ErrorIndicator.Foreground(lipgloss.Red)
+ t.Focused.ErrorMessage = t.Focused.ErrorMessage.Foreground(lipgloss.Red)
+ t.Focused.SelectSelector = t.Focused.SelectSelector.Foreground(accent)
+ t.Focused.NextIndicator = t.Focused.NextIndicator.Foreground(accent)
+ t.Focused.PrevIndicator = t.Focused.PrevIndicator.Foreground(accent)
+ t.Focused.Option = t.Focused.Option.Foreground(text)
+ t.Focused.SelectedOption = t.Focused.SelectedOption.Foreground(accent)
+ t.Focused.UnselectedOption = t.Focused.UnselectedOption.Foreground(text)
+ t.Focused.MultiSelectSelector = t.Focused.MultiSelectSelector.Foreground(accent)
+ t.Focused.FocusedButton = t.Focused.FocusedButton.Foreground(lipgloss.Color("#ffffff")).Background(Indigo)
+ t.Focused.Next = t.Focused.FocusedButton
+ t.Focused.BlurredButton = t.Focused.BlurredButton.Foreground(text).Background(ld(lipgloss.Color("252"), lipgloss.Color("237")))
+ t.Focused.TextInput.Cursor = t.Focused.TextInput.Cursor.Foreground(accent)
+ t.Focused.TextInput.Placeholder = t.Focused.TextInput.Placeholder.Foreground(dim)
+ t.Focused.TextInput.Prompt = t.Focused.TextInput.Prompt.Foreground(accent)
+
+ t.Blurred = t.Focused
+ t.Blurred.Base = t.Focused.Base.BorderStyle(lipgloss.HiddenBorder())
+ t.Blurred.Card = t.Blurred.Base
+ t.Blurred.NextIndicator = lipgloss.NewStyle()
+ t.Blurred.PrevIndicator = lipgloss.NewStyle()
+
+ t.Group.Title = t.Focused.Title
+ t.Group.Description = t.Focused.Description
+ return t
+}
diff --git a/fluxer_rexctl/internal/ui/ui.go b/fluxer_rexctl/internal/ui/ui.go
new file mode 100644
index 000000000..3c310c933
--- /dev/null
+++ b/fluxer_rexctl/internal/ui/ui.go
@@ -0,0 +1,363 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package ui
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+ "sync"
+ "unicode"
+
+ "charm.land/lipgloss/v2"
+ "github.com/charmbracelet/colorprofile"
+ "github.com/charmbracelet/x/ansi"
+ "golang.org/x/term"
+)
+
+type Mode int
+
+const (
+ ModeRich Mode = iota
+ ModePlain
+ ModeJSON
+)
+
+type Options struct {
+ Context context.Context
+ Yes bool
+ JSON bool
+ Quiet bool
+ Verbose bool
+ Stdin io.Reader
+ Stdout io.Writer
+ Stderr io.Writer
+}
+
+type UI struct {
+ opts Options
+ mode Mode
+ interactive bool
+ accessible bool
+ colour bool
+ stdoutTTY bool
+ stderrTTY bool
+ dark bool
+ theme Theme
+ glyphs Glyphs
+ errw io.Writer
+ outw io.Writer
+
+ themeOnce sync.Once
+ mu sync.Mutex
+ spin *spinner
+}
+
+func New(opts Options) *UI {
+ if opts.Stdin == nil {
+ opts.Stdin = os.Stdin
+ }
+ if opts.Stdout == nil {
+ opts.Stdout = os.Stdout
+ }
+ if opts.Stderr == nil {
+ opts.Stderr = os.Stderr
+ }
+ u := &UI{
+ opts: opts,
+ accessible: os.Getenv("ACCESSIBLE") != "",
+ stdoutTTY: isTerminal(opts.Stdout),
+ stderrTTY: isTerminal(opts.Stderr),
+ dark: true,
+ errw: opts.Stderr,
+ outw: opts.Stdout,
+ }
+ u.colour = u.stderrTTY && colourAllowed()
+ switch {
+ case opts.JSON:
+ u.mode = ModeJSON
+ case u.colour:
+ u.mode = ModeRich
+ default:
+ u.mode = ModePlain
+ }
+ u.interactive = isTerminal(opts.Stdin) && u.stderrTTY && !opts.Yes && !opts.JSON
+ if u.colour {
+ u.theme = NewTheme(true)
+ u.glyphs = RichGlyphs
+ u.errw = colorprofile.NewWriter(opts.Stderr, os.Environ())
+ } else {
+ u.theme = plainTheme()
+ u.glyphs = PlainGlyphs
+ }
+ if u.stdoutTTY && colourAllowed() {
+ u.outw = colorprofile.NewWriter(opts.Stdout, os.Environ())
+ }
+ return u
+}
+
+func colourAllowed() bool {
+ return os.Getenv("NO_COLOR") == "" && os.Getenv("TERM") != "dumb"
+}
+
+func isTerminal(v any) bool {
+ f, ok := v.(interface{ Fd() uintptr })
+ return ok && term.IsTerminal(int(f.Fd()))
+}
+
+func hasDarkBackground(in io.Reader, out io.Writer) bool {
+ fin, ok := in.(*os.File)
+ if !ok || !term.IsTerminal(int(fin.Fd())) {
+ return true
+ }
+ fout, ok := out.(*os.File)
+ if !ok {
+ return true
+ }
+ return lipgloss.HasDarkBackground(fin, fout)
+}
+
+func (u *UI) Mode() Mode { return u.mode }
+func (u *UI) Interactive() bool { return u.interactive }
+func (u *UI) Yes() bool { return u.opts.Yes }
+func (u *UI) Quiet() bool { return u.opts.Quiet }
+func (u *UI) Verbose() bool { return u.opts.Verbose }
+func (u *UI) Stdin() io.Reader { return u.opts.Stdin }
+func (u *UI) Stdout() io.Writer { return u.opts.Stdout }
+func (u *UI) Stderr() io.Writer { return u.opts.Stderr }
+func (u *UI) Theme() Theme { return u.themed() }
+func (u *UI) Glyphs() Glyphs { return u.glyphs }
+func (u *UI) ShowsRex() bool { return u.mode == ModeRich && !u.opts.Quiet }
+
+func (u *UI) themed() Theme {
+ u.themeOnce.Do(func() {
+ if u.colour && !u.accessible {
+ u.dark = hasDarkBackground(u.opts.Stdin, u.opts.Stderr)
+ u.theme = NewTheme(u.dark)
+ }
+ })
+ return u.theme
+}
+
+func (u *UI) emit(s string) {
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ if u.spin != nil {
+ u.spin.clear()
+ }
+ fmt.Fprint(u.errw, s)
+}
+
+func (u *UI) glyphLine(glyph string, style lipgloss.Style, msg, fix string) {
+ var b strings.Builder
+ b.WriteString(style.Render(glyph))
+ b.WriteString(" ")
+ b.WriteString(msg)
+ b.WriteString("\n")
+ if fix != "" {
+ b.WriteString(" ")
+ b.WriteString(fix)
+ b.WriteString("\n")
+ }
+ u.emit(b.String())
+}
+
+func (u *UI) OK(format string, args ...any) {
+ if u.opts.Quiet || u.mode == ModeJSON {
+ return
+ }
+ u.glyphLine(u.glyphs.OK, u.theme.OK, fmt.Sprintf(format, args...), "")
+}
+
+func (u *UI) Warn(msg, fix string) {
+ u.glyphLine(u.glyphs.Warn, u.theme.Warn, msg, fix)
+}
+
+func (u *UI) Fail(msg, fix string) {
+ u.glyphLine(u.glyphs.Fail, u.theme.Fail, msg, fix)
+}
+
+func (u *UI) Info(format string, args ...any) {
+ if u.opts.Quiet || u.mode == ModeJSON {
+ return
+ }
+ u.emit(fmt.Sprintf(format, args...) + "\n")
+}
+
+func (u *UI) Detail(format string, args ...any) {
+ if !u.opts.Verbose {
+ return
+ }
+ u.emit(u.theme.Dim.Render(fmt.Sprintf(format, args...)) + "\n")
+}
+
+func (u *UI) Result(s string) {
+ fmt.Fprintln(u.opts.Stdout, s)
+}
+
+func (u *UI) Highlight(s string) {
+ if !u.stdoutTTY {
+ fmt.Fprintln(u.opts.Stdout, s)
+ return
+ }
+ style := lipgloss.NewStyle()
+ if u.outw != u.opts.Stdout {
+ u.themed()
+ style = style.Bold(true).Foreground(AccentColor(lipgloss.LightDark(u.dark)))
+ }
+ fmt.Fprintf(u.outw, "\n %s\n\n", style.Render(s))
+}
+
+func (u *UI) JSON(v any) error {
+ enc := json.NewEncoder(u.opts.Stdout)
+ enc.SetIndent("", " ")
+ enc.SetEscapeHTML(false)
+ return enc.Encode(v)
+}
+
+func (u *UI) Table(headers []string, rows [][]string) {
+ widths := make([]int, len(headers))
+ for i, h := range headers {
+ widths[i] = ansi.StringWidth(h)
+ }
+ for _, r := range rows {
+ for i, c := range r {
+ if i < len(widths) {
+ widths[i] = max(widths[i], ansi.StringWidth(c))
+ }
+ }
+ }
+ format := func(cells []string) string {
+ parts := make([]string, len(cells))
+ for i, c := range cells {
+ if i == len(cells)-1 || i >= len(widths) {
+ parts[i] = c
+ continue
+ }
+ parts[i] = c + strings.Repeat(" ", widths[i]-ansi.StringWidth(c))
+ }
+ return strings.TrimRight(strings.Join(parts, " "), " ")
+ }
+ total := 3 * (len(widths) - 1)
+ for _, w := range widths {
+ total += w
+ }
+ if cols := u.columns(); cols > 0 && total > cols && len(headers) > 2 {
+ u.records(headers, rows)
+ return
+ }
+ head := format(headers)
+ if u.outw != u.opts.Stdout {
+ head = lipgloss.NewStyle().Bold(true).Render(head)
+ }
+ fmt.Fprintln(u.outw, head)
+ for _, r := range rows {
+ fmt.Fprintln(u.outw, format(r))
+ }
+}
+
+func (u *UI) columns() int {
+ f, ok := u.opts.Stdout.(interface{ Fd() uintptr })
+ if !ok || !term.IsTerminal(int(f.Fd())) {
+ return 0
+ }
+ w, _, err := term.GetSize(int(f.Fd()))
+ if err != nil {
+ return 0
+ }
+ return w
+}
+
+func (u *UI) records(headers []string, rows [][]string) {
+ label := 0
+ for _, h := range headers {
+ label = max(label, ansi.StringWidth(h))
+ }
+ for i, r := range rows {
+ if i > 0 {
+ fmt.Fprintln(u.outw)
+ }
+ for j, h := range headers {
+ if j >= len(r) || r[j] == "" {
+ continue
+ }
+ name := h + strings.Repeat(" ", label-ansi.StringWidth(h))
+ if u.outw != u.opts.Stdout {
+ name = lipgloss.NewStyle().Bold(true).Render(name)
+ }
+ fmt.Fprintf(u.outw, "%s %s\n", name, r[j])
+ }
+ }
+}
+
+func (u *UI) ReportError(err error) {
+ if err == nil {
+ return
+ }
+ var ee *ExitError
+ if !errors.As(err, &ee) {
+ u.Fail(sentence(err.Error()), "")
+ return
+ }
+ if ee.Code == ExitInterrupted && ee.Msg == "" {
+ return
+ }
+ msg := ee.Msg
+ if msg == "" && ee.Err != nil {
+ msg = sentence(ee.Err.Error())
+ }
+ if ee.Code == ExitUsage {
+ var b strings.Builder
+ b.WriteString(msg + "\n")
+ if ee.Fix != "" {
+ b.WriteString(ee.Fix + "\n")
+ }
+ u.emit(b.String())
+ } else {
+ u.Fail(msg, ee.Fix)
+ }
+ if ee.Err != nil && ee.Msg != "" {
+ u.Detail("%v", ee.Err)
+ }
+}
+
+func sentence(s string) string {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ return s
+ }
+ r := []rune(s)
+ r[0] = unicode.ToUpper(r[0])
+ s = string(r)
+ if !strings.HasSuffix(s, ".") && !strings.HasSuffix(s, "?") {
+ s += "."
+ }
+ return s
+}
+
+func QuietTerminal() func() {
+ if colourAllowed() || !isTerminal(os.Stdout) {
+ return func() {}
+ }
+ real := os.Stdout
+ r, w, err := os.Pipe()
+ if err != nil {
+ return func() {}
+ }
+ done := make(chan struct{})
+ go func() {
+ _, _ = io.Copy(real, r)
+ close(done)
+ }()
+ os.Stdout = w
+ return func() {
+ os.Stdout = real
+ _ = w.Close()
+ <-done
+ _ = r.Close()
+ }
+}