Skip to content

Commit

Permalink
feat: auto-refresh browser during live reload
Browse files Browse the repository at this point in the history
Co-authored-by: Aditya Hegde <[email protected]>
  • Loading branch information
anirudhsudhir and bwaklog committed Apr 11, 2024
2 parents 3b2093f + b71d24a commit 9328f7c
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[template.URL][]parser.TemplateData),
ErrorLogger: log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile),
RenderDrafts: cmd.RenderDrafts,
LiveReload: cmd.LiveReload,
}

e := engine.Engine{
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 @@ -45,6 +45,7 @@ type TemplateData struct {
Frontmatter Frontmatter
Body template.HTML
Layout LayoutConfig
LiveReload bool
}

type Date int64
Expand Down Expand Up @@ -74,6 +75,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 @@ -129,6 +133,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 @@ -248,7 +253,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/*.layout")
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 @@ -41,4 +41,4 @@ <h1>{{ $PageData.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.xml" />


{{ 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 9328f7c

Please sign in to comment.