Debian Codegraph @

form.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // mauview - A Go TUI library based on tcell.
2 // Copyright © 2019 Tulir Asokan
3 //
4 // This Source Code Form is subject to the terms of the Mozilla Public
5 // License, v. 2.0. If a copy of the MPL was not distributed with this
6 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
8 package mauview
9
10 import (
•11 "github.com/gdamore/tcell/v2"
12 )
13
14 type Form struct {
15 *Grid
16 items []*gridChild
17 }
18
19 type FormItem interface {
20 Component
21 Submit(event KeyEvent) bool
22 }
23
24 func NewForm() *Form {
25 return &Form{
26 Grid: NewGrid(),
27 }
28 }
29
30 func (form *Form) Draw(screen Screen) {
31 form.Grid.Draw(screen)
32 }
33
34 func (form *Form) FocusNextItem() {
35 for i := 0; i < len(form.items)-1; i++ {
36 if form.focused == form.items[i] {
37 form.setFocused(form.items[i+1])
38 return
39 }
40 }
41 form.setFocused(form.items[0])
42 }
43
44 func (form *Form) FocusPreviousItem() {
45 for i := len(form.items) - 1; i > 0; i-- {
46 if form.focused == form.items[i] {
47 form.setFocused(form.items[i-1])
48 return
49 }
50 }
51 form.setFocused(form.items[len(form.items)-1])
52 }
53
54 func (form *Form) AddFormItem(comp Component, x, y, width, height int) *Form {
55 child := form.Grid.createChild(comp, x, y, width, height)
56 form.items = append(form.items, child)
57 form.Grid.addChild(child)
58 return form
59 }
60
61 func (form *Form) RemoveFormItem(comp Component) *Form {
62 for index := len(form.items) - 1; index >= 0; index-- {
63 if form.items[index].target == comp {
64 form.items = append(form.items[:index], form.items[index+1:]...)
65 }
66 }
67 form.Grid.RemoveComponent(comp)
68 return form
69 }
70
71 func (form *Form) OnKeyEvent(event KeyEvent) bool {
72 switch event.Key() {
73 case tcell.KeyTab:
74 form.FocusNextItem()
75 return true
76 case tcell.KeyBacktab:
77 form.FocusPreviousItem()
78 return true
79 case tcell.KeyEnter:
80 if form.focused != nil {
81 if fi, ok := form.focused.target.(FormItem); ok {
82 if fi.Submit(event) {
83 form.FocusNextItem()
84 return true
85 } else {
86 return false
87 }
88 }
89 }
90 }
91 return form.Grid.OnKeyEvent(event)
92 }