-
Notifications
You must be signed in to change notification settings - Fork 14
/
widget.go
98 lines (75 loc) · 2.47 KB
/
widget.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
package service
import (
"encoding/json"
"fmt"
"html/template"
"io/fs"
"sync"
"github.com/EmissarySocial/emissary/model"
"github.com/benpate/derp"
"github.com/benpate/form"
"golang.org/x/exp/slices"
)
// Widget service manages the global, in-memory library of widget templates that can
// be applied to any Stream
type Widget struct {
widgets map[string]model.Widget
mutex sync.RWMutex
funcMap template.FuncMap
}
// NewWidget returns a fully initialized Widget service.
func NewWidget(funcMap template.FuncMap) *Widget {
return &Widget{
widgets: make(map[string]model.Widget),
mutex: sync.RWMutex{},
funcMap: template.FuncMap{},
}
}
// Add loads a widget definition from a filesystem, and adds it to the in-memory library.
func (service *Widget) Add(widgetID string, filesystem fs.FS, definition []byte) error {
const location = "service.widget.Add"
widget := model.NewWidget(widgetID, service.funcMap)
// Unmarshal the file into the schema.
if err := json.Unmarshal(definition, &widget); err != nil {
return derp.Wrap(err, location, "Error loading Schema", widgetID)
}
// Load all HTML widgets from the filesystem
if err := loadHTMLTemplateFromFilesystem(filesystem, widget.HTMLTemplate, service.funcMap); err != nil {
return derp.Wrap(err, location, "Error loading Widget", widgetID)
}
// Load all Bundles from the filesystem
if err := populateBundles(widget.Bundles, filesystem); err != nil {
return derp.Wrap(err, location, "Error loading Bundles", widgetID)
}
fmt.Println("... adding widget: " + widget.WidgetID)
// Add the widget into the service library
service.mutex.Lock()
defer service.mutex.Unlock()
service.widgets[widget.WidgetID] = widget
return nil
}
// Get returns a widget definition from the in-memory library.
func (service *Widget) Get(widgetID string) (model.Widget, bool) {
service.mutex.RLock()
defer service.mutex.RUnlock()
result, ok := service.widgets[widgetID]
return result, ok
}
func (service *Widget) List() []form.LookupCode {
service.mutex.RLock()
defer service.mutex.RUnlock()
result := make([]form.LookupCode, 0, len(service.widgets))
for _, widget := range service.widgets {
result = append(result, form.LookupCode{
Value: widget.WidgetID,
Label: widget.Label,
Description: widget.Description,
})
}
slices.SortFunc(result, form.SortLookupCodeByLabel)
return result
}
func (service *Widget) IsValidWidgetType(widgetType string) bool {
_, ok := service.widgets[widgetType]
return ok
}