Skip to content

Add hot reload for templ feature and updated go server to allow hot reload during local dev and update dependencies #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,8 @@ Runs a simple web server for local playground development
```sh
serve -dir ./public
```
### hot-serve
Runs a simple web server for local playground development with hot reload and sse events to refresh client
```sh
go run server/main.go
```
10 changes: 8 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ module templ/templ-to-go-wasm

go 1.22.2

require github.com/a-h/templ v0.2.663
require (
github.com/a-h/templ v0.2.663
github.com/fsnotify/fsnotify v1.7.0
)

require github.com/a-h/parse v0.0.0-20240121214402-3caf7543159a // indirect
require (
github.com/a-h/parse v0.0.0-20240121214402-3caf7543159a // indirect
golang.org/x/sys v0.15.0 // indirect
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ github.com/a-h/parse v0.0.0-20240121214402-3caf7543159a h1:vlmAfVwFK9sRpDlJyuHY8
github.com/a-h/parse v0.0.0-20240121214402-3caf7543159a/go.mod h1:3mnrkvGpurZ4ZrTDbYU84xhwXW2TjTKShSwjRi2ihfQ=
github.com/a-h/templ v0.2.663 h1:aa0WMm27InkYHGjimcM7us6hJ6BLhg98ZbfaiDPyjHE=
github.com/a-h/templ v0.2.663/go.mod h1:SA7mtYwVEajbIXFRh3vKdYm/4FYyLQAtPH1+KxzGPA8=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
69 changes: 69 additions & 0 deletions public/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -270,3 +270,72 @@ button.loading::after {
.bottom-panel-row.child__panel--hidden {
grid-template-columns: 1fr;
}

.checkbox {
display: flex;
position: relative;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
gap: 0.5rem;
}
.checkbox input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
.checkbox input:checked ~ .checkbox__checkmark {
background-color: var(--main-accent-color);
}
.checkbox input:checked ~ .checkbox__checkmark:after {
opacity: 1;
}
.checkbox:hover input ~ .checkbox__checkmark {
background-color: var(--main-accent-color);
}
.checkbox:hover input:checked ~ .checkbox__checkmark {
background-color: var(--main-accent-color);
}
.checkbox .checkbox__checkmark {
height: 15px;
width: 15px;
background-color: transparent;
transition: background-color 0.25s ease;
border-radius: 4px;
align-self: center;
border: 1px solid var(--main-accent-color);
}
.checkbox .checkbox__checkmark:after {
content: "";
position: absolute;
left: 5px;
width: 5px;
height: 10px;
border: solid #333;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
opacity: 0;
transition: opacity 0.25s ease;
}
.checkbox .checkbox__body {
color: var(--main-accent-color);
line-height: 1.6;
font-size: 0.85rem;
display: flex;
align-items: center;
}

.top-tool-bar__left, .top-tool-bar__right {
display: flex;
flex-direction: row;
align-items: center;
gap: 0.5rem;
}

.checkbox__container {
display: flex;
}
27 changes: 18 additions & 9 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
Expand Down Expand Up @@ -95,7 +95,7 @@
</nav>
<div class="container">
<div class="top-tool-bar">
<div>
<div class="top-tool-bar__left">
<button
onclick="compileAndRunCode()"
class="run-button"
Expand All @@ -107,13 +107,22 @@
<span class="button-text"> Format </span>
</button>
</div>
<button
onclick="toggleHTMLPanel()"
class="html-toggle theme-toggle--toggled"
id="htmlToggle"
>
Show HTML
</button>
<div class="top-tool-bar__right">
<div class="checkbox__container">
<label class="checkbox">
<input type="checkbox" id="hotReloadToggle" />
<div class="checkbox__checkmark"></div>
<div class="checkbox__body">Hot Reload</div>
</label>
</div>
<button
onclick="toggleHTMLPanel()"
class="html-toggle theme-toggle--toggled"
id="htmlToggle"
>
Show HTML
</button>
</div>
</div>
<div class="code-editor-panel">
<div class="panel-header">templ</div>
Expand Down
45 changes: 34 additions & 11 deletions public/script.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,47 @@
let go = new Go();
let editor;
let htmlCodeEditor;
WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then(
(result) => {
go.run(result.instance);
},
);

WebAssembly.instantiateStreaming(
fetch("/assembly/main.wasm"),
go.importObject
).then((result) => {
go.run(result.instance);
});
window.onload = function () {
let timeoutId = null;
const delay = 500;

editor = ace.edit("templ-code");
editor.setTheme("ace/theme/dracula");
editor.getSession().setMode("ace/mode/go");
editor.setShowPrintMargin(false);
editor.on("change", compileGo);
editor.on("change", function () {
console.log("Code Changed");
const hotReloadChecked = document.getElementById("hotReloadToggle").checked
console.log(hotReloadChecked)
if (hotReloadChecked) {
if (timeoutId) {
clearTimeout(timeoutId);
}

timeoutId = setTimeout(compileAndRunCode, delay);
}
});

htmlCodeEditor = ace.edit("output");
htmlCodeEditor.setTheme("ace/theme/dracula");
htmlCodeEditor.getSession().setMode("ace/mode/html");
htmlCodeEditor.setReadOnly(true);
htmlCodeEditor.setShowPrintMargin(false);
};
var source = new EventSource("/events");
source.onmessage = function (e) {
if (e.data === "refresh") {
console.log("%cPage Hot Reloaded", "font-weight: bold; color: cyan;");
location.reload();
}
};
};
async function formatTempl() {
editor.getSession().setAnnotations();
const formatButton = document.getElementById("formatButton");
Expand Down Expand Up @@ -110,18 +133,18 @@ function toggleDarkMode() {

editor.setTheme(isDarkMode ? "ace/theme/dracula" : "ace/theme/textmate");
htmlCodeEditor.setTheme(
isDarkMode ? "ace/theme/dracula" : "ace/theme/textmate",
isDarkMode ? "ace/theme/dracula" : "ace/theme/textmate"
);
}

function toggleHTMLPanel() {
let currentHtmlCode = htmlCodeEditor.session.getValue()
htmlCodeEditor.session.setValue(currentHtmlCode)
let currentHtmlCode = htmlCodeEditor.session.getValue();
htmlCodeEditor.session.setValue(currentHtmlCode);

document
.getElementById("htmlToggle")
.classList.toggle("html-toggle--toggled");

document
.getElementById("bottomPanelRow")
.classList.toggle("child__panel--hidden");
Expand Down
96 changes: 88 additions & 8 deletions server/main.go
Original file line number Diff line number Diff line change
@@ -1,23 +1,103 @@
package main

import (
"fmt"
"log"
"net/http"
"path/filepath"
"strings"

"github.com/fsnotify/fsnotify"
)

var clients = make(map[chan bool]bool)

func main() {
fs := http.FileServer(http.Dir("."))
http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.ServeFile(w, r, "index.html")
} else {
fs.ServeHTTP(w, r)
http.ServeFile(w, r, "public/index.html")
return
}

path := filepath.Join("public", r.URL.Path)
if strings.HasSuffix(r.URL.Path, ".wasm") {
w.Header().Set("Content-Type", "application/wasm")
}

http.ServeFile(w, r, path)
})

http.HandleFunc("/events", sseHandler)

go watchPublicDir()

log.Println("Starting server on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}

func sseHandler(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}

notify := make(chan bool)
clients[notify] = true

defer func() {
delete(clients, notify)
close(notify)
}()

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

for {
select {
case <-notify:
fmt.Fprintf(w, "data: refresh\n\n")
flusher.Flush()
case <-r.Context().Done():
return
}
}))
}
}

func watchPublicDir() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()

log.Println("Listening on :5757...")
err := http.ListenAndServe("127.0.0.1:5757", nil)
err = watcher.Add("public")
if err != nil {
log.Fatal(err)
}

for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write {
log.Println("Modified file:", event.Name)
notifyClients()
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("Error:", err)
}
}
}

func notifyClients() {
for client := range clients {
client <- true
}
}