Skip to content

Commit

Permalink
feat: auto-refresh browser on live reload
Browse files Browse the repository at this point in the history
TODO: If the browser is refreshed manually, the file has to be modified
  twice to reload the page later.

Co-authored-by: Aditya Hegde <[email protected]>
  • Loading branch information
anirudhsudhir and bwaklog committed Apr 8, 2024
1 parent 6fb4718 commit b71d24a
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 4 deletions.
2 changes: 2 additions & 0 deletions cmd/anna/anna.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
type Cmd struct {
RenderDrafts bool
Addr string
LiveReload bool
}

func (cmd *Cmd) VanillaRender() {
Expand All @@ -23,6 +24,7 @@ func (cmd *Cmd) VanillaRender() {
TagsMap: make(map[string][]parser.TemplateData),
ErrorLogger: log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile),
RenderDrafts: cmd.RenderDrafts,
LiveReload: cmd.LiveReload,
}
e := engine.Engine{
Templates: make(map[template.URL]parser.TemplateData),
Expand Down
35 changes: 34 additions & 1 deletion cmd/anna/livereload.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,16 @@ import (
"net/http"
"os"
"path/filepath"
"sync/atomic"
"time"

"github.com/acmpesuecc/anna/pkg/helpers"
)

var reloadPage = make(chan struct{})

var countRequests atomic.Int32

type liveReload struct {
errorLogger *log.Logger
fileTimes map[string]time.Time
Expand Down Expand Up @@ -43,6 +48,7 @@ func (cmd *Cmd) StartLiveReload() {
for _, rootDir := range lr.rootDirs {
if lr.traverseDirectory(rootDir) {
cmd.VanillaRender()
reloadPage <- struct{}{}
}
}
if !lr.serverRunning {
Expand Down Expand Up @@ -97,8 +103,35 @@ func (lr *liveReload) checkFile(path string, modTime time.Time) bool {

func (lr *liveReload) startServer(addr string) {
fmt.Print("Serving content at: http://localhost:", addr, "\n")
err := http.ListenAndServe(":"+addr, http.FileServer(http.Dir(helpers.SiteDataPath+"./rendered")))
http.Handle("/", http.FileServer(http.Dir(helpers.SiteDataPath+"./rendered")))
http.HandleFunc("/events", eventsHandler)
err := http.ListenAndServe(":"+addr, nil)
if err != nil {
lr.errorLogger.Fatal(err)
}
}

func eventsHandler(w http.ResponseWriter, r *http.Request) {
countRequests.Add(1)

// Set CORS headers to allow all origins.
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Expose-Headers", "Content-Type")

w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")

if countRequests.Load() == 1 {
<-reloadPage
} else {
countRequests.Store(countRequests.Load() - 1)
return
}

event := "event:\ndata:\n\n"
w.Write([]byte(event))
w.(http.Flusher).Flush()

countRequests.Store(countRequests.Load() - 1)
}
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ func main() {
}

if serve {
annaCmd.LiveReload = true
annaCmd.StartLiveReload()
}

Expand Down
6 changes: 5 additions & 1 deletion pkg/parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ type TemplateData struct {
Frontmatter Frontmatter
Body template.HTML
Layout LayoutConfig
LiveReload bool

// Do not use these fields to store tags!!
// These fields are populated by the ssg to store merged tag data
Expand Down Expand Up @@ -80,6 +81,9 @@ type Parser struct {
ErrorLogger *log.Logger

Helper *helpers.Helper

// Determines the injection of Live Reload JS in HTML
LiveReload bool
}

func (p *Parser) ParseMDDir(baseDirPath string, baseDirFS fs.FS) {
Expand Down Expand Up @@ -135,6 +139,7 @@ func (p *Parser) AddFileAndRender(baseDirPath string, dirEntryPath string, front
Frontmatter: frontmatter,
Body: template.HTML(body),
Layout: p.LayoutConfig,
LiveReload: p.LiveReload,
}

// Adding the page to the merged map storing all site pages
Expand Down Expand Up @@ -253,7 +258,6 @@ func (p *Parser) ParseRobots(inFilePath string, outFilePath string) {

// Parse all the ".html" layout files in the layout/ directory
func (p *Parser) ParseLayoutFiles() *template.Template {

// Parsing all files in the layout/ dir which match the "*.html" pattern
templ, err := template.ParseGlob(helpers.SiteDataPath + "layout/*.html")
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion site/layout/page.html
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,4 @@ <h1>{{ .Frontmatter.Title }}</h1>

</html>

{{ end}}
{{ end}}
18 changes: 17 additions & 1 deletion site/layout/partials/head.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,28 @@
<link rel="stylesheet" href="https://unpkg.com/highlightjs-copy/dist/highlightjs-copy.min.css" />
<link rel="alternate" type="application/atom+xml" title="feed" href="/feed.atom" />


{{ if .LiveReload }}
<script>
const eventSource = new EventSource('http://localhost:8000/events');
eventSource.onmessage = function (event) {
location.reload()
};
window.onbeforeunload = function(event)
{
return confirm("Confirm refresh");
};
</script>
{{ end }}


{{range .Frontmatter.JSFiles}}
<script src="/script/{{.}}" defer></script>
{{end}} {{range .Layout.SiteScripts}}
<script src="/script/{{.}}" defer></script>
{{end}}


<meta property="og:type" content="website" />
<meta property="og:title" content="{{ .Frontmatter.Title }}" />
<meta property="og:description" content="{{ .Frontmatter.Description }}" />
Expand All @@ -33,4 +49,4 @@
</head>
{{end}}

</html>
</html>

0 comments on commit b71d24a

Please sign in to comment.