package frontend
import (
"html/template"
"net/http"
"os"
"git.sleepycat.moe/sam/mercury/frontend"
"git.sleepycat.moe/sam/mercury/internal/database"
"git.sleepycat.moe/sam/mercury/web/app"
"github.com/rs/zerolog/log"
vueglue "github.com/torenware/vite-go"
_ "embed"
)
//go:embed app.html
var htmlTemplate string
type Frontend struct {
*app.App
glue *vueglue.VueGlue
urlPrefix string
fileServer http.Handler
tmpl *template.Template
}
func New(app *app.App) *Frontend {
fe := &Frontend{
App: app,
}
if app.Config.Core.Dev {
glue, err := vueglue.NewVueGlue(&vueglue.ViteConfig{
Environment: "development",
AssetsPath: "frontend",
EntryPoint: "src/main.ts",
Platform: "svelte",
FS: os.DirFS("frontend"),
})
if err != nil {
log.Err(err).Msg("Creating vite glue")
os.Exit(1)
}
fe.glue = glue
fe.urlPrefix = "/src/*"
} else {
glue, err := vueglue.NewVueGlue(&vueglue.ViteConfig{
Environment: "production",
URLPrefix: "/assets/",
AssetsPath: "dist",
EntryPoint: "src/main.ts",
Platform: "svelte",
FS: frontend.Embed,
})
if err != nil {
log.Err(err).Msg("Creating vite glue")
os.Exit(1)
}
fe.glue = glue
fe.urlPrefix = "/assets/*"
}
fileServer, err := fe.glue.FileServer()
if err != nil {
log.Err(err).Msg("Creating vite file server")
os.Exit(1)
}
fe.fileServer = fileServer
tmpl, err := template.New("app").Parse(htmlTemplate)
if err != nil {
log.Err(err).Msg("Parsing frontend HTML template")
os.Exit(1)
}
fe.tmpl = tmpl
return fe
}
func (app *Frontend) AssetsPath() string { return app.urlPrefix }
func (app *Frontend) ServeAssets(w http.ResponseWriter, r *http.Request) {
app.fileServer.ServeHTTP(w, r)
}
func (app *Frontend) ServeFrontend(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
err := app.tmpl.Execute(w, map[string]any{
"Config": database.DefaultConfig,
"Vue": app.glue,
})
if err != nil {
log.Err(err).Msg("executing frontend template")
}
}