-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcustom.go
69 lines (64 loc) · 2.1 KB
/
custom.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package form
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/df-mc/dragonfly/server/player/form"
"github.com/df-mc/dragonfly/server/world"
)
// Custom represents a form that may be sent to a player and has fields that should be filled out by the player that the
// form is sent to.
type Custom struct {
// Title is the title of the form that is displayed at the very top of the form.
Title string
// Buttons is a slice of elements that can be modified by a player. There must be at least one element for the client
// to render the form.
Elements []Element
// Submit is called when the form is closed or if a player pressed the submit button. This is always called after the
// Submit of every Element. The values will be passed in a slice, with the same order as the Elements slice. If the
// form was closed, the values slice will be nil.
Submit func(closed bool, values []any, tx *world.Tx)
}
// Element appends an element to the bottom of the form.
func (form *Custom) Element(element Element) {
form.Elements = append(form.Elements, element)
}
// SubmitJSON ...
func (form *Custom) SubmitJSON(data []byte, _ form.Submitter, tx *world.Tx) error {
if data == nil {
if form.Submit != nil {
form.Submit(true, nil, tx)
}
return nil
}
dec := json.NewDecoder(bytes.NewBuffer(data))
dec.UseNumber()
var inputData []any
if err := dec.Decode(&inputData); err != nil {
return fmt.Errorf("error decoding JSON data to slice: %w", err)
} else if len(form.Elements) != len(inputData) {
return fmt.Errorf("form JSON data array does not have enough values")
}
for i, element := range form.Elements {
err := element.submit(inputData[i])
if err != nil {
return fmt.Errorf("error parsing form response value: %w", err)
}
}
if form.Submit != nil {
form.Submit(false, inputData, tx)
}
return nil
}
// MarshalJSON ...
func (form *Custom) MarshalJSON() ([]byte, error) {
if len(form.Elements) == 0 {
return nil, errors.New("menu form requires at least one element")
}
return json.Marshal(map[string]any{
"type": "custom_form",
"title": form.Title,
"content": form.Elements,
})
}