Debian Codegraph @

button.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 Button struct {
15 text string
16 style tcell.Style
17 focusedStyle tcell.Style
18 focused bool
19 onClick func()
20 }
21
22 func NewButton(text string) *Button {
23 return &Button{
24 text: text,
25 style: tcell.StyleDefault.Background(Styles.ContrastBackgroundColor).Foreground(Styles.PrimaryTextColor),
26 focusedStyle: tcell.StyleDefault.Background(Styles.MoreContrastBackgroundColor).Foreground(Styles.PrimaryTextColor),
27 }
28 }
29
30 func (b *Button) SetText(text string) *Button {
31 b.text = text
32 return b
33 }
34
35 func (b *Button) SetForegroundColor(color tcell.Color) *Button {
36 b.style = b.style.Foreground(color)
37 return b
38 }
39
40 func (b *Button) SetBackgroundColor(color tcell.Color) *Button {
41 b.style = b.style.Background(color)
42 return b
43 }
44
45 func (b *Button) SetFocusedForegroundColor(color tcell.Color) *Button {
46 b.focusedStyle = b.focusedStyle.Foreground(color)
47 return b
48 }
49
50 func (b *Button) SetFocusedBackgroundColor(color tcell.Color) *Button {
51 b.focusedStyle = b.focusedStyle.Background(color)
52 return b
53 }
54
55 func (b *Button) SetStyle(style tcell.Style) *Button {
56 b.style = style
57 return b
58 }
59
60 func (b *Button) SetFocusedStyle(style tcell.Style) *Button {
61 b.focusedStyle = style
62 return b
63 }
64
65 func (b *Button) SetOnClick(fn func()) *Button {
66 b.onClick = fn
67 return b
68 }
69
70 func (b *Button) Focus() {
71 b.focused = true
72 }
73
74 func (b *Button) Blur() {
75 b.focused = false
76 }
77
78 func (b *Button) Draw(screen Screen) {
79 width, _ := screen.Size()
80 style := b.style
81 if b.focused {
82 style = b.focusedStyle
83 }
84 screen.SetStyle(style)
85 screen.Clear()
86 PrintWithStyle(screen, b.text, 0, 0, width, AlignCenter, style)
87 }
88
89 func (b *Button) Submit(event KeyEvent) bool {
90 if b.onClick != nil {
91 b.onClick()
92 }
93 return true
94 }
95
96 func (b *Button) OnKeyEvent(event KeyEvent) bool {
97 if event.Key() == tcell.KeyEnter {
98 if b.onClick != nil {
99 b.onClick()
100 }
101 return true
102 }
103 return false
104 }
105
106 func (b *Button) OnMouseEvent(event MouseEvent) bool {
107 if event.Buttons() == tcell.Button1 && !event.HasMotion() {
108 if b.onClick != nil {
109 b.onClick()
110 }
111 return true
112 }
113 return false
114 }
115
116 func (b *Button) OnPasteEvent(event PasteEvent) bool {
117 return false
118 }