Skip to content
Myr

main.go

This file

Path

examples/isbn-form/main.go

245 lines · 4.8 KiB · Go

Last changed by

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

History of this file

Take it

1package main23import (4	"fmt"5	"log"6	"strings"7	"unicode"89	"charm.land/bubbles/v2/textinput"10	tea "charm.land/bubbletea/v2"11	"charm.land/lipgloss/v2"12	"github.com/charmbracelet/x/exp/charmtone"13)1415func main() {16	p := tea.NewProgram(initialModel())1718	if _, err := p.Run(); err != nil {19		log.Fatal(err)20	}21}2223type (24	errMsg error25)2627var (28	inputStyle    = lipgloss.NewStyle().Foreground(lipgloss.Color(charmtone.Tang.Hex()))29	continueStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(charmtone.Anchovy.Hex()))30	validStyle    = lipgloss.NewStyle().Foreground(lipgloss.Color(charmtone.Guac.Hex()))31	errStyle      = lipgloss.NewStyle().Foreground(lipgloss.Color(charmtone.Cherry.Hex()))32)3334type model struct {35	isbnInput    textinput.Model36	titleInput   textinput.Model37	focusedInput int38	err          error39}4041// canFindBook returns whether the find button is to be pressed42func (m model) canFindBook() bool {43	correctIsbnGiven := m.isbnInput.Err == nil && len(m.isbnInput.Value()) != 044	correctTitleGiven := m.titleInput.Err == nil && len(m.titleInput.Value()) != 04546	return correctIsbnGiven && correctTitleGiven47}4849// Validator function to ensure valid input50func isbn13Validator(s string) error {51	// A valid ISBN looks like this:52	// 978-3-548-37257-0 or53	// 9783548372570 without any spaces5455	// Remove dashes56	s = strings.ReplaceAll(s, "-", "")57	if len(s) != 13 {58		return fmt.Errorf("ISBN is of wrong length")59	}6061	for _, c := range s {62		if !unicode.IsDigit(c) {63			return fmt.Errorf("ISBN contains invalid characters")64		}65	}6667	gs1Prefix := s[:3]68	switch gs1Prefix {69	case "978", "979":70		break71	default:72		return fmt.Errorf("ISBN has invalid GS1 prefix")73	}7475	// The last digit, the check digit,76	// must make the checksum a multiple of 10.77	// All digits are added up after being multiplied78	// by either 1 or 3 alternately.79	// So 9x1 + 7x3 + 8x1 + ... + 0 must be a multiple of 10.8081	sum := 082	for i, c := range s {83		// Convert rune to int84		n := int(c - '0')8586		// Multiply the uneven indices by 387		if i%2 != 0 {88			n *= 389		}9091		sum += n92	}9394	if sum%10 != 0 {95		return fmt.Errorf("ISBN has invalid check digit")96	}9798	return nil99}100101var bannedTitleWords = []string{102	"very",103	"bad",104	"words",105	"that",106	"should",107	"not",108	"appear",109	"in",110	"book",111	"titles",112}113114func bookTitleValidator(s string) error {115	s = strings.TrimSpace(s)116117	if len(s) == 0 {118		return fmt.Errorf("Book title is empty")119	}120121	for _, bannedWord := range bannedTitleWords {122		if strings.Contains(s, bannedWord) {123			return fmt.Errorf("Book title contains banned word %q", bannedWord)124		}125	}126127	return nil128}129130func initialModel() model {131	isbnInput := textinput.New()132	isbnInput.Focus()133	isbnInput.Placeholder = "978-X-XXX-XXXXX-X"134	isbnInput.CharLimit = 17135	isbnInput.SetWidth(30)136	isbnInput.Prompt = ""137	isbnInput.Validate = isbn13Validator138139	titleInput := textinput.New()140	titleInput.Blur()141	titleInput.Placeholder = "Title"142	titleInput.CharLimit = 100143	titleInput.SetWidth(100)144	titleInput.Prompt = ""145	titleInput.Validate = bookTitleValidator146147	return model{148		isbnInput:    isbnInput,149		titleInput:   titleInput,150		focusedInput: 0,151		err:          nil,152	}153}154155func (m model) Init() tea.Cmd {156	return textinput.Blink157}158159func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {160	switch msg := msg.(type) {161	case tea.KeyPressMsg:162		switch msg.String() {163		case "up", "down":164			// Switch between text inputs165			switch m.focusedInput {166			case 0:167				m.focusedInput = 1168				m.titleInput.Focus()169				m.isbnInput.Blur()170			case 1:171				m.focusedInput = 0172				m.isbnInput.Focus()173				m.titleInput.Blur()174			}175		case "enter":176			// Enter is blocked until all inputs are ok177			if m.canFindBook() {178				return m, tea.Quit179			}180		case "ctrl+c", "esc":181			return m, tea.Quit182		}183184	// We handle errors just like any other message185	case errMsg:186		m.err = msg187		return m, nil188	}189190	var isbnCommand tea.Cmd191	m.isbnInput, isbnCommand = m.isbnInput.Update(msg)192193	var titleCommand tea.Cmd194	m.titleInput, titleCommand = m.titleInput.Update(msg)195196	return m, tea.Batch(isbnCommand, titleCommand)197}198199func (m model) View() tea.View {200	var continueText string201	if m.canFindBook() {202		continueText = continueStyle.Render("Find ->")203	}204205	var isbnErrorText string206	if m.isbnInput.Value() != "" {207		if m.isbnInput.Err != nil {208			isbnErrorText = errStyle.Render(m.isbnInput.Err.Error())209		} else {210			isbnErrorText = validStyle.Render("Valid ISBN")211		}212	}213214	var titleErrorText string215	if m.titleInput.Value() != "" {216		if m.titleInput.Err != nil {217			titleErrorText = errStyle.Render(m.titleInput.Err.Error())218		} else {219			titleErrorText = validStyle.Render("Valid title")220		}221	}222223	return tea.NewView(fmt.Sprintf(224		` Search book:225 %s226 %s227 %s228229 %s230 %s231 %s232233 %s234`,235		inputStyle.Width(30).Render("ISBN"),236		m.isbnInput.View(),237		isbnErrorText,238239		inputStyle.Width(30).Render("Title"),240		m.titleInput.View(),241		titleErrorText,242243		continueText,244	) + "\n")245}