Skip to content

Commit

Permalink
feat: live-preview WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
xNaCly committed Apr 21, 2023
1 parent 3c9c1b9 commit 9317f41
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 6 deletions.
49 changes: 46 additions & 3 deletions core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ package core

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

"github.com/xnacly/fleck/cli"
Expand All @@ -28,15 +32,54 @@ func FlagCombinationSensible() {
// TODO: implement this
// TODO: document this in doc/Usage.md
func LivePreview(fileName string) {
updateChan := make(chan struct{})
port := "12345"

fmt.Print(logger.ANSI_CLEAR)
logger.LInfo("starting live preview")

Run(fileName)
// DONE: compile source

// start webserver at 12345, maybe a flag? --port
// TODO: make this a flag, --port x
file := strings.TrimSuffix(fileName, filepath.Ext(fileName))

go func() {
logger.LInfo("watching for changes...")

iStat, err := os.Stat(fileName)
if err != nil {
logger.LError("failed to watch for changes: " + err.Error())
}

i := 0
for {
stat, err := os.Stat(fileName)
if err != nil {
logger.L("test")
logger.LError("failed to watch for changes: " + err.Error())
}

if stat.Size() != iStat.Size() || stat.ModTime() != stat.ModTime() {
iStat = stat
i++
fmt.Print(logger.ANSI_CLEAR)
logger.LInfo("detected change, recompiling... (" + fmt.Sprint(i) + ")")
Run(fileName)
// notify web about change
updateChan <- struct{}{}
}

time.Sleep(100 * time.Millisecond)
}
}()

// inject js into html with websocket connection
// open default browser at localhost:12345

// if change -> send notification via websocket to html file
// html file should reload

logger.LInfo("listening on http://localhost:" + port + "/" + file + ".html")
log.Fatal(http.ListenAndServe(":"+port, http.FileServer(http.Dir("."))))
}

// watches for changes in a file, recompiles the file if a change occurs, can be exited via <C-c>
Expand Down
4 changes: 1 addition & 3 deletions fleck.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,7 @@ func main() {
logger.LWarn("'shell-macro-enabled' flag specified, this can harm your operating system and make it vulnerable for attack, proceed at your own digression")
}
if cli.GetFlag(cli.ARGUMENTS, "live-preview") {
logger.LError("not implemented yet, watch out for the next release!")
// TODO:
// core.LivePreview(fileName)
core.LivePreview(fileName)
} else if cli.GetFlag(cli.ARGUMENTS, "watch") {
core.WatchForChanges(fileName, core.Run)
} else {
Expand Down

0 comments on commit 9317f41

Please sign in to comment.