Skip to content

Commit 9317f41

Browse files
committed
feat: live-preview WIP
1 parent 3c9c1b9 commit 9317f41

File tree

2 files changed

+47
-6
lines changed

2 files changed

+47
-6
lines changed

core/core.go

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@ package core
22

33
import (
44
"fmt"
5+
"log"
6+
"net/http"
57
"os"
8+
"path/filepath"
9+
"strings"
610
"time"
711

812
"github.com/xnacly/fleck/cli"
@@ -28,15 +32,54 @@ func FlagCombinationSensible() {
2832
// TODO: implement this
2933
// TODO: document this in doc/Usage.md
3034
func LivePreview(fileName string) {
35+
updateChan := make(chan struct{})
36+
port := "12345"
37+
38+
fmt.Print(logger.ANSI_CLEAR)
3139
logger.LInfo("starting live preview")
40+
3241
Run(fileName)
33-
// DONE: compile source
3442

35-
// start webserver at 12345, maybe a flag? --port
43+
// TODO: make this a flag, --port x
44+
file := strings.TrimSuffix(fileName, filepath.Ext(fileName))
45+
46+
go func() {
47+
logger.LInfo("watching for changes...")
48+
49+
iStat, err := os.Stat(fileName)
50+
if err != nil {
51+
logger.LError("failed to watch for changes: " + err.Error())
52+
}
53+
54+
i := 0
55+
for {
56+
stat, err := os.Stat(fileName)
57+
if err != nil {
58+
logger.L("test")
59+
logger.LError("failed to watch for changes: " + err.Error())
60+
}
61+
62+
if stat.Size() != iStat.Size() || stat.ModTime() != stat.ModTime() {
63+
iStat = stat
64+
i++
65+
fmt.Print(logger.ANSI_CLEAR)
66+
logger.LInfo("detected change, recompiling... (" + fmt.Sprint(i) + ")")
67+
Run(fileName)
68+
// notify web about change
69+
updateChan <- struct{}{}
70+
}
71+
72+
time.Sleep(100 * time.Millisecond)
73+
}
74+
}()
75+
3676
// inject js into html with websocket connection
37-
// open default browser at localhost:12345
77+
3878
// if change -> send notification via websocket to html file
3979
// html file should reload
80+
81+
logger.LInfo("listening on http://localhost:" + port + "/" + file + ".html")
82+
log.Fatal(http.ListenAndServe(":"+port, http.FileServer(http.Dir("."))))
4083
}
4184

4285
// watches for changes in a file, recompiles the file if a change occurs, can be exited via <C-c>

fleck.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,7 @@ func main() {
4848
logger.LWarn("'shell-macro-enabled' flag specified, this can harm your operating system and make it vulnerable for attack, proceed at your own digression")
4949
}
5050
if cli.GetFlag(cli.ARGUMENTS, "live-preview") {
51-
logger.LError("not implemented yet, watch out for the next release!")
52-
// TODO:
53-
// core.LivePreview(fileName)
51+
core.LivePreview(fileName)
5452
} else if cli.GetFlag(cli.ARGUMENTS, "watch") {
5553
core.WatchForChanges(fileName, core.Run)
5654
} else {

0 commit comments

Comments
 (0)