-
-
Notifications
You must be signed in to change notification settings - Fork 288
/
Copy pathstorybook.go
549 lines (501 loc) · 13.1 KB
/
storybook.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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
package storybook
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync"
"golang.org/x/mod/sumdb/dirhash"
_ "embed"
"github.com/a-h/templ"
"github.com/rs/cors"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type Storybook struct {
// Path to the storybook-server directory, defaults to ./storybook-server.
Path string
// RoutePrefix is the prefix of HTTP routes, e.g. /prod/
RoutePrefix string
// Config of the Stories.
Config map[string]*Conf
// Handlers for each of the components.
Handlers map[string]http.Handler
// Handler used to serve Storybook, defaults to filesystem at ./storybook-server/storybook-static.
StaticHandler http.Handler
Header string
Server http.Server
Log *zap.Logger
AdditionalPrefixJS string
}
type StorybookConfig func(*Storybook)
func WithServerAddr(addr string) StorybookConfig {
return func(sb *Storybook) {
sb.Server.Addr = addr
}
}
func WithHeader(header string) StorybookConfig {
return func(s *Storybook) {
s.Header = header
}
}
func WithPath(path string) StorybookConfig {
return func(sb *Storybook) {
sb.Path = path
}
}
// WithAdditionalPreviewJS / WithAdditionalPreviewJS allows to add content to the generated .storybook/preview.js file.
// For example this can be used to include custom CSS.
func WithAdditionalPreviewJS(content string) StorybookConfig {
return func(sb *Storybook) {
sb.AdditionalPrefixJS = content
}
}
func New(conf ...StorybookConfig) *Storybook {
cfg := zap.NewProductionConfig()
cfg.EncoderConfig.EncodeTime = zapcore.RFC3339TimeEncoder
logger, err := cfg.Build()
if err != nil {
panic("templ-storybook: zap configuration failed: " + err.Error())
}
sh := &Storybook{
Path: "./storybook-server",
Config: map[string]*Conf{},
Handlers: map[string]http.Handler{},
Log: logger,
}
sh.Server = http.Server{
Handler: sh,
Addr: ":60606",
}
for _, sc := range conf {
sc(sh)
}
// Depends on the correct Path, so must be set after additional config
sh.StaticHandler = http.FileServer(http.Dir(path.Join(sh.Path, "storybook-static")))
return sh
}
func (sh *Storybook) AddComponent(name string, componentConstructor any, args ...Arg) *Conf {
//TODO: Check that the component constructor is a function that returns a templ.Component.
c := NewConf(name, args...)
sh.Config[name] = c
h := NewHandler(name, componentConstructor, args...)
sh.Handlers[name] = h
return c
}
func (sh *Storybook) Build(ctx context.Context) (err error) {
defer func() {
_ = sh.Log.Sync()
}()
// Download Storybook to the directory required.
sh.Log.Info("Installing storybook.")
err = sh.installStorybook()
if err != nil {
return
}
if ctx.Err() != nil {
return
}
// Copy the config to Storybook.
sh.Log.Info("Configuring storybook.")
configHasChanged, err := sh.configureStorybook()
if err != nil {
return
}
if ctx.Err() != nil {
return
}
// Execute a static build of storybook if the config has changed.
if configHasChanged {
sh.Log.Info("Config not present, or has changed, rebuilding storybook.")
err = sh.buildStorybook()
if err != nil {
return
}
} else {
sh.Log.Info("Storybook is up-to-date, skipping build step.")
}
if ctx.Err() != nil {
return
}
return
}
func (sh *Storybook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sbh := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, path.Join(sh.RoutePrefix, "/storybook_preview/")) {
sh.previewHandler(w, r)
return
}
sh.StaticHandler.ServeHTTP(w, r)
})
cors.Default().Handler(sbh).ServeHTTP(w, r)
}
func (sh *Storybook) ListenAndServeWithContext(ctx context.Context) (err error) {
err = sh.Build(ctx)
if err != nil {
return
}
go func() {
sh.Log.Info("Starting Go server", zap.String("address", sh.Server.Addr))
err = sh.Server.ListenAndServe()
}()
<-ctx.Done()
// Close the Go server.
sh.Server.Close()
return err
}
func (sh *Storybook) previewHandler(w http.ResponseWriter, r *http.Request) {
prefix := path.Join(sh.RoutePrefix, "/storybook_preview/")
if !strings.HasPrefix(r.URL.Path, prefix) {
sh.Log.Warn("URL does not match preview prefix", zap.String("url", r.URL.String()))
http.NotFound(w, r)
return
}
name, err := url.PathUnescape(strings.TrimPrefix(r.URL.Path, prefix))
if err != nil {
http.Error(w, fmt.Sprintf("failed to unescape URL: %v", err), http.StatusBadRequest)
return
}
if name == "" {
sh.Log.Warn("URL does not contain component name", zap.String("url", r.URL.String()))
http.NotFound(w, r)
return
}
name = strings.TrimPrefix(name, "/")
h, found := sh.Handlers[name]
if !found {
sh.Log.Info("Component name not found", zap.String("name", name), zap.String("url", r.URL.String()), zap.Strings("available", keysOfMap(sh.Handlers)))
http.NotFound(w, r)
return
}
h.ServeHTTP(w, r)
}
func keysOfMap[K comparable, V any](handler map[K]V) (keys []K) {
keys = make([]K, len(handler))
var i int
for k := range handler {
keys[i] = k
i++
}
return keys
}
//go:embed _package.json
var packageJSON string
func (sh *Storybook) installStorybook() (err error) {
_, err = os.Stat(sh.Path)
if err == nil {
sh.Log.Info("Storybook already installed, Skipping installation.")
return
}
if os.IsNotExist(err) {
err = os.Mkdir(sh.Path, os.ModePerm)
if err != nil {
return fmt.Errorf("templ-storybook: error creating @storybook/server directory: %w", err)
}
err = os.WriteFile(filepath.Join(sh.Path, "package.json"), []byte(packageJSON), 0644)
if err != nil {
return fmt.Errorf("templ-storybook: error writing package.json: %w", err)
}
}
var cmd exec.Cmd
cmd.Dir = sh.Path
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Path, err = exec.LookPath("npx")
if err != nil {
return fmt.Errorf("templ-storybook: cannot install storybook, cannot find npx on the path, check that Node.js is installed: %w", err)
}
cmd.Args = []string{"npx", "sb", "init", "-t", "server", "--no-dev"}
return cmd.Run()
}
func (sh *Storybook) configureStorybook() (configHasChanged bool, err error) {
// Delete template/existing files in the stories directory.
storiesDir := filepath.Join(sh.Path, "stories")
before, err := dirhash.HashDir(storiesDir, "/", dirhash.DefaultHash)
if err != nil && !os.IsNotExist(err) {
return configHasChanged, err
}
if err = os.RemoveAll(storiesDir); err != nil {
return configHasChanged, err
}
if err := os.Mkdir(storiesDir, os.ModePerm); err != nil {
return configHasChanged, err
}
// Create new *.stories.json files.
for _, c := range sh.Config {
name := filepath.Join(sh.Path, fmt.Sprintf("stories/%s.stories.json", c.Title))
f, err := os.Create(name)
if err != nil {
return configHasChanged, fmt.Errorf("failed to create config file to %q: %w", name, err)
}
err = json.NewEncoder(f).Encode(c)
if err != nil {
return configHasChanged, fmt.Errorf("failed to write JSON config to %q: %w", name, err)
}
}
after, err := dirhash.HashDir(storiesDir, "/", dirhash.DefaultHash)
if err != nil {
return configHasChanged, fmt.Errorf("failed to hash directory %q: %w", storiesDir, err)
}
configHasChanged = before != after
// Configure storybook Preview URL.
err = os.WriteFile(filepath.Join(sh.Path, ".storybook/preview.js"), []byte(fmt.Sprintf("%s\n%s", sh.AdditionalPrefixJS, previewJS)), os.ModePerm)
if err != nil {
return
}
// Configure preview-head.html
err = os.WriteFile(filepath.Join(sh.Path, ".storybook/preview-head.html"), []byte(sh.Header), os.ModePerm)
return
}
var previewJS = `
// Customise fetch so that it uses a relative URL.
const fetchStoryHtml = async (url, path, params, context) => {
const qs = new URLSearchParams(params);
const response = await fetch("/storybook_preview/" + path + "?" + qs.toString());
return response.text();
};
export const parameters = {
server: {
url: "http://localhost/storybook_preview", // Ignored by fetchStoryHtml.
fetchStoryHtml,
},
};
`
func (sh *Storybook) buildStorybook() (err error) {
var cmd exec.Cmd
cmd.Dir = sh.Path
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Path, err = exec.LookPath("npm")
if err != nil {
return fmt.Errorf("templ-storybook: cannot run storybook, cannot find npm on the path, check that Node.js is installed: %w", err)
}
cmd.Args = []string{"npm", "run", "build-storybook"}
return cmd.Run()
}
func NewHandler(name string, f any, args ...Arg) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
argv := make([]any, len(args))
q := r.URL.Query()
for i, arg := range args {
argv[i] = arg.Get(q)
}
component, err := executeTemplate(name, f, argv)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
templ.Handler(component).ServeHTTP(w, r)
})
}
func executeTemplate(name string, fn any, values []any) (output templ.Component, err error) {
v := reflect.ValueOf(fn)
t := v.Type()
argv := make([]reflect.Value, t.NumIn())
if len(argv) != len(values) {
err = fmt.Errorf("templ-storybook: component %s expects %d argument, but %d were provided", fn, len(argv), len(values))
return
}
for i := 0; i < len(argv); i++ {
argv[i] = reflect.ValueOf(values[i])
}
result := v.Call(argv)
if len(result) != 1 {
err = fmt.Errorf("templ-storybook: function %s must return a templ.Component", name)
return
}
output, ok := result[0].Interface().(templ.Component)
if !ok {
err = fmt.Errorf("templ-storybook: result of function %s is not a templ.Component", name)
return
}
return output, nil
}
func NewConf(title string, args ...Arg) *Conf {
c := &Conf{
Title: title,
Parameters: StoryParameters{
Server: map[string]any{
"id": title,
},
},
Args: NewSortedMap(),
ArgTypes: NewSortedMap(),
Stories: []Story{},
}
for _, arg := range args {
c.Args.Add(arg.Name, arg.Value)
c.ArgTypes.Add(arg.Name, map[string]any{
"control": arg.Control,
})
}
c.AddStory("Default")
return c
}
func (c *Conf) AddStory(name string, args ...Arg) {
m := NewSortedMap()
for _, arg := range args {
m.Add(arg.Name, arg.Value)
}
c.Stories = append(c.Stories, Story{
Name: name,
Args: m,
})
}
// Controls for the configuration.
// See https://storybook.js.org/docs/react/essentials/controls
type Arg struct {
Name string
Value any
Control any
Get func(q url.Values) any
}
func ObjectArg(name string, value any, valuePtr any) Arg {
return Arg{
Name: name,
Value: value,
Control: "object",
Get: func(q url.Values) any {
err := json.Unmarshal([]byte(q.Get(name)), valuePtr)
if err != nil {
return err
}
return reflect.Indirect(reflect.ValueOf(valuePtr)).Interface()
},
}
}
func TextArg(name, value string) Arg {
return Arg{
Name: name,
Value: value,
Control: "text",
Get: func(q url.Values) any {
return q.Get(name)
},
}
}
func BooleanArg(name string, value bool) Arg {
return Arg{
Name: name,
Value: value,
Control: "boolean",
Get: func(q url.Values) any {
return q.Get(name) == "true"
},
}
}
type IntArgConf struct{ Min, Max, Step *int }
func IntArg(name string, value int, conf IntArgConf) Arg {
control := map[string]any{
"type": "number",
}
if conf.Min != nil {
control["min"] = conf.Min
}
if conf.Max != nil {
control["max"] = conf.Max
}
if conf.Step != nil {
control["step"] = conf.Step
}
arg := Arg{
Name: name,
Value: value,
Control: control,
Get: func(q url.Values) any {
i64, err := strconv.ParseInt(q.Get(name), 10, 64)
if err != nil || i64 < math.MinInt || i64 > math.MaxInt {
return 0
}
return int(i64)
},
}
return arg
}
func FloatArg(name string, value float64, min, max, step float64) Arg {
return Arg{
Name: name,
Value: value,
Control: map[string]any{
"type": "number",
"min": min,
"max": max,
"step": step,
},
Get: func(q url.Values) any {
i, _ := strconv.ParseFloat(q.Get(name), 64)
return i
},
}
}
type Conf struct {
Title string `json:"title"`
Parameters StoryParameters `json:"parameters"`
Args *SortedMap `json:"args"`
ArgTypes *SortedMap `json:"argTypes"`
Stories []Story `json:"stories"`
}
type StoryParameters struct {
Server map[string]any `json:"server"`
}
func NewSortedMap() *SortedMap {
return &SortedMap{
m: new(sync.Mutex),
internal: map[string]any{},
keys: []string{},
}
}
type SortedMap struct {
m *sync.Mutex
internal map[string]any
keys []string
}
func (sm *SortedMap) Add(key string, value any) {
sm.m.Lock()
defer sm.m.Unlock()
sm.keys = append(sm.keys, key)
sm.internal[key] = value
}
func (sm *SortedMap) MarshalJSON() (output []byte, err error) {
sm.m.Lock()
defer sm.m.Unlock()
b := new(bytes.Buffer)
b.WriteRune('{')
enc := json.NewEncoder(b)
for i, k := range sm.keys {
err = enc.Encode(k)
if err != nil {
return
}
_, err = b.WriteRune(':')
if err != nil {
return
}
err = enc.Encode(sm.internal[k])
if err != nil {
return
}
if i < len(sm.keys)-1 {
_, err = b.WriteRune(',')
if err != nil {
return
}
}
}
b.WriteRune('}')
return b.Bytes(), nil
}
type Story struct {
Name string `json:"name"`
Args *SortedMap `json:"args"`
}