forked from andreaskoch/allmark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
renderer.go
92 lines (68 loc) · 2.04 KB
/
renderer.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
// Copyright 2014 Andreas Koch. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package filetreerenderer
import (
"fmt"
"strings"
"github.com/andreaskoch/allmark/common/paths"
"github.com/andreaskoch/allmark/common/route"
"github.com/andreaskoch/allmark/model"
)
func New(pathProvider paths.Pather, baseRoute route.Route, files []*model.File) *FileTreeRenderer {
return &FileTreeRenderer{
pathProvider: pathProvider,
base: baseRoute,
files: convertFilesToTree(files),
}
}
type FileTreeRenderer struct {
pathProvider paths.Pather
base route.Route
files *FileTree
}
func (r *FileTreeRenderer) Render(title, cssClass, path string) string {
// create the base route from the path
folderRoute := route.NewFromRequest(path)
fullFolderRoute := route.Combine(r.base, folderRoute)
// render the filesystem
code := ""
if strings.TrimSpace(title) != "" {
code += fmt.Sprintf("\n**%s**\n\n", title)
}
if rootNode := r.files.GetNode(fullFolderRoute); rootNode != nil {
// Render the children of the root node
code += "- " + r.renderFileNode(rootNode, 1)
}
return code
}
func (r *FileTreeRenderer) renderFileNode(node *FileNode, indentation int) string {
html := ""
if file := node.Value(); file != nil {
fileRoute := file.Route()
filepath := r.pathProvider.Path(fileRoute.Value())
html = fmt.Sprintf("[%s](%s)\n", fileRoute.LastComponentName(), filepath)
} else {
html = node.Name() + "\n"
}
if children := node.Children(); len(children) > 0 {
for _, child := range children {
html += fmt.Sprintf("%s- %s", getIndentation(indentation, "\t"), r.renderFileNode(child, indentation+1))
}
}
return html
}
func getIndentation(depth int, character string) string {
indentation := ""
for level := 1; level <= depth; level++ {
indentation += character
}
return indentation
}
func convertFilesToTree(files []*model.File) *FileTree {
tree := newTree()
for _, file := range files {
tree.Insert(file)
}
return tree
}