frontend.go

299 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
package frontend

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
	"os"
	"path/filepath"
	"sync"

	"congo.gg/pkg/application"
	"congo.gg/pkg/frontend/esbuild"
)

// Frontend manages JavaScript component islands within HTMX-driven pages.
type Frontend struct {
	SourceDir string // Default: "components"
	OutputDir string // Default: "views/static/scripts/gen"
	DevMode   bool   // Enable HMR and file watching

	// Bundler configuration (optional, for WithBundler)
	bundler  *esbuild.Bundler
	buildMu  sync.Mutex // serializes concurrent Build() calls

	// HMR broadcast hub — a single goroutine owns client state,
	// no mutex needed. Channels coordinate access.
	hmrJoin   chan chan struct{} // send a channel to subscribe
	hmrLeave  chan chan struct{} // send a channel to unsubscribe
	hmrReload chan struct{}      // signal all clients to reload
	hmrDone   chan struct{}      // closed on Stop() to shut down hub

	// File watcher (stored for cleanup)
	watcher interface{ Close() error }
}

// New creates a new Frontend instance.
func New() *Frontend {
	f := &Frontend{
		SourceDir: "components",
		OutputDir: "views/static/scripts/gen",
		DevMode:   os.Getenv("ENV") != "production",
		hmrJoin:   make(chan chan struct{}),
		hmrLeave:  make(chan chan struct{}),
		hmrReload: make(chan struct{}, 1),
		hmrDone:   make(chan struct{}),
	}
	go f.hmrHub()
	return f
}

// hmrHub is a single goroutine that owns the client map.
// All access is serialized through channels — no mutex needed.
func (f *Frontend) hmrHub() {
	clients := make(map[chan struct{}]struct{})
	for {
		select {
		case ch := <-f.hmrJoin:
			clients[ch] = struct{}{}
		case ch := <-f.hmrLeave:
			delete(clients, ch)
		case <-f.hmrReload:
			for ch := range clients {
				select {
				case ch <- struct{}{}:
				default:
				}
			}
		case <-f.hmrDone:
			for ch := range clients {
				close(ch)
			}
			return
		}
	}
}

// Script returns the runtime script tags for templates.
// This includes mount orchestration and HMR client in development.
// The nonce parameter is injected into all generated <script> tags for CSP compliance.
func (f *Frontend) Script(nonce string) template.HTML {
	nonceAttr := ""
	if nonce != "" {
		nonceAttr = fmt.Sprintf(` nonce="%s"`, nonce)
	}

	hmr := ""
	if f.DevMode {
		hmr = `
// HMR in development
if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') {
    const evtSource = new EventSource('/_frontend/hmr');
    evtSource.onmessage = () => location.reload();
    evtSource.onerror = () => setTimeout(() => location.reload(), 1000);
}
`
	}

	// Mount orchestration (framework-agnostic)
	// Components bundle must provide: __render(el, Component, props), __unmount(el), window.ComponentName
	orchestration := fmt.Sprintf(`
<script%s>
window.__renderAll = function() {
    document.querySelectorAll('[data-component]').forEach(el => {
        const name = el.dataset.component;
        const Component = window[name];
        if (!Component) {
            console.warn('[frontend] Component not found:', name);
            return;
        }
        el.innerHTML = '';
        __render(el, Component, JSON.parse(el.dataset.props || '{}'));
    });
};

// HTMX integration - use document instead of document.body to avoid null reference
// when script runs in <head> before body exists
document.addEventListener('htmx:beforeSwap', (e) => {
    e.detail.target.querySelectorAll('[data-component]').forEach(__unmount);
});
document.addEventListener('htmx:afterSwap', (e) => {
    e.detail.target.querySelectorAll('[data-component]').forEach(el => {
        const Component = window[el.dataset.component];
        if (Component) {
            el.innerHTML = '';
            __render(el, Component, JSON.parse(el.dataset.props || '{}'));
        }
    });
});

// Handle full page swaps (hx-boost)
document.addEventListener('htmx:afterSettle', (e) => {
    if (e.detail.requestConfig?.boosted) {
        __renderAll();
    }
});
</script>
`, nonceAttr)

	// Cache-busting hash from bundle content
	cacheBust := ""
	if data, err := os.ReadFile(filepath.Join(f.OutputDir, "components.js")); err == nil {
		h := sha256.Sum256(data)
		cacheBust = "?v=" + hex.EncodeToString(h[:4])
	}

	// Components bundle + trigger
	bundle := fmt.Sprintf(`<script%s type="module" src="/_frontend/components.js%s"></script>
<script%s type="module">
__renderAll();
%s
</script>`, nonceAttr, cacheBust, nonceAttr, hmr)

	return template.HTML(orchestration + bundle)
}

// Render returns an island container for the named component.
// Props are JSON-serialized into data-props attribute.
func (f *Frontend) Render(name string, props any) template.HTML {
	propsJSON := "{}"
	if props != nil {
		data, err := json.Marshal(props)
		if err == nil {
			propsJSON = string(data)
		}
	}

	// Use a skeleton placeholder while the component loads
	html := fmt.Sprintf(`<div data-component="%s" data-props='%s'>
    <div class="skeleton h-32 w-full"></div>
</div>`, template.HTMLEscapeString(name), template.HTMLEscapeString(propsJSON))

	return template.HTML(html)
}

// handleHMR handles SSE connections for hot module replacement.
func (f *Frontend) handleHMR(w http.ResponseWriter, r *http.Request) {
	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "SSE not supported", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	if f.DevMode {
		w.Header().Set("Access-Control-Allow-Origin", "*")
	}

	// Subscribe to reload signals via the hub
	ch := make(chan struct{}, 1)
	select {
	case f.hmrJoin <- ch:
	case <-f.hmrDone:
		return
	}

	// Send initial connection message
	fmt.Fprintf(w, "data: connected\n\n")
	flusher.Flush()

	// Wait for reload signal or disconnect
	select {
	case <-ch:
		fmt.Fprintf(w, "data: reload\n\n")
		flusher.Flush()
	case <-r.Context().Done():
	}

	// Unsubscribe — safe even after hub shutdown
	select {
	case f.hmrLeave <- ch:
	case <-f.hmrDone:
	}
}

// handleComponents serves the compiled components bundle.
func (f *Frontend) handleComponents(w http.ResponseWriter, r *http.Request) {
	bundlePath := filepath.Join(f.OutputDir, "components.js")

	// Check if bundle exists
	if _, err := os.Stat(bundlePath); os.IsNotExist(err) {
		// Try to build if source exists
		if _, srcErr := os.Stat(f.SourceDir); srcErr == nil {
			if buildErr := f.Build(); buildErr != nil {
				http.Error(w, "Build failed: "+buildErr.Error(), http.StatusInternalServerError)
				return
			}
		} else {
			// No source, serve empty module
			w.Header().Set("Content-Type", "application/javascript")
			w.Write([]byte("// No components found\nwindow.__render = () => {};\nwindow.__unmount = () => {};\n"))
			return
		}
	}

	w.Header().Set("Content-Type", "application/javascript")
	if f.DevMode {
		w.Header().Set("Cache-Control", "no-cache")
	} else {
		w.Header().Set("Cache-Control", "max-age=31536000")
	}
	http.ServeFile(w, r, bundlePath)
}

// handleSourceMap serves the source map for debugging.
func (f *Frontend) handleSourceMap(w http.ResponseWriter, r *http.Request) {
	mapPath := filepath.Join(f.OutputDir, "components.js.map")
	if _, err := os.Stat(mapPath); os.IsNotExist(err) {
		http.NotFound(w, r)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	http.ServeFile(w, r, mapPath)
}

// notifyClients signals all connected HMR clients to reload.
func (f *Frontend) notifyClients() {
	select {
	case f.hmrReload <- struct{}{}:
	default:
	}
}

// WithBundler returns an application.Option that uses the esbuild bundler.
// This is the recommended way to configure the frontend for library mode.
//
// Example:
//
//	application.Serve(views,
//	    frontend.WithBundler(&esbuild.Config{
//	        Entry:   "components/index.ts",
//	        Include: []string{"components"},
//	    }),
//	)
func WithBundler(cfg *esbuild.Config) application.Option {
	f := New()

	// Default config if nil
	if cfg == nil {
		cfg = &esbuild.Config{}
	}

	// Set source dir from config (first Include directory, used for file watching)
	if len(cfg.Include) > 0 {
		f.SourceDir = cfg.Include[0]
	}

	// Create bundler
	f.bundler = esbuild.NewBundler(cfg, f.OutputDir, f.DevMode)

	return func(app *application.App) {
		app.Controller(f.Controller())
	}
}