Skip to content

Commit

Permalink
add Context Condition
Browse files Browse the repository at this point in the history
  • Loading branch information
zekro committed Sep 1, 2022
1 parent 1a81f7b commit 36bbed9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
20 changes: 17 additions & 3 deletions componentbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ type ComponentBuilder struct {
msgId string
chanId string

condition ComponentHandlerFunc

*componentAssembler
}

Expand Down Expand Up @@ -147,6 +149,11 @@ func (t *ComponentBuilder) AddActionsRow(build func(b ComponentAssembler), once
return t
}

func (t *ComponentBuilder) Condition(cond ComponentHandlerFunc) *ComponentBuilder {
t.condition = cond
return t
}

// Build attaches the registered messgae components to
// the specified message and registers the interaction
// handlers to the handler registry.
Expand All @@ -165,9 +172,14 @@ func (t *ComponentBuilder) Build() (unreg func() error, err error) {

for key := range t.handlers {
handler := t.handlers[key]

if t.condition == nil {
t.condition = func(ctx ComponentContext) bool { return true }
}

if len(handler.onceGroup) > 0 {
t.ch.handlers[key] = func(ctx ComponentContext) bool {
if !handler.handler(ctx) {
if !t.condition(ctx) || !handler.handler(ctx) {
return false
}

Expand All @@ -187,7 +199,7 @@ func (t *ComponentBuilder) Build() (unreg func() error, err error) {
} else if handler.once {
k := key // copy key for anonymous function
t.ch.handlers[key] = func(ctx ComponentContext) bool {
if !handler.handler(ctx) {
if !t.condition(ctx) || !handler.handler(ctx) {
return false
}

Expand All @@ -202,7 +214,9 @@ func (t *ComponentBuilder) Build() (unreg func() error, err error) {
return true
}
} else {
t.ch.handlers[key] = handler.handler
t.ch.handlers[key] = func(ctx ComponentContext) bool {
return t.condition(ctx) && handler.handler(ctx)
}
}
}

Expand Down
3 changes: 3 additions & 0 deletions examples/components/commands/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ func (c *TestCommand) Run(ctx ken.Context) (err error) {
return true
}, !clearAll)
}, clearAll).
Condition(func(cctx ken.ComponentContext) bool {
return cctx.User().ID == ctx.User().ID
}).
Build()

return err
Expand Down

0 comments on commit 36bbed9

Please sign in to comment.