pelican/internal/ui/cardform.go
Dan Anglin d921231017
refactor(ui): change type cardModal to cardForm
- Change type cardModal to cardForm because it is a Form and not a
  Modal.
- Text the card's details directly from the form items when the Save
  button is pressed instead of updating fields in the cardForm value
  every time a change is made to the input fields.
2024-01-12 12:33:18 +00:00

120 lines
2.5 KiB
Go

package ui
import (
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
)
type cardFormMode int
const (
create cardFormMode = iota
edit
)
type cardForm struct {
*tview.Form
frame *tview.Frame
titleLabel string
descLabel string
done func(string, string, bool, cardFormMode)
mode cardFormMode
}
func newCardForm() *cardForm {
var (
background = tcell.ColorBlack.TrueColor()
buttonBackground = tcell.ColorBlueViolet.TrueColor()
textColour = tcell.ColorWhite.TrueColor()
fieldBackground = tcell.ColorGrey.TrueColor()
labelColour = tcell.ColorGreen.TrueColor()
form = tview.NewForm()
)
c := cardForm{
Form: form,
frame: tview.NewFrame(form),
done: nil,
mode: create,
titleLabel: "Title",
descLabel: "Description",
}
// Stylise the buttons
c.SetButtonsAlign(tview.AlignCenter).
SetButtonBackgroundColor(buttonBackground).
SetButtonTextColor(textColour).
SetBorderPadding(0, 0, 0, 0)
// Stylise the form
c.SetLabelColor(labelColour).
SetFieldBackgroundColor(fieldBackground).
SetFieldTextColor(textColour).
SetBackgroundColor(background)
// Stylise the frame around the form
c.frame.SetBorders(0, 0, 1, 0, 0, 0).
SetBorder(true).
SetBorderColor(tcell.ColorOrangeRed.TrueColor()).
SetBackgroundColor(background).
SetBorderPadding(1, 1, 1, 1)
c.AddButton("Save", func() {
if c.done != nil {
title, ok := c.GetFormItemByLabel(c.titleLabel).(*tview.InputField)
if !ok {
return
}
description, ok := c.GetFormItemByLabel(c.descLabel).(*tview.TextArea)
if !ok {
return
}
c.done(title.GetText(), description.GetText(), true, c.mode)
}
})
c.AddButton("Cancel", func() {
if c.done != nil {
c.done("", "", false, c.mode)
}
})
return &c
}
func (c *cardForm) updateInputFields(title, description string) {
c.Clear(false)
c.AddInputField(c.titleLabel, title, 60, nil, nil)
c.AddTextArea(c.descLabel, description, 60, 10, 0, nil)
}
func (c *cardForm) setDoneFunc(handler func(string, string, bool, cardFormMode)) *cardForm {
c.done = handler
return c
}
func (c *cardForm) Draw(screen tcell.Screen) {
buttonsWidth := 20
screenWidth, screenHeight := screen.Size()
width := screenWidth / 3
if width < buttonsWidth {
width = buttonsWidth
}
height := 20
width += 4
// Set the form's position and size.
x := (screenWidth - width) / 2
y := (screenHeight - height) / 2
c.SetRect(x, y, width, height)
// Draw the frame.
c.frame.SetRect(x, y, width, height)
c.frame.Draw(screen)
}