-
Notifications
You must be signed in to change notification settings - Fork 27
/
configuration.go
78 lines (70 loc) · 1.81 KB
/
configuration.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
package page
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"github.com/jfyne/live"
)
// CompoentConfig configure a component.
type ComponentConfig func(c *Component) error
// WithRegister set a register handler on the component.
func WithRegister(fn RegisterHandler) ComponentConfig {
return func(c *Component) error {
c.Register = fn
return nil
}
}
// WithMount set a mounnt handler on the component.
func WithMount(fn MountHandler) ComponentConfig {
return func(c *Component) error {
c.Mount = fn
return nil
}
}
// WithRender set a render handler on the component.
func WithRender(fn RenderHandler) ComponentConfig {
return func(c *Component) error {
c.Render = fn
return nil
}
}
// WithComponentMount set the live.Handler to mount the root component.
func WithComponentMount(construct ComponentConstructor) live.HandlerConfig {
return func(h *live.Handler) error {
h.Mount = func(ctx context.Context, r *http.Request, s *live.Socket) (interface{}, error) {
root, err := construct(ctx, h, r, s)
if err != nil {
return nil, fmt.Errorf("failed to construct root component: %w", err)
}
if s.Connected() {
if err := root.Register(&root); err != nil {
return nil, err
}
}
if err := root.Mount(ctx, &root, r); err != nil {
return nil, err
}
return root, nil
}
return nil
}
}
// WithComponentRenderer set the live.Handler to use a root component to render.
func WithComponentRenderer() live.HandlerConfig {
return func(h *live.Handler) error {
h.Render = func(ctx context.Context, data interface{}) (io.Reader, error) {
c, ok := data.(Component)
if !ok {
return nil, fmt.Errorf("root render data is not a component")
}
var buf bytes.Buffer
if err := c.Render(&buf, &c); err != nil {
return nil, err
}
return &buf, nil
}
return nil
}
}