core/templates/bn/validation.go
Alex Dunmow 868df2d761 feat: WO-PS-011 SDK templates/bn shared components
Head, engagement, toolbar templ components and validation helpers
for use by template plugins.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-01 09:17:55 +08:00

51 lines
1.6 KiB
Go

package bn
import (
"context"
"io"
"github.com/a-h/templ"
)
// validationContextKey is the key used to store validation tracking in context.
type validationContextKey struct{}
// ValidationTracker tracks which bn functions are called during template rendering.
// Used during template registration to validate templates include required calls.
type ValidationTracker struct {
HeadCalled bool
BodyEndCalled bool
}
// NewValidationContext creates a context with validation tracking enabled.
// Use GetValidationTracker after rendering to check which functions were called.
func NewValidationContext(ctx context.Context) (context.Context, *ValidationTracker) {
tracker := &ValidationTracker{}
return context.WithValue(ctx, validationContextKey{}, tracker), tracker
}
// GetValidationTracker retrieves the validation tracker from context, if any.
func GetValidationTracker(ctx context.Context) *ValidationTracker {
if tracker, ok := ctx.Value(validationContextKey{}).(*ValidationTracker); ok {
return tracker
}
return nil
}
// recordValidationCall records that a bn function was called during rendering.
// Returns an empty component (renders nothing) but has the side effect of tracking the call.
func recordValidationCall(ctx context.Context, fnName string) templ.Component {
if tracker := GetValidationTracker(ctx); tracker != nil {
switch fnName {
case "Head":
tracker.HeadCalled = true
case "BodyEnd":
tracker.BodyEndCalled = true
}
}
// Return empty component - renders nothing
return templ.ComponentFunc(func(ctx context.Context, w io.Writer) error {
return nil
})
}