-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent.go
More file actions
405 lines (358 loc) · 11.1 KB
/
Copy pathcomponent.go
File metadata and controls
405 lines (358 loc) · 11.1 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package strut
import (
"errors"
"fmt"
"reflect"
"sync"
"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/handler"
"github.com/disgoorg/snowflake/v2"
)
// Style is a button's appearance.
type Style = discord.ButtonStyle
const (
Primary = discord.ButtonStylePrimary
Secondary = discord.ButtonStyleSecondary
Success = discord.ButtonStyleSuccess
Danger = discord.ButtonStyleDanger
Link = discord.ButtonStyleLink
)
// codecs caches one codec per state type, so a type used by several commands
// is only compiled once.
var codecs sync.Map // reflect.Type -> *stateCodec
func codecFor(t reflect.Type) (*stateCodec, error) {
if c, ok := codecs.Load(t); ok {
return c.(*stateCodec), nil
}
c, err := newStateCodec(t)
if err != nil {
return nil, err
}
actual, _ := codecs.LoadOrStore(t, c)
return actual.(*stateCodec), nil
}
// Component is one built component. A build error travels with it and
// surfaces when the reply is sent, so a builder chain stays readable.
//
// Everything is placed with Row. Discord decides what may share one: up to
// five buttons, or a single select menu.
type Component struct {
c discord.InteractiveComponent
err error
}
// Button carries state back to the handler registered with OnComponent.
func Button[S any](state S, label string, style Style) Component {
id, err := encodeState(state)
if err != nil {
return Component{err: err}
}
return Component{c: discord.NewButton(style, label, id, "", 0)}
}
// LinkButton opens a URL. It carries no state, since Discord never sends an
// interaction for it.
func LinkButton(label, url string) Component {
return Component{c: discord.NewLinkButton(label, url)}
}
// Select offers a fixed list of values, handed to the handler registered
// with OnSelect.
func Select[S, V any](state S, placeholder string, choices ...Choice[V]) Component {
id, err := encodeState(state)
if err != nil {
return Component{err: err}
}
opts := make([]discord.StringSelectMenuOption, 0, len(choices))
for _, ch := range choices {
v, err := stateString(reflect.ValueOf(ch.Value))
if err != nil {
return Component{err: err}
}
opts = append(opts, discord.NewStringSelectMenuOption(ch.Name, v))
}
return Component{c: discord.NewStringSelectMenu(id, placeholder, opts...)}
}
// UserSelect picks users. The chosen ids reach the handler registered with
// OnEntitySelect.
func UserSelect[S any](state S, placeholder string) Component {
return entitySelect(state, func(id string) discord.InteractiveComponent {
return discord.NewUserSelectMenu(id, placeholder)
})
}
// RoleSelect picks roles.
func RoleSelect[S any](state S, placeholder string) Component {
return entitySelect(state, func(id string) discord.InteractiveComponent {
return discord.NewRoleSelectMenu(id, placeholder)
})
}
// ChannelSelect picks channels.
func ChannelSelect[S any](state S, placeholder string) Component {
return entitySelect(state, func(id string) discord.InteractiveComponent {
return discord.NewChannelSelectMenu(id, placeholder)
})
}
// MentionableSelect picks users and roles together.
func MentionableSelect[S any](state S, placeholder string) Component {
return entitySelect(state, func(id string) discord.InteractiveComponent {
return discord.NewMentionableSelectMenu(id, placeholder)
})
}
func entitySelect[S any](state S, build func(id string) discord.InteractiveComponent) Component {
id, err := encodeState(state)
if err != nil {
return Component{err: err}
}
return Component{c: build(id)}
}
// WithDisabled greys the component out, which is how a menu is closed off
// once a choice has been made.
func (b Component) WithDisabled(disabled bool) Component {
switch v := b.c.(type) {
case discord.ButtonComponent:
v.Disabled = disabled
b.c = v
case discord.StringSelectMenuComponent:
v.Disabled = disabled
b.c = v
case discord.UserSelectMenuComponent:
v.Disabled = disabled
b.c = v
case discord.RoleSelectMenuComponent:
v.Disabled = disabled
b.c = v
case discord.ChannelSelectMenuComponent:
v.Disabled = disabled
b.c = v
case discord.MentionableSelectMenuComponent:
v.Disabled = disabled
b.c = v
}
return b
}
// WithEmoji puts an emoji on a button.
func (b Component) WithEmoji(emoji discord.ComponentEmoji) Component {
if v, ok := b.c.(discord.ButtonComponent); ok {
v.Emoji = &emoji
b.c = v
}
return b
}
// WithRange lets a select menu take between min and max values. Without it a
// menu takes exactly one.
func (b Component) WithRange(min, max int) Component {
if min < 0 || max < min {
b.err = errors.Join(b.err, fmt.Errorf("strut: select range %d to %d is impossible", min, max))
return b
}
switch v := b.c.(type) {
case discord.StringSelectMenuComponent:
v.MinValues, v.MaxValues = &min, max
b.c = v
case discord.UserSelectMenuComponent:
v.MinValues, v.MaxValues = &min, max
b.c = v
case discord.RoleSelectMenuComponent:
v.MinValues, v.MaxValues = &min, max
b.c = v
case discord.ChannelSelectMenuComponent:
v.MinValues, v.MaxValues = &min, max
b.c = v
case discord.MentionableSelectMenuComponent:
v.MinValues, v.MaxValues = &min, max
b.c = v
default:
b.err = errors.Join(b.err, errors.New("strut: WithRange applies to select menus only"))
}
return b
}
// Row adds one action row. Discord allows up to five buttons in a row, or a
// single select menu on its own.
func (r Reply) Row(components ...Component) Reply {
if len(components) == 0 {
return r
}
if len(components) > maxRowComponents {
r.err = errors.Join(r.err, errTooManyInRow(len(components)))
return r
}
out := make([]discord.InteractiveComponent, 0, len(components))
for _, c := range components {
if c.err != nil {
r.err = errors.Join(r.err, c.err)
continue
}
out = append(out, c.c)
}
if r.err != nil {
return r
}
r.Components = append(r.Components, discord.NewActionRow(out...))
return r
}
// maxRowComponents is Discord's per-row limit.
const maxRowComponents = 5
func errTooManyInRow(n int) error {
return fmt.Errorf("strut: %d components in one row, max %d", n, maxRowComponents)
}
func encodeState[S any](state S) (string, error) {
c, err := codecFor(reflect.TypeFor[S]())
if err != nil {
return "", err
}
return c.encode(reflect.ValueOf(state))
}
// OnComponent registers a handler for components carrying S. The route comes
// from S's type name, so it survives a restart.
func (f *Framework[D]) OnComponent[S any](h func(*Event[D], S) error) *Framework[D] {
c, err := codecFor(reflect.TypeFor[S]())
if err != nil {
f.errs = append(f.errs, err)
return f
}
if err := f.claim(c.route, c.typ.Name()); err != nil {
f.errs = append(f.errs, err)
return f
}
f.register(c.route, func(ev *Event[D], state reflect.Value) *Error[D] {
ev.meta = Meta{Name: c.route}
if !f.live.begin() {
return &Error[D]{Kind: ErrShuttingDown, Event: ev}
}
defer f.live.done()
return f.wrap(ev, f.chain(func(e *Event[D]) error {
return h(e, state.Interface().(S))
})(ev))
})
f.mux.Component(c.route, func(e *handler.ComponentEvent) error {
state, err := c.decode(e.Vars)
if err != nil {
return err
}
return f.runComponent(e, c.route, func(ev *Event[D]) error {
return h(ev, state.Interface().(S))
})
})
return f
}
// OnSelect registers a handler for a select menu carrying S. The chosen
// values are decoded into V.
func (f *Framework[D]) OnSelect[S, V any](h func(*Event[D], S, []V) error) *Framework[D] {
c, err := codecFor(reflect.TypeFor[S]())
if err != nil {
f.errs = append(f.errs, err)
return f
}
if err := f.claim(c.route, c.typ.Name()); err != nil {
f.errs = append(f.errs, err)
return f
}
valueOf, err := stateSetter(fieldSpec{Type: reflect.TypeFor[V]()})
if err != nil {
f.errs = append(f.errs, fmt.Errorf("strut: select values: %w", err))
return f
}
f.mux.SelectMenuComponent(c.route, func(data discord.SelectMenuInteractionData, e *handler.ComponentEvent) error {
state, err := c.decode(e.Vars)
if err != nil {
return err
}
sm, ok := data.(discord.StringSelectMenuInteractionData)
if !ok {
return fmt.Errorf("strut: %s is not a string select menu", c.route)
}
values := make([]V, 0, len(sm.Values))
for _, raw := range sm.Values {
v := reflect.New(reflect.TypeFor[V]())
if err := valueOf(v.Elem(), raw); err != nil {
return err
}
values = append(values, v.Elem().Interface().(V))
}
return f.runComponent(e, c.route, func(ev *Event[D]) error {
return h(ev, state.Interface().(S), values)
})
})
return f
}
// OnEntitySelect registers a handler for a user, role, channel or mentionable
// select carrying S. Those menus always return ids.
func (f *Framework[D]) OnEntitySelect[S any](h func(*Event[D], S, []snowflake.ID) error) *Framework[D] {
c, err := codecFor(reflect.TypeFor[S]())
if err != nil {
f.errs = append(f.errs, err)
return f
}
if err := f.claim(c.route, c.typ.Name()); err != nil {
f.errs = append(f.errs, err)
return f
}
f.register(c.route, func(ev *Event[D], state reflect.Value) *Error[D] {
return &Error[D]{Kind: ErrCommandFailed, Event: ev,
Err: errors.New("strut: an entity select is driven by its chosen ids")}
})
f.mux.SelectMenuComponent(c.route, func(data discord.SelectMenuInteractionData, e *handler.ComponentEvent) error {
state, err := c.decode(e.Vars)
if err != nil {
return err
}
var ids []snowflake.ID
switch d := data.(type) {
case discord.UserSelectMenuInteractionData:
ids = d.Values
case discord.RoleSelectMenuInteractionData:
ids = d.Values
case discord.ChannelSelectMenuInteractionData:
ids = d.Values
case discord.MentionableSelectMenuInteractionData:
ids = d.Values
default:
return fmt.Errorf("strut: %s is not an entity select menu", c.route)
}
return f.runComponent(e, c.route, func(ev *Event[D]) error {
return h(ev, state.Interface().(S), ids)
})
})
return f
}
// runComponent builds an Event for a component interaction and reports any
// failure through the framework's error handler.
func (f *Framework[D]) runComponent(ce *handler.ComponentEvent, route string, run func(*Event[D]) error) error {
ctx, cancel := tokenContext(ce.Ctx, ce.CreatedAt())
defer cancel()
e := &Event[D]{
data: f.opts.Data,
ctx: ctx,
client: ce.Client(),
log: f.log,
kind: Slash,
meta: Meta{Name: route},
fw: f,
src: interactionSource[*handler.ComponentEvent]{ce},
res: componentResponder{ce},
opener: componentResponder{ce},
}
if err := f.chain(run)(e); err != nil {
var already *Error[D]
if !errors.As(err, &already) {
already = &Error[D]{Kind: ErrCommandFailed, Event: e, Err: err}
}
f.report(nil, already)
}
return nil
}
// register records a component handler so the test harness can drive it.
func (f *Framework[D]) register(route string, h func(*Event[D], reflect.Value) *Error[D]) {
if f.components == nil {
f.components = map[string]func(*Event[D], reflect.Value) *Error[D]{}
}
f.components[route] = h
}
// wrap turns a handler error into the framework's error type.
func (f *Framework[D]) wrap(e *Event[D], err error) *Error[D] {
if err == nil {
return nil
}
var already *Error[D]
if errors.As(err, &already) {
return already
}
return &Error[D]{Kind: ErrCommandFailed, Event: e, Err: err}
}