This repository has been archived by the owner on Dec 26, 2023. It is now read-only.
/
livejs.go
67 lines (54 loc) · 1.63 KB
/
livejs.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
// Package livejs injects code to reload the current page when it (or its
// dependencies) are modified. This plugin is helpful for authoring web content
// locally, but should be disabled for site deployment. This can be achieved by
// conditionally including it using the "condition" filter.
package livejs
import (
"bytes"
_ "embed"
"fmt"
"github.com/FooSoft/goldsmith"
"github.com/FooSoft/goldsmith-components/filters/wildcard"
"github.com/PuerkitoBio/goquery"
)
//go:embed js/live.js
var livejs string
// LiveJs chainable context.
type LiveJs struct {
html string
}
// New creates a new instance of the LiveJs plugin.
func New() *LiveJs {
return new(LiveJs)
}
func (*LiveJs) Name() string {
return "livejs"
}
func (self *LiveJs) Initialize(context *goldsmith.Context) error {
self.html = fmt.Sprintf("\n<!-- begin livejs code -->\n<script>\n%s\n</script>\n<!-- end livejs code -->\n", livejs)
context.Filter(wildcard.New("**/*.html", "**/*.htm"))
return nil
}
func (self *LiveJs) Process(context *goldsmith.Context, inputFile *goldsmith.File) error {
if outputFile := context.RetrieveCachedFile(inputFile.Path(), inputFile); outputFile != nil {
outputFile.CopyProps(inputFile)
context.DispatchFile(outputFile)
return nil
}
doc, err := goquery.NewDocumentFromReader(inputFile)
if err != nil {
return err
}
doc.Find("body").AppendHtml(self.html)
html, err := doc.Html()
if err != nil {
return err
}
outputFile, err := context.CreateFileFromReader(inputFile.Path(), bytes.NewReader([]byte(html)))
if err != nil {
return err
}
outputFile.CopyProps(inputFile)
context.DispatchAndCacheFile(outputFile)
return nil
}