-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLLM.txt
More file actions
573 lines (474 loc) · 17.4 KB
/
LLM.txt
File metadata and controls
573 lines (474 loc) · 17.4 KB
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# HTMX Generic Component Registry - LLM Context
## Project Overview
HxComponents is a type-safe, framework-agnostic Go library for building dynamic HTMX components with minimal boilerplate. It uses Go 1.23+ generics to provide compile-time type safety and automatic form parsing.
## Core Architecture
### Component Registry Pattern
The library provides a centralized registry that:
1. Stores component type information and render functions
2. Handles HTTP requests (GET and POST)
3. Automatically parses form data into typed structs
4. Manages HTMX request/response headers via optional interfaces
5. Renders components using templ templates
### Key Design Decisions
1. **Framework-Agnostic**: Uses `http.HandlerFunc` to work with any Go router
2. **Generic-Based**: Type-safe component registration using Go generics
3. **Interface-Driven**: Optional HTMX headers via interface implementation
4. **Zero Configuration**: Sensible defaults with customization options
## File Structure
```
/components/
registry.go - Core registry implementation with panic recovery
processor.go - Processor interface for business logic
initializer.go - Initializer interface for component setup (NEW)
validator.go - Validator interface for form validation (NEW)
event_handler.go - Event handler interfaces (BeforeEvent, AfterEvent)
request_headers.go - HTMX request header interfaces
response_headers.go - HTMX response header interfaces
headers.go - Header application logic
errors.go - Structured error types (NEW)
error.templ - Default error template
registry_test.go - Comprehensive tests
registry_event_test.go - Event handler tests
/examples/
main.go - Example application
ROUTER_EXAMPLES.md - Router integration examples
/search/ - Search component example
/login/ - Login component example
/profile/ - Profile component example
/counter/ - Counter component with events
/todolist/ - TodoList component with full lifecycle
/card/ - Card component with Constructor pattern (NEW)
/pages/ - Page templates
/testutil/ - Test utilities (Playwright helpers)
```
## Core Components
### 1. Registry (`components/registry.go`)
**Key Types:**
```go
type Registry struct {
mu sync.RWMutex
components map[string]componentEntry
errorHandler ErrorHandler
debugMode bool
}
type componentEntry struct {
structType reflect.Type
}
type ErrorHandler func(w http.ResponseWriter, req *http.Request, title string, message string, code int)
type ComponentInfo struct {
Name string
StructType string
}
```
**Key Methods:**
- `NewRegistry()` - Creates new registry with default error handler
- `Register[T templ.Component](registry, name)` - Registers a component (component must implement templ.Component)
- `Handler(w, req)` - Extracts component name from URL and renders (wildcard routing) with validation
- `HandlerFor(componentName)` - Returns http.HandlerFunc for specific component with panic recovery
- `SetErrorHandler(handler)` - Customizes error rendering
- `EnableDebugMode()` / `DisableDebugMode()` - Toggle debug headers (NEW)
- `ListComponents()` - Get all registered component names (NEW)
- `IsRegistered(name)` - Check if component exists (NEW)
- `GetComponentInfo(name)` - Get component metadata (NEW)
### 2. Initializer Interface (`components/initializer.go`) - NEW
```go
type Initializer interface {
Init(ctx context.Context) error
}
```
Components implement this to perform initialization logic. Called after form decoding but before validation/events/processing.
**Use cases:**
- Set default values
- Load data from database
- Initialize computed fields
- Constructor pattern for templ templates
**Example Constructor Pattern:**
```go
func NewCard(ctx context.Context, title string, count int) *CardComponent {
c := &CardComponent{Title: title, Count: count}
_ = c.Init(ctx) // Initialize computed fields
return c
}
func (c *CardComponent) Init(ctx context.Context) error {
if c.Title == "" {
c.Title = "Untitled"
}
c.Description = fmt.Sprintf("Card with %d items", c.Count)
return nil
}
```
Usage in templ: `@NewCard(ctx, "My Card", 42)`
### 3. Validator Interface (`components/validator.go`) - NEW
```go
type Validator interface {
Validate(ctx context.Context) []ValidationError
}
type ValidationError struct {
Field string
Message string
}
```
Components implement this for field-level validation. Called after Init but before events.
**Use cases:**
- Form field validation
- Business rule validation
- Return validation errors for rendering
### 4. Event Handler Interfaces (`components/event_handler.go`)
```go
type BeforeEventHandler interface {
BeforeEvent(ctx context.Context, eventName string) error
}
type AfterEventHandler interface {
AfterEvent(ctx context.Context, eventName string) error
}
```
Components can implement hooks that run before/after event handlers.
**Event Handler Methods:**
- Must have signature: `On{EventName}(ctx context.Context) error`
- Example: `OnIncrement(ctx)`, `OnAddItem(ctx)`, `OnDelete(ctx)`
- Triggered by `hxc-event` form parameter
- Context provides request-scoped values and cancellation
### 5. Processor Interface (`components/processor.go`)
```go
type Processor interface {
Process(ctx context.Context) error
}
```
Components implement this to run business logic after events but before rendering.
**Use cases:**
- Final data transformations
- Database save operations
- Setting response headers based on processing results
### 6. Structured Error Types (`components/errors.go`) - NEW
```go
type ComponentError struct {
ComponentName string
Operation string // "parse", "decode", "process", "render", "event"
Err error
StatusCode int
}
type ErrComponentNotFound struct {
ComponentName string
}
type ErrEventNotFound struct {
ComponentName string
EventName string
}
type ErrInvalidComponentName struct {
ComponentName string
Reason string
}
```
Structured errors for better error handling and debugging.
### 7. HTMX Request Headers (`components/request_headers.go`)
Optional interfaces components can implement to capture HTMX request headers:
```go
type HxBoosted interface { SetHxBoosted(bool) }
type HxRequest interface { SetHxRequest(bool) }
type HxCurrentURL interface { SetHxCurrentURL(string) }
type HxPrompt interface { SetHxPrompt(string) }
type HxTarget interface { SetHxTarget(string) }
type HxTrigger interface { SetHxTrigger(string) }
type HxTriggerName interface { SetHxTriggerName(string) }
type HttpMethod interface { SetHttpMethod(string) }
```
### 8. HTMX Response Headers (`components/response_headers.go`)
Optional interfaces components can implement to set HTMX response headers:
```go
type HxLocationResponse interface { GetHxLocation() string }
type HxPushUrlResponse interface { GetHxPushUrl() string }
type HxRedirectResponse interface { GetHxRedirect() string }
type HxRefreshResponse interface { GetHxRefresh() bool }
type HxReplaceUrlResponse interface { GetHxReplaceUrl() string }
type HxReswapResponse interface { GetHxReswap() string }
type HxRetargetResponse interface { GetHxRetarget() string }
type HxReselectResponse interface { GetHxReselect() string }
type HxTriggerResponse interface { GetHxTrigger() string }
type HxTriggerAfterSettleResponse interface { GetHxTriggerAfterSettle() string }
type HxTriggerAfterSwapResponse interface { GetHxTriggerAfterSwap() string }
```
## Request Flow (Updated)
```
1. HTTP Request (GET or POST) arrives
2. Registry.HandlerFor(componentName) handler is invoked with panic recovery
3. Check HTTP method (only GET and POST allowed)
4. Validate component name (alphanumeric, dash, underscore only)
5. Look up component in registry
6. Parse form data (POST: req.PostForm, GET: req.Form)
7. Create instance of component struct
8. Decode form data into struct using go-playground/form (custom decoder supported)
9. Apply HTMX request headers (if interfaces implemented)
10. Call Init(ctx) method (if Initializer interface implemented) - NEW
11. Call Validate(ctx) method (if Validator interface implemented) - NEW
12. Handle events if hxc-event parameter present:
a. Call BeforeEvent(ctx, eventName) if implemented
b. Call On{EventName}(ctx) event handler - REQUIRES CONTEXT NOW
c. Call AfterEvent(ctx, eventName) if implemented
13. Call Process(ctx) method (if Processor interface implemented)
14. Apply HTMX response headers (if interfaces implemented)
15. Add debug headers if debug mode enabled
16. Render component using templ
17. Return HTML response
Note: Context (ctx) is now passed to all lifecycle methods for:
- Database queries
- Request cancellation
- Request-scoped values
- Timeout handling
```
## Example Component (Updated)
```go
// Component struct with form tags
type LoginComponent struct {
Username string `form:"username"`
Password string `form:"password"`
RedirectTo string `json:"-"`
Error string `json:"-"`
Errors []components.ValidationError `json:"-"`
}
// Implement Validator interface (NEW)
func (c *LoginComponent) Validate(ctx context.Context) []components.ValidationError {
var errs []components.ValidationError
if c.Username == "" {
errs = append(errs, components.ValidationError{
Field: "username", Message: "Username is required"})
}
if len(c.Password) < 8 {
errs = append(errs, components.ValidationError{
Field: "password", Message: "Password must be at least 8 characters"})
}
c.Errors = errs
return errs
}
// Implement Processor interface (context parameter now required)
func (c *LoginComponent) Process(ctx context.Context) error {
if c.Username == "demo" && c.Password == "password" {
c.RedirectTo = "/dashboard"
return nil
}
c.Error = "Invalid credentials"
return nil
}
// Implement response header interface
func (c *LoginComponent) GetHxRedirect() string {
return c.RedirectTo
}
// Implement templ.Component
func (c *LoginComponent) Render(ctx context.Context, w io.Writer) error {
return Login(*c).Render(ctx, w)
}
// Templ template (in login.templ)
templ Login(data LoginComponent) {
if data.Error != "" {
<div class="error">{data.Error}</div>
}
if len(data.Errors) > 0 {
<ul class="errors">
for _, err := range data.Errors {
<li>{err.Field}: {err.Message}</li>
}
</ul>
}
<form hx-post="/component/login" hx-target="#result">
<input type="text" name="username" />
<input type="password" name="password" />
<button>Login</button>
</form>
}
```
## Router Integration
### chi Router (Wildcard Pattern - Recommended)
```go
router.Get("/component/*", registry.Handler)
router.Post("/component/*", registry.Handler)
```
The `Handler` method extracts component name from URL path. Example: `/component/login` → component name: `login`
### chi Router (Specific URLs)
```go
router.Get("/login", registry.HandlerFor("login"))
router.Post("/login", registry.HandlerFor("login"))
```
### gorilla/mux (Wildcard Pattern)
```go
router.PathPrefix("/component/").HandlerFunc(registry.Handler).Methods("GET", "POST")
```
### gorilla/mux (Specific URLs)
```go
router.HandleFunc("/login", registry.HandlerFor("login")).Methods("GET", "POST")
```
### net/http (Wildcard Pattern)
```go
http.HandleFunc("/component/", registry.Handler)
```
### net/http (Specific URLs)
```go
http.HandleFunc("/login", registry.HandlerFor("login"))
```
## Testing Strategy
The test suite covers:
1. Basic component registration and rendering
2. Form data parsing (simple and array fields)
3. GET vs POST request handling
4. Processor interface execution
5. HTMX redirect headers
6. Error handling
## Dependencies
- `github.com/a-h/templ` - Type-safe Go templating
- `github.com/go-playground/form/v4` - Form decoding
- `log/slog` - Structured logging
**No router dependency** - Works with any Go HTTP router (chi, gorilla/mux, standard library, etc.)
## Key Design Patterns
1. **Generic Registration**: `Register[T any](registry, name, renderFunc)` maintains type safety
2. **Interface Segregation**: Small, focused interfaces for optional features
3. **Dependency Injection**: ErrorHandler can be customized
4. **Reflection**: Used internally for type-safe form decoding
5. **Template Method**: Process() hook allows custom logic insertion
## Common Patterns
### Login with Redirect
```go
type LoginComponent struct {
Username string
RedirectTo string
}
func (c *LoginComponent) Process(ctx context.Context) error {
if authenticate(ctx, c.Username) {
c.RedirectTo = "/dashboard"
}
return nil
}
func (c *LoginComponent) GetHxRedirect() string {
return c.RedirectTo
}
```
### Form Validation with Validator Interface
```go
type FormComponent struct {
Email string `form:"email"`
Errors []components.ValidationError `json:"-"`
}
func (c *FormComponent) Validate(ctx context.Context) []components.ValidationError {
var errs []components.ValidationError
if !isValidEmail(c.Email) {
errs = append(errs, components.ValidationError{
Field: "email", Message: "Invalid email address"})
}
c.Errors = errs
return errs
}
```
### Constructor Pattern with Init
```go
type DashboardComponent struct {
UserID int `form:"user_id"`
Username string `json:"-"` // Loaded in Init
Stats Stats `json:"-"` // Computed in Init
}
func NewDashboard(ctx context.Context, userID int) *DashboardComponent {
d := &DashboardComponent{UserID: userID}
_ = d.Init(ctx)
return d
}
func (d *DashboardComponent) Init(ctx context.Context) error {
user, err := db.GetUser(ctx, d.UserID)
if err != nil {
return err
}
d.Username = user.Name
d.Stats = computeStats(ctx, d.UserID)
return nil
}
```
### GET vs POST Behavior
```go
type SearchComponent struct {
Query string
Method string
}
func (c *SearchComponent) SetHttpMethod(m string) {
c.Method = m
}
func (c *SearchComponent) Process(ctx context.Context) error {
if c.Method == "GET" {
// Load default results
} else {
// Process search query with context
results, err := search(ctx, c.Query)
if err != nil {
return err
}
c.Results = results
}
return nil
}
```
### Event Handlers with Context
```go
type TodoComponent struct {
Items []TodoItem `form:"items"`
}
func (t *TodoComponent) OnAddItem(ctx context.Context) error {
// Use context for database operations
item, err := db.CreateTodoItem(ctx, t.NewItemText)
if err != nil {
return err
}
t.Items = append(t.Items, item)
return nil
}
func (t *TodoComponent) BeforeEvent(ctx context.Context, eventName string) error {
// Check authentication before any event
if !isAuthenticated(ctx) {
return errors.New("unauthorized")
}
return nil
}
```
## Error Handling
1. **Default Handler**: Uses `ErrorComponent` templ template
2. **Custom Handler**: Set via `SetErrorHandler()`
3. **Structured Error Types**:
- `ComponentError` - Wraps errors with context (component name, operation, status code)
- `ErrComponentNotFound` - Component not registered
- `ErrEventNotFound` - Event handler method not found
- `ErrInvalidComponentName` - Invalid component name (security)
4. **HTTP Status Codes**:
- Method Not Allowed (405)
- Component Not Found (404)
- Invalid Component Name (400)
- Form Parse Error (400)
- Form Decode Error (400)
- Validation Error (400)
- Init Error (500)
- Event Error (500)
- Process Error (500)
- Render Error (500)
5. **Panic Recovery**: HandlerFor includes panic recovery with stack trace logging
## Logging
Uses `log/slog` with structured logging:
- **Debug**: Component rendering lifecycle
- **Warn**: Method not allowed, component not found
- **Error**: Parse/decode/process/render errors
## Best Practices
1. **Use json:"-" tag** for internal fields that shouldn't be serialized
2. **Use Init() for defaults** - Set default values and load data in Init, not in constructor
3. **Use Validate() for validation** - Return ValidationErrors instead of checking in Process
4. **Use context parameter** - All lifecycle methods now receive context for database access and cancellation
5. **Implement Process(ctx)** for business logic after validation
6. **Return nil from Process(ctx)** for validation errors (use Validator interface instead)
7. **Return error from Process(ctx)** only for unexpected failures
8. **Use Constructor pattern** - Create NewComponent(ctx, params) for easy template usage
9. **Use HandlerFor()** for framework-agnostic code
10. **Component name validation** - Only alphanumeric, dash, underscore (max 100 chars)
11. **Register GET and POST** for best HTMX compatibility
12. **Event handlers require context** - All On{Event} methods must accept context.Context parameter
## Limitations
1. Only GET and POST methods supported
2. Mount() method requires chi router
3. Uses reflection internally (slight performance overhead)
4. Form decoder doesn't support nested structs by default
## Future Enhancements (Not Implemented)
- Middleware support (use router middleware for cross-cutting concerns)
- Built-in validation helpers (currently manual via Validator interface)
- WebSocket support
- Server-sent events
- Nested struct support in form decoder
- Custom form decoders per component (currently global decoder only)