notes-server/notes/file.go

61 lines
1.7 KiB
Go
Executable File

package notes
import (
"encoding/base64"
"errors"
"fmt"
"io"
"io/ioutil"
"local/notes-server/filetree"
"strings"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/ast"
"github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser"
)
func (n *Notes) File(urlPath string) (string, error) {
p := filetree.NewPathFromURL(urlPath)
if p.IsDir() {
return "", errors.New("path is dir")
}
b, _ := ioutil.ReadFile(p.Local)
renderer := html.NewRenderer(html.RendererOptions{
Flags: html.CommonFlags | html.TOC,
RenderNodeHook: n.commentFormer(),
})
parser := parser.NewWithExtensions(parser.CommonExtensions | parser.HeadingIDs | parser.AutoHeadingIDs | parser.Titleblock)
content := markdown.ToHTML(b, parser, renderer)
return string(content) + "\n", nil
}
func (n *Notes) commentFormer() html.RenderNodeFunc {
header_n := 0
return func(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
if heading, ok := node.(*ast.Heading); ok {
if !entering {
literal := ""
ast.WalkFunc(heading, func(n ast.Node, e bool) ast.WalkStatus {
if leaf := n.AsLeaf(); e && leaf != nil {
if literal != "" {
literal += ".*"
}
literal += string(leaf.Literal)
}
return ast.GoToNext
})
level := heading.Level
id := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(`^[ \t]*%s\s*%s(].*)?\s*$`, strings.Repeat("#", level), literal)))
fmt.Fprintf(w, `
<form method="POST" target="/comment" name="%s" class="comment">
<input autocomplete="off" name="content" type="text"/>
<input type="submit"/>
</form>
`, id)
}
}
return ast.GoToNext, false
}
}