...
1 package client
2
3 import (
4 "context"
5 "fmt"
6 "math/rand"
7 "reflect"
8
9 "fyne.io/fyne/v2"
10 "fyne.io/fyne/v2/container"
11 "fyne.io/fyne/v2/layout"
12 "fyne.io/fyne/v2/widget"
13
14 "jschan/app"
15 "jschan/app/models"
16 )
17
18 type Gui struct {
19 Thread *models.Post
20 jschan *jschan.Client
21 ctx context.Context
22 labels map[string]*widget.Label
23 }
24
25 func (x *Gui) newLabel(name string) *widget.Label {
26 w := widget.NewLabel("")
27 x.labels[name] = w
28 return w
29 }
30
31 func NewGui(jschanUrl string) *Gui {
32 return &Gui{
33 ctx: context.Background(),
34 jschan: jschan.NewClient(jschanUrl),
35 labels: make(map[string]*widget.Label),
36 }
37 }
38
39 func (x *Gui) DataToScreen() {
40 myType := reflect.TypeOf(x.Thread).Elem()
41 myValue := reflect.ValueOf(x.Thread).Elem()
42 for i := 0; i < myType.NumField(); i++ {
43 tag := myType.Field(i).Tag.Get("json")
44 ft := myType.Field(i).Type.String()
45 switch ft {
46 case "string":
47 v := myValue.Field(i).String()
48 x.labels[tag].SetText(v)
49 }
50 }
51 }
52
53 func (x *Gui) NewForm(w fyne.Window) fyne.Widget {
54 form := &widget.Form{}
55 tt := reflect.TypeOf(x.Thread).Elem()
56 for i := 0; i < tt.NumField(); i++ {
57 fld := tt.Field(i)
58 tag := fld.Tag.Get("json")
59 ft := fld.Type.String()
60 switch ft {
61 case "string":
62 form.Append(fld.Name, x.newLabel(tag))
63 }
64 }
65 return form
66 }
67
68 func (g *Gui) Refresh(w fyne.Window) {
69
70 res, err := g.jschan.GetOverboardCatalog(g.ctx, nil)
71 if err != nil {
72 fmt.Println(err)
73 return
74 }
75 threadNum := rand.Intn(len(res.Threads))
76 g.Thread = &res.Threads[threadNum]
77
78 g.DataToScreen()
79 }
80
81 func Show(win fyne.Window) fyne.CanvasObject {
82
83 g := NewGui("https://94chan.org")
84
85 form := g.NewForm(win)
86
87 refresh := widget.NewButton("Refresh", func() {
88 go g.Refresh(win)
89 })
90
91 buttons := container.NewHBox(layout.NewSpacer(), refresh)
92
93 return container.NewBorder(form, buttons, nil, nil)
94 }
95
View as plain text