/
code.go
112 lines (97 loc) · 2.5 KB
/
code.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
package helpers
import (
"bytes"
"html"
"html/template"
"path/filepath"
"strings"
"github.com/gobuffalo/buffalo/render"
"github.com/gobuffalo/genny/v2"
"github.com/gobuffalo/github_flavored_markdown"
"github.com/gobuffalo/packr/v2"
"github.com/gobuffalo/plush/v4"
"github.com/gobuffalo/tags"
"github.com/markbates/going/randx"
"github.com/pkg/errors"
)
func CodeTabs(help plush.HelperContext) (template.HTML, error) {
if !help.HasBlock() {
return "", nil
}
s, err := help.Block()
if err != nil {
return "", errors.WithStack(err)
}
return codeTab(s)
}
func codeTab(s string) (template.HTML, error) {
s = strings.TrimSpace(s)
t := tags.New("div", tags.Options{
"class": "codetabs",
"id": randx.String(10),
})
t.Append(tags.New("ul", tags.Options{}))
s = string(github_flavored_markdown.Markdown([]byte(s)))
s = html.UnescapeString(s)
t.Append(tags.New("div", tags.Options{
"class": "tab-content",
"body": template.HTML(s),
}))
return t.HTML(), nil
}
func ExampleDir(r *render.Engine) func(dir string, help plush.HelperContext) (template.HTML, error) {
return func(dir string, help plush.HelperContext) (template.HTML, error) {
files := map[string][]genny.File{}
box := r.TemplatesBox
err := box.WalkPrefix(dir, func(path string, f packr.File) error {
if filepath.Base(path) == ".DS_Store" {
return nil
}
name := strings.TrimPrefix(path, dir+string(filepath.Separator))
key := "/"
dirs := strings.Split(name, string(filepath.Separator))
if len(dirs) > 1 {
key = dirs[0]
}
gfs, ok := files[key]
if !ok {
gfs = []genny.File{}
}
gfs = append(gfs, genny.NewFile(name, f))
files[key] = gfs
return nil
})
if err != nil {
return "", errors.WithStack(err)
}
div := tags.New("div", tags.Options{})
for k, gfs := range files {
dt := tags.New("div", tags.Options{})
title := strings.TrimSpace(k)
if !strings.HasPrefix(title, "/") {
title = "/" + title
}
title = "." + title
dt.Append(tags.New("h3", tags.Options{"body": title}))
bb := &bytes.Buffer{}
for _, f := range gfs {
ext := strings.TrimPrefix(filepath.Ext(f.Name()), ".")
if len(ext) == 0 {
ext = "plain"
}
bb.WriteString("\n```")
bb.WriteString(ext + "\n")
bb.WriteString("// " + f.Name() + "\n")
bb.WriteString(f.String())
bb.WriteString("\n```\n")
}
ct, err := codeTab(bb.String())
if err != nil {
return "", errors.WithStack(err)
}
dt.Append(ct)
div.Append(dt)
}
return div.HTML(), nil
}
}