Debian Codegraph @

_examples/vxfw/flex/main.go

raw
1 package main
2
3 import (
4 "log"
5
6 "git.sr.ht/~rockorager/vaxis"
7 "git.sr.ht/~rockorager/vaxis/vxfw"
8 "git.sr.ht/~rockorager/vaxis/vxfw/richtext"
9 "git.sr.ht/~rockorager/vaxis/vxfw/text"
10 "git.sr.ht/~rockorager/vaxis/vxfw/vxlayout"
11 )
12
13 type App struct {
14 help vxfw.Widget
15 layout *vxlayout.FlexLayout
16 }
17
18 func (a *App) CaptureEvent(ev vaxis.Event) (vxfw.Command, error) {
19 switch ev := ev.(type) {
20 case vaxis.Key:
21 if ev.Matches('c', vaxis.ModCtrl) {
22 return vxfw.QuitCmd{}, nil
23 }
24 if ev.Matches('l') || ev.Matches('L') {
25 a.swapLayout()
26 return vxfw.ConsumeAndRedraw(), nil
27 }
28 }
29 return nil, nil
30 }
31
32 func (a *App) swapLayout() {
33 if a.layout.Direction == vxlayout.FlexVertical {
34 a.layout.Direction = vxlayout.FlexHorizontal
35 } else {
36 a.layout.Direction = vxlayout.FlexVertical
37 }
38 }
39
40 func (a *App) HandleEvent(ev vaxis.Event, phase vxfw.EventPhase) (vxfw.Command, error) {
41 return nil, nil
42 }
43
44 func (a *App) Draw(ctx vxfw.DrawContext) (vxfw.Surface, error) {
45 root := vxfw.NewSurface(ctx.Max.Width, ctx.Max.Height, a)
46
47 // the example layout should be constrained to a smaller size in the cross dimension, since
48 // otherwise Center will take up everything.
49 layoutCtx := vxfw.DrawContext(ctx)
50 switch a.layout.Direction {
51 case vxlayout.FlexHorizontal:
52 layoutCtx.Max.Height = 1
53 case vxlayout.FlexVertical:
54 layoutCtx.Max.Width = 6
55 layoutCtx.Max.Height -= 1 // leave room for the hint
56 }
57 layout, err := a.layout.Draw(layoutCtx)
58 if err != nil {
59 return vxfw.Surface{}, err
60 }
61
62 help, err := a.help.Draw(vxfw.DrawContext{
63 Max: vxfw.Size{Width: ctx.Max.Width, Height: 1},
64 Characters: ctx.Characters,
65 })
66
67 root.AddChild(0, 0, help)
68 root.AddChild(0, 1, layout)
69 return root, nil
70 }
71
72 func main() {
73 app, err := vxfw.NewApp(vaxis.Options{})
74 if err != nil {
75 log.Fatalf("Couldn't create a new app: %v", err)
76 }
77
78 widgets := []vxfw.Widget{
79 richtext.New([]vaxis.Segment{
80 {Text: "FIRST", Style: vaxis.Style{Background: vaxis.IndexColor(1)}},
81 }),
82 richtext.New([]vaxis.Segment{
83 {Text: "MIDDLE", Style: vaxis.Style{Background: vaxis.IndexColor(2)}},
84 }),
85 richtext.New([]vaxis.Segment{
86 {Text: "LAST", Style: vaxis.Style{Background: vaxis.IndexColor(3)}},
87 }),
88 }
89
90 root := &App{
91 help: text.New("Ctrl+C to quit, L (or l) to switch layouts."),
92 layout: &vxlayout.FlexLayout{
93 Children: []*vxlayout.FlexItem{
94 {Widget: widgets[0], Flex: 0},
95 vxlayout.MustSpacer(1),
96 {Widget: widgets[1], Flex: 0},
97 {Widget: vxlayout.Spacer{}, Flex: 1},
98 {Widget: widgets[2], Flex: 0},
99 },
100 Direction: vxlayout.FlexHorizontal,
101 },
102 }
103
104 app.Run(root)
105 }