-
Notifications
You must be signed in to change notification settings - Fork 0
/
event_handler.go
111 lines (89 loc) · 2.36 KB
/
event_handler.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
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
package hikari
import (
"fmt"
"reflect"
"slices"
"github.com/fatih/color"
"github.com/olehvolynets/hikari/config"
)
var (
numberFormat Colorizer = color.New(color.FgHiRed)
stringFormat Colorizer = color.New(color.FgWhite)
boolFormat Colorizer = color.New(color.FgBlue)
nullFormat Colorizer = color.New(color.FgYellow, color.Bold)
mapKeyFormat Colorizer = color.New(color.FgRed)
)
type Entry map[string]any
type Colorizer = *color.Color
type Handler interface {
Render(*Context, Entry)
}
type EventHandler struct {
Event config.Event
Handlers []Handler
RefHandlers []Handler
}
func NewEventHandler(evt config.Event, refHandlers []*ReferenceHandler) *EventHandler {
handler := EventHandler{
Event: evt,
Handlers: make([]Handler, len(evt.Scheme)),
}
for idx, schemeItem := range evt.Scheme {
if schemeItem.Literal == "" {
attrHandler := &AttributeHandler{
Key: schemeItem.Name,
Skip: schemeItem.Skip,
Optional: schemeItem.Optional,
Inline: schemeItem.Inline,
Type: schemeItem.Type,
Colorizer: schemeItem.ToColor(),
EnumHandler: NewEnumHandler(schemeItem.Variants),
Prefix: NewDecorator(schemeItem.Prefix),
Postfix: NewDecorator(schemeItem.Postfix),
}
if schemeItem.As != "" {
for _, h := range refHandlers {
if h.Name == schemeItem.As {
attrHandler.RefHandler = h
}
}
if attrHandler.RefHandler == nil {
panic(fmt.Sprintf("hikari: unknown reference \"as: %s\"", schemeItem.As))
}
}
handler.Handlers[idx] = attrHandler
} else {
handler.Handlers[idx] = &LiteralHandler{
Literal: schemeItem.Literal,
Colorizer: schemeItem.ToColor(),
}
}
}
return &handler
}
func (h *EventHandler) Render(ctx *Context, val Entry) {
if len(val) == 0 {
return
}
for _, attrHandler := range h.Handlers {
attrHandler.Render(ctx, val)
}
unhandled := make(Entry, len(val)/2)
for k, v := range val {
if !slices.Contains(ctx.HandledAttributes, k) {
unhandled[k] = v
}
}
DefaultEventHandler.Render(ctx, unhandled)
fmt.Fprintln(ctx.W)
}
type defaultEventHandler struct{}
func (h *defaultEventHandler) Render(ctx *Context, val Entry) {
if len(val) == 0 {
return
}
attrHandler := AttributeHandler{}
attrHandler.render(ctx, reflect.ValueOf(val))
fmt.Fprintln(ctx.W)
}
var DefaultEventHandler = &defaultEventHandler{}