2 Commits

Author SHA1 Message Date
Ryan Hamamura
d4b831492e refactor: simplify Datastar configuration API
Flatten DatastarConfig struct into Options (DatastarContent, DatastarPath)
and replace datastarHandlerRegistered bool with sync.Once for thread safety.
2026-01-14 02:01:18 -10:00
Ryan Hamamura
ea7b9ad4a1 feat: add custom Datastar.js configuration support
Allow users to provide their own Datastar.js script (e.g., Datastar Pro
or custom builds) via Via's Options configuration. Adds DatastarConfig
struct with Content ([]byte) and Path (string) fields.
2026-01-14 01:47:39 -10:00
4 changed files with 86 additions and 15 deletions

View File

@@ -37,4 +37,12 @@ type Options struct {
// with scs LoadAndSave middleware. Configure the session manager before // with scs LoadAndSave middleware. Configure the session manager before
// passing it (lifetime, cookie settings, store, etc). // passing it (lifetime, cookie settings, store, etc).
SessionManager *scs.SessionManager SessionManager *scs.SessionManager
// DatastarContent is the Datastar.js script content.
// If nil, the embedded default is used.
DatastarContent []byte
// DatastarPath is the URL path where the script is served.
// Defaults to "/_datastar.js" if empty.
DatastarPath string
} }

1
h/h.go
View File

@@ -79,7 +79,6 @@ func HTML5(p HTML5Props) H {
Body: retype(p.Body), Body: retype(p.Body),
HTMLAttrs: retype(p.HTMLAttrs), HTMLAttrs: retype(p.HTMLAttrs),
} }
gp.Head = append(gp.Head, Script(Type("module"), Src("/_datastar.js")))
return gc.HTML5(gp) return gc.HTML5(gp)
} }

44
via.go
View File

@@ -32,14 +32,17 @@ var datastarJS []byte
// V is the root application. // V is the root application.
// It manages page routing, user sessions, and SSE connections for live updates. // It manages page routing, user sessions, and SSE connections for live updates.
type V struct { type V struct {
cfg Options cfg Options
mux *http.ServeMux mux *http.ServeMux
contextRegistry map[string]*Context contextRegistry map[string]*Context
contextRegistryMutex sync.RWMutex contextRegistryMutex sync.RWMutex
documentHeadIncludes []h.H documentHeadIncludes []h.H
documentFootIncludes []h.H documentFootIncludes []h.H
devModePageInitFnMap map[string]func(*Context) devModePageInitFnMap map[string]func(*Context)
sessionManager *scs.SessionManager sessionManager *scs.SessionManager
datastarPath string
datastarContent []byte
datastarOnce sync.Once
} }
func (v *V) logFatal(format string, a ...any) { func (v *V) logFatal(format string, a ...any) {
@@ -108,6 +111,12 @@ func (v *V) Config(cfg Options) {
if cfg.SessionManager != nil { if cfg.SessionManager != nil {
v.sessionManager = cfg.SessionManager v.sessionManager = cfg.SessionManager
} }
if cfg.DatastarContent != nil {
v.datastarContent = cfg.DatastarContent
}
if cfg.DatastarPath != "" {
v.datastarPath = cfg.DatastarPath
}
} }
// AppendToHead appends the given h.H nodes to the head of the base HTML document. // AppendToHead appends the given h.H nodes to the head of the base HTML document.
@@ -141,6 +150,7 @@ func (v *V) AppendToFoot(elements ...h.H) {
// }) // })
// }) // })
func (v *V) Page(route string, initContextFn func(c *Context)) { func (v *V) Page(route string, initContextFn func(c *Context)) {
v.ensureDatastarHandler()
// check for panics // check for panics
func() { func() {
defer func() { defer func() {
@@ -176,7 +186,7 @@ func (v *V) Page(route string, initContextFn func(c *Context)) {
if v.cfg.DevMode { if v.cfg.DevMode {
v.devModePersist(c) v.devModePersist(c)
} }
headElements := []h.H{} headElements := []h.H{h.Script(h.Type("module"), h.Src(v.datastarPath))}
headElements = append(headElements, v.documentHeadIncludes...) headElements = append(headElements, v.documentHeadIncludes...)
headElements = append(headElements, headElements = append(headElements,
h.Meta(h.Data("signals", fmt.Sprintf("{'via-ctx':'%s'}", id))), h.Meta(h.Data("signals", fmt.Sprintf("{'via-ctx':'%s'}", id))),
@@ -258,6 +268,15 @@ func (v *V) HTTPServeMux() *http.ServeMux {
return v.mux return v.mux
} }
func (v *V) ensureDatastarHandler() {
v.datastarOnce.Do(func() {
v.mux.HandleFunc("GET "+v.datastarPath, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/javascript")
_, _ = w.Write(v.datastarContent)
})
})
}
func (v *V) devModePersist(c *Context) { func (v *V) devModePersist(c *Context) {
p := filepath.Join(".via", "devmode", "ctx.json") p := filepath.Join(".via", "devmode", "ctx.json")
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil { if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
@@ -378,6 +397,8 @@ func New() *V {
contextRegistry: make(map[string]*Context), contextRegistry: make(map[string]*Context),
devModePageInitFnMap: make(map[string]func(*Context)), devModePageInitFnMap: make(map[string]func(*Context)),
sessionManager: scs.New(), sessionManager: scs.New(),
datastarPath: "/_datastar.js",
datastarContent: datastarJS,
cfg: Options{ cfg: Options{
DevMode: false, DevMode: false,
ServerAddress: ":3000", ServerAddress: ":3000",
@@ -386,11 +407,6 @@ func New() *V {
}, },
} }
v.mux.HandleFunc("GET /_datastar.js", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/javascript")
_, _ = w.Write(datastarJS)
})
v.mux.HandleFunc("GET /_sse", func(w http.ResponseWriter, r *http.Request) { v.mux.HandleFunc("GET /_sse", func(w http.ResponseWriter, r *http.Request) {
isReconnect := false isReconnect := false
if r.Header.Get("last-event-id") == "via" { if r.Header.Get("last-event-id") == "via" {

View File

@@ -28,6 +28,10 @@ func TestPageRoute(t *testing.T) {
func TestDatastarJS(t *testing.T) { func TestDatastarJS(t *testing.T) {
v := New() v := New()
v.Page("/", func(c *Context) {
c.View(func() h.H { return h.Div() })
})
req := httptest.NewRequest("GET", "/_datastar.js", nil) req := httptest.NewRequest("GET", "/_datastar.js", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
v.mux.ServeHTTP(w, req) v.mux.ServeHTTP(w, req)
@@ -37,6 +41,50 @@ func TestDatastarJS(t *testing.T) {
assert.Contains(t, w.Body.String(), "🖕JS_DS🚀") assert.Contains(t, w.Body.String(), "🖕JS_DS🚀")
} }
func TestCustomDatastarContent(t *testing.T) {
customScript := []byte("// Custom Datastar Script")
v := New()
v.Config(Options{
DatastarContent: customScript,
})
v.Page("/", func(c *Context) {
c.View(func() h.H { return h.Div() })
})
req := httptest.NewRequest("GET", "/_datastar.js", nil)
w := httptest.NewRecorder()
v.mux.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "application/javascript", w.Header().Get("Content-Type"))
assert.Contains(t, w.Body.String(), "Custom Datastar Script")
}
func TestCustomDatastarPath(t *testing.T) {
v := New()
v.Config(Options{
DatastarPath: "/assets/datastar.js",
})
v.Page("/test", func(c *Context) {
c.View(func() h.H { return h.Div() })
})
// Custom path should serve the script
req := httptest.NewRequest("GET", "/assets/datastar.js", nil)
w := httptest.NewRecorder()
v.mux.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "application/javascript", w.Header().Get("Content-Type"))
assert.Contains(t, w.Body.String(), "🖕JS_DS🚀")
// Page should reference the custom path in script tag
req2 := httptest.NewRequest("GET", "/test", nil)
w2 := httptest.NewRecorder()
v.mux.ServeHTTP(w2, req2)
assert.Contains(t, w2.Body.String(), `src="/assets/datastar.js"`)
}
func TestSignal(t *testing.T) { func TestSignal(t *testing.T) {
var sig *signal var sig *signal
v := New() v := New()