Documentation
¶
Overview ¶
templ: version: v0.3.924
templ: version: v0.3.924
Index ¶
- func AllowBlocking(ctx context.Context) context.Context
- func Any(v any) templ.Component
- func Attributes(a []Attr) templ.Component
- func Call(ctx context.Context, conf CallConf) (func(), bool)
- func Components(content ...templ.Component) templ.Component
- func E(f func(context.Context) templ.Component) templ.Component
- func F(f Fragment) templ.Component
- func Go(f func(context.Context)) templ.Component
- func Head[M any](b Beam[M], cast func(M) HeadData) templ.Component
- func Imports(entries ...Import) templ.Component
- func Include() templ.Component
- func Inject[T any](key any, beam Beam[T]) templ.Component
- func InstanceEnd(ctx context.Context)
- func InstanceId(ctx context.Context) string
- func InstanceLoad(ctx context.Context, key any) any
- func InstanceRemove(ctx context.Context, key any)
- func InstanceSave(ctx context.Context, key any, value any) bool
- func LocationAssign(ctx context.Context, model any) error
- func LocationAssignRaw(ctx context.Context, url string)
- func LocationReload(ctx context.Context)
- func LocationReplace(ctx context.Context, model any) error
- func LocationReplaceRaw(ctx context.Context, url string)
- func RandId() string
- func Run(f func(context.Context)) templ.Component
- func Script() templ.Component
- func ScriptDisposable() templ.Component
- func ScriptPrivate() templ.Component
- func SessionEnd(ctx context.Context)
- func SessionExpire(ctx context.Context, d time.Duration)
- func SessionId(ctx context.Context) string
- func SessionLoad(ctx context.Context, key any) any
- func SessionRemove(ctx context.Context, key any)
- func SessionSave(ctx context.Context, key any, value any) bool
- func Style() templ.Component
- func StyleDisposable() templ.Component
- func StylePrivate() templ.Component
- func Sub[T any](beam Beam[T], render func(T) templ.Component) templ.Component
- func Text(value any) templ.Component
- type ABlur
- type AChange
- type AClick
- type AData
- type ADataMap
- type ADyn
- type AFileHref
- type AFocus
- type AFocusIn
- type AFocusOut
- type AGotPointerCapture
- type AHook
- type AHref
- type AInput
- type AKeyDown
- type AKeyUp
- type ALostPointerCapture
- type APointerCancel
- type APointerDown
- type APointerEnter
- type APointerLeave
- type APointerMove
- type APointerOut
- type APointerOver
- type APointerUp
- type ARawFileHref
- type ARawHook
- type ARawSrc
- type ARawSubmit
- type ASrc
- type ASubmit
- type Active
- type After
- type Attr
- type AttrIndicator
- type AttrInit
- type Attrs
- type Beam
- type BlockingScope
- type CSP
- type CallConf
- type CallOnError
- type ChangeEvent
- type ClassIndicator
- type ClassRemoveIndicator
- type ContentIndicator
- type DebounceScope
- type Door
- type ESConf
- type ESOptions
- type FocusEvent
- type Fragment
- type FrameScope
- type HeadData
- type HrefActiveMatch
- type Import
- type ImportModule
- type ImportModuleBundle
- type ImportModuleBundleFS
- type ImportModuleBytes
- type ImportModuleExternal
- type ImportModuleHosted
- type ImportModuleRaw
- type ImportModuleRawBytes
- type ImportStyle
- type ImportStyleBytes
- type ImportStyleExternal
- type ImportStyleHosted
- type IndicateOnError
- type Indicator
- func IndicatorAttr(attr string, value string) []Indicator
- func IndicatorAttrQuery(query string, attr string, value string) []Indicator
- func IndicatorAttrQueryParent(query string, attr string, value string) []Indicator
- func IndicatorClass(class string) []Indicator
- func IndicatorClassQuery(query string, class string) []Indicator
- func IndicatorClassQueryParent(query string, class string) []Indicator
- func IndicatorClassRemove(class string) []Indicator
- func IndicatorClassRemoveQuery(query string, class string) []Indicator
- func IndicatorClassRemoveQueryParent(query string, class string) []Indicator
- func IndicatorContent(content string) []Indicator
- func IndicatorContentQuery(query string, content string) []Indicator
- func IndicatorContentQueryParent(query string, content string) []Indicator
- type InputEvent
- type JSX
- type KeyboardEvent
- type LatestScope
- type Location
- type Mod
- func EnableCSP(csp CSP) Mod
- func ServeDir(prefix string, path string) Mod
- func ServeFS(prefix string, fs fs.FS) Mod
- func ServeFallback(handler http.Handler) Mod
- func ServeFile(path string, localPath string) Mod
- func ServePage[M any](handler func(p PageRouter[M], r RPage[M]) PageRoute) Mod
- func SetESConf(p ESConf) Mod
- func SetErrorPage(page func(message string) templ.Component) Mod
- func SetGoroutineLimitPerInstance(n int) Mod
- func SetSessionHooks(create func(id string), delete func(id string)) Mod
- func SetSystemConf(conf SystemConf) Mod
- type Node
- type OnError
- type Page
- type PageRoute
- type PageRouter
- type ParsedForm
- type PathMatcher
- type PointerEvent
- type QueryMatcher
- type R
- type RAfter
- type RCall
- type REvent
- type RForm
- type RHook
- type RPage
- type RRawForm
- type RRawHook
- type Router
- type Scope
- type ScopeSet
- type Selector
- type SerialScope
- type SourceBeam
- type SystemConf
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Attributes ¶
func Call ¶
Call sends a backend-initiated JavaScript function call to the frontend.
The call is dispatched as soon as the frontend connection is ready. It serializes the Arg field of CallConf to JSON and sends it to a frontend function registered with the given Name. Optionally, the backend can handle a response via the Trigger field, or react to cancellation via the Cancel field.
If the component or context is no longer valid (e.g., unmounted), Cancel is called automatically.
Parameters:
- ctx: the current rendering or lifecycle context.
- conf: the configuration specifying the function name, argument, and optional handlers.
Returns:
- a function to cancel the pending call (usually ignored).
- ok: false if the call couldn't be registered or marshaling failed.
Example:
// Go (backend): d.Call(ctx, d.CallConf{ Name: "alert", Arg: "Hello", }) // JavaScript (frontend): $doors.Script() { <script> $d.on("alert", (message) => alert(message)) </script> }
Notes:
- The Name must match the identifier registered via `$D.on(...)` in frontend JavaScript.
- The Arg is serialized to JSON and passed as the first argument to the JS handler.
- Use `document` instead of `document.currentScript` to register globally.
- To handle a frontend response, set the Trigger field in CallConf
func E ¶
E evaluates the provided function at render time and returns the resulting templ.Component.
This is useful when rendering logic is complex or better expressed in plain Go code, rather than templ syntax. The function is called with the current render context.
Example:
@doors.E(func(ctx context.Context) templ.Component { user, err := db.Get(id) if err != nil { return RenderError(err) } return RenderUser(user) })
Parameters:
- f: a function that returns a templ.Component, given the current render context
Returns:
- A templ.Component produced by evaluating f during rendering
func F ¶
F renders a Fragment as a templ.Component.
This helper wraps a Fragment and returns a valid templ.Component, enabling Fragments to be used inside other templ components.
Example:
templ Demo() { @doors.F(&Counter{}) }
func Go ¶
Go starts a goroutine at render time using a blocking-safe context tied to the component's lifecycle.
The goroutine runs only if the component is rendered. The context is canceled when the component is unmounted, allowing for proper cleanup. You must explicitly listen to ctx.Done() to stop work.
The context allows safe blocking operations, making it safe to use with X* operations (e.g., XUpdate, XRemove).
Example:
@doors.Go(func(ctx context.Context) { for { select { case <-time.After(time.Second): door.Update(ctx, currentTime()) case <-ctx.Done(): return } } })
Parameters:
- f: a function to run in a goroutine, scoped to the component's render lifecycle
Returns:
- A non-visual templ.Component that starts the goroutine when rendered
func Imports ¶
Imports generates the HTML import map and resource loading tags for the specified imports. This component should be placed in the HTML head section and can only be used once per page. It processes all import entries, builds an ES modules import map, and generates the necessary script and link tags for loading resources.
The function handles:
- ES module import map generation
- JavaScript and CSS resource processing
- Content Security Policy header updates
- Automatic resource caching and optimization
Import entries are processed in order, and any errors are logged while continuing with the remaining entries.
func Include ¶
Include returns a component that includes the framework's main client-side script and styles. This should be placed in the HTML head section and is required for the framework to function.
func Inject ¶
Inject creates a reactive component that injects Beam values into the context for child components.
It subscribes to the Beam and re-renders its children whenever the value changes, making the current value available to child components via Extract().
This enables passing reactive values down the component tree without explicit prop drilling.
Example:
@Inject("user", userBeam) { @UserProfile() // Can use ctx.Value("user").(User) to get current user }
func InstanceEnd ¶
InstanceEnd terminates the current instance while keeping the session and other instances active. This closes the connection for the specific browser tab or window.
Use this when you need to close a specific page without affecting the entire session. The session continues with remaining instances until they are all closed or the session expires.
Example:
// Close current tab after completion doors.InstanceEnd(ctx)
func InstanceId ¶
InstanceId returns the unique identifier for the current instance. Each instance represents a single browser tab or window connection.
The ID is a cryptographically secure random string that uniquely identifies this instance within the application. Useful for logging, debugging, or tracking specific client connections.
Example:
instanceId := doors.InstanceId(ctx) log.Printf("Processing request for instance: %s", instanceId)
func InstanceLoad ¶
InstanceLoad retrieves a value from the instance-scoped storage by its key. Returns nil if the key doesn't exist in the storage.
The returned value must be type-asserted to its original type. The storage is isolated to the current instance and not shared with other instances.
Example:
// Load user preferences for this specific tab if val := doors.InstanceLoad(ctx, "prefs"); val != nil { prefs := val.(Preferences) applyTheme(prefs.Theme) }
func InstanceRemove ¶
InstanceRemove deletes a key-value pair from the instance-scoped storage. If the key does not exist, the method performs no action. The storage is isolated to the current instance.
Example:
// Remove user preferences for this specific tab doors.InstanceRemove(ctx, "prefs")
func InstanceSave ¶
InstanceSave stores a key-value pair in the instance-scoped storage. The storage persists for the instance lifetime and is isolated to the current instance (browser tab / page). Each instance has its own separate storage.
Both key and value can be of any type. The storage is thread-safe and can be accessed concurrently from different goroutines within the same instance.
Returns true if the value was successfully saved, false otherwise.
Example:
// Store user preferences for this specific tab type Preferences struct { Theme string Language string } saved := doors.InstanceSave(ctx, "prefs", Preferences{ Theme: "dark", Language: "en", })
func LocationAssign ¶
LocationAssign navigates the browser to a URL generated from the provided model by calling location.assign(url) in JavaScript. This creates a new history entry, allowing the user to navigate back.
The model should be a struct with a registered path adapter. Navigation between different path model types triggers a full page reload and new instance creation, while navigation within the same model type updates the current instance reactively.
Example:
// Navigate to item page err := doors.LocationAssign(ctx, CatalogPath{ IsItem: true, CatId: "electronics", ItemId: 123, })
Returns an error if the model cannot be encoded into a location.
func LocationAssignRaw ¶
LocationAssignRaw navigates the browser to the specified URL by calling location.assign(url) in JavaScript. This creates a new entry in the browser's history stack, allowing the user to navigate back.
The url parameter should be a complete URL string. The Origin field is set to false, indicating this is a raw URL navigation rather than model-based routing. Use this for external URLs or paths that don't correspond to path models.
Example:
// Navigate to external site doors.LocationAssignRaw(ctx, "https://example.com")
func LocationReload ¶
LocationReload triggers a browser location reload for the current instance. This executes location.reload() in JavaScript through the framework's call mechanism.
The reload is performed asynchronously, causing the browser to reload the current page and create a new instance.
Example:
func (h *handler) logout() doors.Attr { return doors.AClick{ On: func(ctx context.Context, r doors.REvent[doors.PointerEvent]) bool { // Clear session data... doors.LocationReload(ctx) return true }, } }
func LocationReplace ¶
LocationReplace replaces the current browser location with a URL generated from the provided model. This calls location.replace(url) in JavaScript and does not create a new history entry.
The model should be a struct with a registered path adapter. The adapter encodes the model into a URL path according to struct tags defined in the path model. The Origin field is set to true for model-based routing.
Example:
type CatalogPath struct { IsCat bool `path:"/catalog/:CatId"` CatId string } // Replace current location with category page err := doors.LocationReplace(ctx, CatalogPath{ IsCat: true, CatId: "electronics", })
Returns an error if the model cannot be encoded into a location.
func LocationReplaceRaw ¶
LocationReplaceRaw replaces the current browser location with the specified URL by calling location.replace(url) in JavaScript. This does not create a new history entry, preventing the user from navigating back to the current page.
The url parameter should be a complete URL string. Use this for redirects where you don't want the current page in the browser's history.
func RandId ¶
func RandId() string
RandId generates a cryptographically secure random identifier string. The generated ID is URL-safe and suitable for use as session IDs, instance IDs, tokens, or any other unique identifiers. Case sensative.
Example:
// Generate unique token token := doors.RandId() // Use for session creation session := Session{ ID: doors.RandId(), UserID: user.ID, Created: time.Now(), }
func Script ¶
Script converts inline script content to an external resource. The JavaScript/TypeScript content is processed by esbuild and served as an external resource with a src attribute. This is the default mode - the resource is publicly accessible as a static asset.
The script content is automatically wrapped in an anonymous async function to support await and protect the global context. A special $d variable is provided to access frontend framework functions.
The content must be wrapped in <script> tags. TypeScript is supported by adding type="text/typescript" attribute.
Example:
@Script() { <script> console.log("Hello from [not] inline script!"); // $d provides access to framework functions // await is supported due to async wrapper await $d.hook("hello","world"); </script> }
Or with TypeScript:
@Script() { <script type="text/typescript"> const message: string = "TypeScript works!"; console.log(message); </script> }
func ScriptDisposable ¶
ScriptDisposable converts inline script content to an external resource within the current context scope without caching. The script is processed on every render and served with a src attribute, but not exposed as a static resource. The script content is wrapped in an anonymous async function and provides the $d variable. The content must be wrapped in <script> tags.
func ScriptPrivate ¶
ScriptPrivate converts inline script content to an external resource that is served securely within the current context scope. The script is processed and served with a src attribute, but not exposed as a publicly accessible static asset. The script content is wrapped in an anonymous async function and provides the $d variable. The content must be wrapped in <script> tags.
func SessionEnd ¶
SessionEnd immediately terminates the current session and all its associated instances. This disconnects all active connections and cleans up server-side session resources.
This must be called during logout to ensure no authorized pages remain active after the user logs out. Each session can contain multiple instances (browser tabs/windows), and this ensures they are all terminated.
Example:
func (h *handler) logout() doors.Attr { return doors.AClick{ On: func(ctx context.Context, r doors.REvent[doors.PointerEvent]) bool { // Clear auth cookie r.SetCookie(&http.Cookie{ Name: "session", MaxAge: -1, }) // Terminate all instances doors.SessionEnd(ctx) return true }, } }
func SessionExpire ¶
SessionExpire sets the expiration duration for the current session. After the specified duration without activity, the session will be automatically terminated along with all its instances.
Setting d to 0 disables automatic expiration. If the session has no active instances when expiration is disabled, it will be immediately terminated.
This is commonly used to align the framework's session lifetime with your application's authentication session to ensure authorized pages don't outlive the authentication.
Example:
// In login handler const sessionDuration = 24 * time.Hour session := createAuthSession(user, sessionDuration) doors.SessionExpire(ctx, sessionDuration)
func SessionId ¶
SessionId returns the unique identifier for the current session. A session represents a browser session and may contain multiple instances (tabs/windows) sharing the same session state.
The ID is a cryptographically secure random string stored in a session cookie. All instances within the same browser share this session ID.
Example:
sessionId := doors.SessionId(ctx) analytics.Track("page_view", sessionId)
func SessionLoad ¶
SessionLoad retrieves a value from the session-scoped storage by its key. Returns nil if the key doesn't exist in the storage.
The returned value must be type-asserted to its original type. The storage is shared across all instances within the same session.
Example:
// Load user preferences if val := doors.SessionLoad(ctx, "prefs"); val != nil { prefs := val.(Preferences) applyTheme(prefs.Theme) }
func SessionRemove ¶
SessionRemove deletes a key-value pair from the session-scoped storage. If the key does not exist, the method performs no action. The storage is shared across all instances within the same session.
Example:
// Remove user preferences doors.SessionRemove(ctx, "prefs")
func SessionSave ¶
SessionSave stores a key-value pair in the session-scoped storage. The storage persists for the session lifetime and is shared across all instances (browser tabs) within the same session.
Both key and value can be of any type. The storage is thread-safe and can be accessed concurrently from different instances or goroutines.
Returns true if the value was successfully saved, false otherwise.
Example:
// Store user preferences type Preferences struct { Theme string Language string } saved := doors.SessionSave(ctx, "prefs", Preferences{ Theme: "dark", Language: "en", })
func Style ¶
Style converts inline CSS content to an external resource. The CSS is minified and served as an external resource with an href attribute. This is the default mode - the resource is publicly accessible as a static asset.
The content must be wrapped in <style> tags.
Example:
@Style() { <style> .my-class { color: blue; font-size: 14px; } </style> }
func StyleDisposable ¶
StyleDisposable converts inline CSS content to an external resource within the current context scope without caching. The CSS is processed on every render and served with an href attribute, but not exposed as a static resource. The content must be wrapped in <style> tags.
func StylePrivate ¶
StylePrivate converts inline CSS content to an external resource that is served securely within the current context scope. The CSS is processed and served with an href attribute, but not exposed as a publicly accessible static asset. The content must be wrapped in <style> tags.
func Sub ¶
Sub creates a reactive component that automatically updates when a Beam value changes.
It subscribes to the Beam and re-renders the inner content whenever the value changes. The render function is called with the current Beam value and must return a templ.Component.
This is the preferred way to bind Beam values into the DOM in a declarative and reactive manner.
Example:
templ display(value int) { <span>{strconv.Itoa(value)}</span> } templ demo(beam Beam[int]) { @doors.Sub(beam, func(v int) templ.Component { return display(v) }) }
Parameters:
- beam: the reactive Beam to observe
- render: a function that maps the current Beam value to a templ.Component
Returns:
- A templ.Component that updates reactively as the Beam value changes
Types ¶
type ABlur ¶
type ABlur struct { // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate the hook is running (e.g., spinner, class, content). Optional. Indicator []Indicator // On is the required backend handler that runs when the event is triggered. // // The function receives a typed EventRequest[FocusEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[FocusEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
ABlur is an attribute struct used with A(ctx, ...) to handle 'blur' events via backend hooks.
type AChange ¶
type AChange struct { // Mode determines how this hook is scheduled (e.g., blocking, debounce). // See ModeDefault, ModeBlock, ModeFrame, etc. Scope []Scope // Indicator specifies how to visually indicate the hook is running // (e.g., by applying a class, attribute, or replacing content). Optional. Indicator []Indicator // On is the required backend handler for the change event. // // It receives a typed EventRequest[ChangeEvent] and should return true // when the hook is complete and can be removed. On func(context.Context, REvent[ChangeEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
AChange is an attribute struct used with A(ctx, ...) to handle 'change' events via backend hooks.
It binds to inputs, selects, or other form elements and triggers the On handler when the value is committed (typically when focus leaves or enter is pressed).
This is useful for handling committed input changes (unlike 'input', which fires continuously).
Example:
<input type="text" { A(ctx, AChange{ On: func(ctx context.Context, ev EventRequest[ChangeEvent]) bool { // handle changed input value return true }, })... }>
type AClick ¶
type AClick struct { // StopPropagation, if true, stops the event from bubbling up the DOM. StopPropagation bool // PreventDefault, if true, prevents the browser's default action for the event. PreventDefault bool // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate that the hook is running. Indicator []Indicator // On is the required backend handler for the click event. // It receives a typed REvent[PointerEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[PointerEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
AClick is an attribute struct used with A(ctx, ...) to handle click or pointer events via backend hooks.
type ADyn ¶
type AFocus ¶
type AFocus struct { // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate the hook is running (e.g., spinner, class, content). Optional. Indicator []Indicator // On is the required backend handler that runs when the event is triggered. // // The function receives a typed EventRequest[FocusEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[FocusEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
AFocus is an attribute struct used with A(ctx, ...) to handle 'focus' events via backend hooks.
type AFocusIn ¶
type AFocusIn struct { // StopPropagation, if true, stops the event from bubbling up the DOM. StopPropagation bool // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate the hook is running (e.g., spinner, class, content). Optional. Indicator []Indicator // On is the required backend handler that runs when the event is triggered. // // The function receives a typed EventRequest[FocusEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[FocusEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
AFocusIn is an attribute struct used with A(ctx, ...) to handle 'focusin' events via backend hooks.
type AFocusOut ¶
type AFocusOut struct { // StopPropagation, if true, stops the event from bubbling up the DOM. StopPropagation bool // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate the hook is running (e.g., spinner, class, content). Optional. Indicator []Indicator // On is the required backend handler that runs when the event is triggered. // // The function receives a typed EventRequest[FocusEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[FocusEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
AFocusOut is an attribute struct used with A(ctx, ...) to handle 'focusout' events via backend hooks.
type AGotPointerCapture ¶
type AGotPointerCapture pointerEventHook
AGotPointerCapture is an attribute struct used with A(ctx, ...) to handle 'gotpointercapture' events via backend hooks.
func (AGotPointerCapture) Attr ¶
func (c AGotPointerCapture) Attr() AttrInit
type AHook ¶
type AHook[I any, O any] struct { On func(ctx context.Context, r RHook[I]) (O, bool) Name string Scope []Scope Indicator []Indicator }
type AHref ¶
type AHref struct { Active Active StopPropagation bool Model any Indicator []Indicator OnError []OnError }
type AInput ¶
type AInput struct { Scope []Scope Indicator []Indicator On func(context.Context, REvent[InputEvent]) bool ExcludeValue bool OnError []OnError }
type AKeyDown ¶
type AKeyDown struct { // StopPropagation, if true, stops the event from bubbling up the DOM. StopPropagation bool // PreventDefault, if true, prevents the browser's default action for the event. PreventDefault bool // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate that the hook is running. Indicator []Indicator // On is the required backend handler for the click event. // It receives a typed EventRequest[KeyboardEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[KeyboardEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
AKeyDown is an attribute struct used with A(ctx, ...) to handle 'keydown' events via backend hooks.
type AKeyUp ¶
type AKeyUp struct { // StopPropagation, if true, stops the event from bubbling up the DOM. StopPropagation bool // PreventDefault, if true, prevents the browser's default action for the event. PreventDefault bool // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate that the hook is running. Indicator []Indicator // On is the required backend handler for the click event. // It receives a typed EventRequest[KeyboardEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[KeyboardEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
AKeyUp is an attribute struct used with A(ctx, ...) to handle 'keyup' events via backend hooks.
type ALostPointerCapture ¶
type ALostPointerCapture pointerEventHook
ALostPointerCapture is an attribute struct used with A(ctx, ...) to handle 'lostpointercapture' events via backend hooks.
func (ALostPointerCapture) Attr ¶
func (c ALostPointerCapture) Attr() AttrInit
type APointerCancel ¶
type APointerCancel struct { // StopPropagation, if true, stops the event from bubbling up the DOM. StopPropagation bool // PreventDefault, if true, prevents the browser's default action for the event. PreventDefault bool // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate that the hook is running. Indicator []Indicator // On is the required backend handler for the click event. // It receives a typed REvent[PointerEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[PointerEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
APointerCancel is an attribute struct used with A(ctx, ...) to handle 'pointercancel' events via backend hooks.
func (APointerCancel) Attr ¶
func (c APointerCancel) Attr() AttrInit
type APointerDown ¶
type APointerDown struct { // StopPropagation, if true, stops the event from bubbling up the DOM. StopPropagation bool // PreventDefault, if true, prevents the browser's default action for the event. PreventDefault bool // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate that the hook is running. Indicator []Indicator // On is the required backend handler for the click event. // It receives a typed REvent[PointerEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[PointerEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
APointerDown is an attribute struct used with A(ctx, ...) to handle 'pointerdown' events via backend hooks.
func (APointerDown) Attr ¶
func (c APointerDown) Attr() AttrInit
type APointerEnter ¶
type APointerEnter struct { // StopPropagation, if true, stops the event from bubbling up the DOM. StopPropagation bool // PreventDefault, if true, prevents the browser's default action for the event. PreventDefault bool // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate that the hook is running. Indicator []Indicator // On is the required backend handler for the click event. // It receives a typed REvent[PointerEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[PointerEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
APointerEnter is an attribute struct used with A(ctx, ...) to handle 'pointerenter' events via backend hooks.
func (APointerEnter) Attr ¶
func (c APointerEnter) Attr() AttrInit
type APointerLeave ¶
type APointerLeave struct { // StopPropagation, if true, stops the event from bubbling up the DOM. StopPropagation bool // PreventDefault, if true, prevents the browser's default action for the event. PreventDefault bool // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate that the hook is running. Indicator []Indicator // On is the required backend handler for the click event. // It receives a typed REvent[PointerEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[PointerEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
APointerLeave is an attribute struct used with A(ctx, ...) to handle 'pointerleave' events via backend hooks.
func (APointerLeave) Attr ¶
func (c APointerLeave) Attr() AttrInit
type APointerMove ¶
type APointerMove struct { // StopPropagation, if true, stops the event from bubbling up the DOM. StopPropagation bool // PreventDefault, if true, prevents the browser's default action for the event. PreventDefault bool // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate that the hook is running. Indicator []Indicator // On is the required backend handler for the click event. // It receives a typed REvent[PointerEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[PointerEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
APointerMove is an attribute struct used with A(ctx, ...) to handle 'pointermove' events via backend hooks.
func (APointerMove) Attr ¶
func (c APointerMove) Attr() AttrInit
type APointerOut ¶
type APointerOut struct { // StopPropagation, if true, stops the event from bubbling up the DOM. StopPropagation bool // PreventDefault, if true, prevents the browser's default action for the event. PreventDefault bool // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate that the hook is running. Indicator []Indicator // On is the required backend handler for the click event. // It receives a typed REvent[PointerEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[PointerEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
APointerOut is an attribute struct used with A(ctx, ...) to handle 'pointerout' events via backend hooks.
func (APointerOut) Attr ¶
func (c APointerOut) Attr() AttrInit
type APointerOver ¶
type APointerOver pointerEventHook
APointerOver is an attribute struct used with A(ctx, ...) to handle 'pointerover' events via backend hooks.
func (APointerOver) Attr ¶
func (c APointerOver) Attr() AttrInit
type APointerUp ¶
type APointerUp struct { // StopPropagation, if true, stops the event from bubbling up the DOM. StopPropagation bool // PreventDefault, if true, prevents the browser's default action for the event. PreventDefault bool // Scope determines how this hook is scheduled (e.g., blocking, debounce). Scope []Scope // Indicator specifies how to visually indicate that the hook is running. Indicator []Indicator // On is the required backend handler for the click event. // It receives a typed REvent[PointerEvent] and should return true // when the hook is considered complete and can be removed. On func(context.Context, REvent[PointerEvent]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
APointerUp is an attribute struct used with A(ctx, ...) to handle 'pointerup' events via backend hooks.
func (APointerUp) Attr ¶
func (c APointerUp) Attr() AttrInit
type ARawFileHref ¶
type ARawFileHref struct { Once bool Name string Handler func(w http.ResponseWriter, r *http.Request) }
func (ARawFileHref) Attr ¶
func (s ARawFileHref) Attr() AttrInit
type ARawHook ¶
type ARawHook struct { Name string On func(ctx context.Context, r RRawHook) bool Scope []Scope Indicator []Indicator }
type ARawSubmit ¶
type ARawSubmit struct { // Mode determines how this hook is scheduled (e.g., blocking, debounce). // See ModeDefault, ModeBlock, ModeFrame, etc. Scope []Scope // Indicator specifies how to visually indicate the hook is running // (e.g., by applying a class, attribute, or replacing content). Optional. Indicator []Indicator // On is the required backend handler for the form submission. // // It receives a RawFormRequest and should return true (is done) // when processing is complete and the hook can be removed. On func(context.Context, RRawForm) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
ARawSubmit is an attribute struct used with A(ctx, ...) to handle form submissions via backend hooks, providing low-level access to the raw multipart form data.
Unlike ASubmit, this variant does not decode the form into a typed struct. Instead, it gives full control over file uploads, streaming, and multipart parsing via RawFormRequest.
This is useful when handling large forms, file uploads, or custom parsing logic.
Example:
<form { A(ctx, ARawSubmit{ On: func(ctx context.Context, req RawFormRequest) bool { form, _ := req.ParseForm(32 << 20) // 32 MB file, _, _ := form.FormFile("upload") // handle file... return true }, })... }>
func (ARawSubmit) Attr ¶
func (s ARawSubmit) Attr() AttrInit
type ASubmit ¶
type ASubmit[D any] struct { // MaxMemory sets the maximum number of bytes to parse into memory // before falling back to temporary files when handling multipart forms. // // This affects file upload behavior. It is passed to ParseMultipartForm. // Defaults to 8 MB if zero. MaxMemory int // Mode determines how this hook is scheduled (e.g., blocking, debounce). // See ModeDefault, ModeBlock, ModeFrame, etc. Scope []Scope // Indicator specifies how to visually indicate the hook is running // (e.g., by applying a class, attribute, or replacing content). Optional. Indicator []Indicator // On is the required backend handler for the form submission. // // It receives a typed FormRequest[D] and should return true (is done) // when processing is complete and the hook can be removed. On func(context.Context, RForm[D]) bool // OnError determines what to do if error occured during hook requrest OnError []OnError }
ASubmit is an attribute struct used with A(ctx, ...) to handle form submissions via backend hooks.
It binds a <form> element to a backend handler that receives decoded form data of type D. The hook runs when the form is submitted and can support file uploads or large payloads.
This is typically used as:
<form { A(ctx, ASubmit[MyFormData]{ On: func(ctx context.Context, req FormRequest[MyFormData]) bool { // handle form submission return true }, })... }>
type Active ¶
type Active struct { PathMatcher PathMatcher QueryMatcher QueryMatcher Indicator []Indicator }
type After ¶
type After interface {
// contains filtered or unexported methods
}
After represents a client-side action to execute after a request completes. After actions can perform navigation, page reloads, or other browser operations.
func AfterLocationAssign ¶
AfterLocationAssign creates an After action that navigates to a new URL. This adds the new URL to the browser's history stack. The model parameter is used to generate the target URL using the application's routing system.
func AfterLocationReload ¶
func AfterLocationReload() After
AfterLocationReload creates an After action that reloads the current page. This triggers a full page refresh in the browser.
func AfterLocationReplace ¶
AfterLocationReplace creates an After action that replaces the current URL. This navigates to a new URL without adding an entry to the browser's history stack. The model parameter is used to generate the target URL using the application's routing system.
type AttrIndicator ¶
type AttrIndicator struct { Selector Selector // Element selector Name string // Attribute name Value string // Attribute value }
AttrIndicator temporarily sets an attribute on the selected element. The original attribute value (if any) is automatically restored when the indicator is removed.
func (AttrIndicator) Indicate ¶
func (c AttrIndicator) Indicate() *indicate
type Beam ¶
Beam represents a reactive value stream that can be read, subscribed to, or watched.
When used in a render cycle, it is guaranteed that a Door and all of its children will observe the exact same value for a given Beam. This ensures stable and predictable rendering behavior, even when multiple components depend on the same reactive source.
func NewBeam ¶
func NewBeam[T any, T2 comparable](source Beam[T], cast func(T) T2) Beam[T2]
NewBeam derives a new Beam[T2] from an existing Beam[T] by applying a transformation function.
The cast function maps values from the source beam to the derived beam. Updates are only propagated when the new value passes the default distinct function with != comparison to the old value
Parameters:
- source: the source Beam[T] to derive from
- cast: a function that transforms values from type T to type T2
Returns:
- A new Beam[T2] that emits transformed values when they differ from the previous value
func NewBeamExt ¶
func NewBeamExt[T any, T2 any](source Beam[T], cast func(T) T2, distinct func(new T2, old T2) bool) Beam[T2]
NewBeamExt derives a new Beam[T2] from an existing Beam[T] using custom transformation and filtering.
The cast function transforms source values from type T to type T2. The distinct function determines whether updated values should be propagated by comparing new and old values. If distinct is nil, every transformation will be propagated regardless of value equality.
Parameters:
- source: the source Beam[T] to derive from
- cast: a function to transform T → T2
- distinct: a function to determine if transformed values should propagate, or nil to always propagate
Returns:
- A new Beam[T2] that emits transformed values filtered by the distinct function
type BlockingScope ¶
type BlockingScope struct {
// contains filtered or unexported fields
}
BlockingScope prevents concurrent event processing within the same scope. When an event is already being processed, subsequent events are cancelled until the current event completes. This is useful for preventing double-clicks or rapid form submissions.
type CallConf ¶
type CallConf struct { // Name of the JavaScript call handler (must be registered on the frontend). Name string // Arg is the value passed to the frontend function. It is serialized to JSON. Arg any // On is an optional backend handler that is called with the frontend call responce. On func(context.Context, RCall) // OnCancel is called if the context becomes invalid before the call is delivered, // or if the call is canceled explicitly. Optional. OnCancel func(context.Context, error) }
CallConf configures a backend-to-frontend JavaScript call.
This allows server-side code to invoke a JavaScript function in the browser, passing arguments and optionally handling a response via a trigger hook.
The call is sent to the frontend immediately once the connection is ready (typically within a few milliseconds). If the backend context is no longer valid (e.g., the component was unmounted), the call is automatically canceled.
Fields:
- Name: the name of the frontend JavaScript function to call.
- Arg: the argument to pass to the function (must be JSON-serializable).
- Trigger: optional. Called when the frontend responds to the function call. The handler receives a CallRequest, which can read data from the frontend.
- Cancel: optional. Called if the call is invalidated before it reaches the frontend, or if manually canceled using the returned TryCancel function.
type CallOnError ¶
func (CallOnError) ErrorAction ¶
func (o CallOnError) ErrorAction() *errorAction
type ChangeEvent ¶
type ChangeEvent = front.ChangeEvent
type ClassIndicator ¶
type ClassIndicator struct { Selector Selector // Element selector Class string // CSS classes to add (space-separated) }
ClassIndicator temporarily adds CSS classes to the selected element. Multiple classes can be specified separated by spaces. The classes are automatically removed when the indicator is removed.
func (ClassIndicator) Indicate ¶
func (c ClassIndicator) Indicate() *indicate
type ClassRemoveIndicator ¶
type ClassRemoveIndicator struct { Selector Selector // Element selector Class string // CSS classes to remove (space-separated) }
ClassRemoveIndicator temporarily removes CSS classes from the selected element. Multiple classes can be specified separated by spaces. The classes are automatically restored when the indicator is removed.
func (ClassRemoveIndicator) Indicate ¶
func (c ClassRemoveIndicator) Indicate() *indicate
type ContentIndicator ¶
type ContentIndicator struct { Selector Selector // Element selector Content string // Text content to display }
ContentIndicator temporarily replaces the innerHTML of the selected element. The original content is automatically restored when the indicator is removed.
func (ContentIndicator) Indicate ¶
func (c ContentIndicator) Indicate() *indicate
type DebounceScope ¶
type DebounceScope struct {
// contains filtered or unexported fields
}
DebounceScope delays event processing using a debounce mechanism with both duration and limit parameters. Events are delayed by the duration, but will always execute within the limit timeframe regardless of new events.
func (*DebounceScope) Scope ¶
Scope creates a debounced scope with the specified timing parameters. The duration parameter sets the debounce delay - events are delayed by this amount and reset if new events arrive. The limit parameter sets the maximum time an event can be delayed - events will execute after this time regardless of new events.
Parameters:
- duration: Debounce delay time (resets on new events)
- limit: Maximum delay time (executes regardless of new events)
type Door ¶
Door represents a dynamic placeholder in the DOM tree that can be updated, replaced, or removed at runtime.
It is a fundamental building block of the framework, used to manage dynamic HTML content. All changes made to a Door are automatically synchronized with the frontend DOM.
A Door is itself a templ.Component and can be used directly in templates:
@door // or @door { // initial HTML content }
Doors start inactive and become active when rendered. Operations on inactive doors are stored virtually and applied when the door becomes active. If a door is removed or replaced, it becomes inactive again, but operations continue to update its virtual state for potential future rendering.
The context used when rendering a Door's content follows the Door's lifecycle. This allows you to safely use `ctx.Done()` inside background goroutines that depend on the Door's presence in the DOM.
Extended methods (prefixed with X) return a channel that can be used to track when operations complete. The channel receives nil on success or an error on failure, then closes. For inactive doors, the channel closes immediately without sending a value.
During a single render cycle, Doors and their children are guaranteed to observe consistent state (Beam), ensuring stable and predictable rendering.
type ESConf ¶
type ESConf = resources.BuildProfiles
type FocusEvent ¶
type FocusEvent = front.FocusEvent
type Fragment ¶
Fragment is a helper interface for defining composable, stateful, and code-interactive components.
A Fragment groups fields, methods, and rendering logic into a reusable unit. This is especially useful when a simple templ function is not sufficient — for example, when you need to manage internal state, expose multiple methods, or control updates from Go code.
Fragments implement the Render method and can be rendered using the F() helper.
A Fragment can be stored in a variable, rendered once, and later updated by calling custom methods. These methods typically encapsulate internal Door updates — such as a Refresh() function that re-renders part of the fragment's content manually.
By default, a Fragment is static — its output does not change after rendering. To enable dynamic behavior, use a root-level Door to support targeted updates.
Example:
type Counter struct { door doors.Door count int } func (c *Counter) Refresh(ctx context.Context) { c.door.Update(ctx, c.display()) } templ (c *Counter) Render() { @c.door { @c.display() } <button { doors.A(ctx, doors.AClick{ On: func(ctx context.Context, _ doors.REvent[doors.PointerEvent]) bool { c.count++ c.Refresh(ctx) return false }, })... }> Click Me! </button> } templ (c *Counter) display() { Clicked { fmt.Sprint(c.count) } time(s)! }
type FrameScope ¶
type FrameScope struct {
// contains filtered or unexported fields
}
FrameScope manages two types of events: immediate events and frame events. Immediate events (frame=false) executed normaly. Frame events (frame=true) wait until all previous events in the scope complete, while blocking new events, and then execute normaly.
func (*FrameScope) Scope ¶
func (d *FrameScope) Scope(frame bool) Scope
Scope creates a frame-based scope with the specified event type. Immediate events (frame=false) executed normaly. Frame events (frame=true) wait until all previous events in the scope complete, while blocking new events (frame=true and frame=false), and then execute normaly.
Parameters:
- frame: false for immediate execution, true to wait for other events to complete
type HrefActiveMatch ¶
type HrefActiveMatch int
const ( MatchFull HrefActiveMatch = iota MatchPath MatchStarts )
type Import ¶
type Import interface {
// contains filtered or unexported methods
}
Import represents a resource that can be imported into a web page. Imports can be JavaScript modules, CSS stylesheets, or external resources. They are processed during rendering to generate appropriate HTML tags and import maps.
type ImportModule ¶
type ImportModule struct { Specifier string // Import map specifier name (optional) Path string // File system path to the module Profile string // Build profile for esbuild options Load bool // Whether to load the module immediately via script tag Name string // Custom name for the generated file (optional) }
ImportModule imports a JavaScript/TypeScript file, processes it through esbuild, and makes it available as an ES module. The module can be added to the import map with a specifier name and/or loaded directly via script tag.
type ImportModuleBundle ¶
type ImportModuleBundle struct { Specifier string // Import map specifier name (optional) Entry string // Entry point file for the bundle Profile string // Build profile for esbuild options Load bool // Whether to load the module immediately via script tag Name string // Custom name for the generated file (optional) }
ImportModuleBundle creates a bundled JavaScript module from an entry point, bundling all local imports and dependencies into a single file using esbuild.
type ImportModuleBundleFS ¶
type ImportModuleBundleFS struct { CacheKey string // Unique cache key for this filesystem/bundle combination Specifier string // Import map specifier name (optional) FS fs.FS // File system to read from Entry string // Entry point file within the filesystem Profile string // Build profile for esbuild options Load bool // Whether to load the module immediately via script tag Name string // Custom name for the generated file (optional) }
ImportModuleBundleFS creates a bundled JavaScript module from a file system entry point, bundling all local imports and dependencies into a single file using esbuild. This is useful for embedding assets or working with embed.FS.
type ImportModuleBytes ¶
type ImportModuleBytes struct { Specifier string // Import map specifier name (optional) Content []byte // Module source code Profile string // Build profile for esbuild options Load bool // Whether to load the module immediately via script tag Name string // Custom name for the generated file }
ImportModuleBytes imports JavaScript/TypeScript content from a byte slice, processes it through esbuild, and makes it available as an ES module.
type ImportModuleExternal ¶
type ImportModuleExternal struct { Specifier string // Import map specifier name (optional) Load bool // Whether to load the module immediately via script tag Src string // External URL to the module }
ImportModuleExternal imports a JavaScript module from an external URL. This adds the URL to the Content Security Policy script sources.
type ImportModuleHosted ¶
type ImportModuleHosted struct { Specifier string // Import map specifier name (optional) Load bool // Whether to load the module immediately via script tag Src string // Full path to the hosted module }
ImportModuleHosted imports a JavaScript module that is hosted locally but not processed by the build system. The Src should be a full path starting from the application root.
type ImportModuleRaw ¶
type ImportModuleRaw struct { Specifier string // Import map specifier name (optional) Path string // File system path to the module Load bool // Whether to load the module immediately via script tag Name string // Custom name for the generated file (optional) }
ImportModuleRaw imports a JavaScript file without any processing or transformation. The file is served as-is without going through esbuild.
type ImportModuleRawBytes ¶
type ImportModuleRawBytes struct { Specifier string // Import map specifier name (optional) Content []byte // Raw JavaScript content Load bool // Whether to load the module immediately via script tag Name string // Custom name for the generated file }
ImportModuleRawBytes imports JavaScript content from a byte slice without any processing or transformation. The content is served as-is.
type ImportStyle ¶
type ImportStyle struct { Path string // File system path to the CSS file Name string // Custom name for the generated file (optional) }
ImportStyle imports a CSS file, processes it (minification), and makes it available as a stylesheet link in the HTML head.
type ImportStyleBytes ¶
type ImportStyleBytes struct { Content []byte // CSS source code Name string // Custom name for the generated file }
ImportStyleBytes imports CSS content from a byte slice, processes it (minification), and makes it available as a stylesheet link.
type ImportStyleExternal ¶
type ImportStyleExternal struct {
Href string // External URL to the stylesheet
}
ImportStyleExternal imports a CSS stylesheet from an external URL. This adds the URL to the Content Security Policy style sources.
type ImportStyleHosted ¶
type ImportStyleHosted struct {
Href string // Full path to the hosted stylesheet
}
ImportStyleHosted imports a CSS stylesheet that is hosted locally but not processed by the build system. The Href should be a full path starting from the application root.
type IndicateOnError ¶
func (IndicateOnError) ErrorAction ¶
func (o IndicateOnError) ErrorAction() *errorAction
type Indicator ¶
Indicator represents a temporary modification to a DOM element. Indicators can change content, attributes, or CSS classes and are automatically cleaned up when no longer needed.
func IndicatorAttr ¶
IndicatorAttr creates an indicator that sets an attribute on the target element. This is a convenience function equivalent to AttrIndicator{SelectorTarget(), attr, value}.
func IndicatorAttrQuery ¶
IndicatorAttrQuery creates an indicator that sets an attribute on an element selected by CSS query. The query parameter should be a valid CSS selector string.
func IndicatorAttrQueryParent ¶
IndicatorAttrQueryParent creates an indicator that sets an attribute on a parent element. Starting from the target element's parent, it finds the closest ancestor matching the CSS query.
func IndicatorClass ¶
IndicatorClass creates an indicator that adds CSS classes to the target element. Multiple classes can be specified separated by spaces. This is a convenience function equivalent to ClassIndicator{SelectorTarget(), class}.
func IndicatorClassQuery ¶
IndicatorClassQuery creates an indicator that adds CSS classes to an element selected by CSS query. The query parameter should be a valid CSS selector string. Multiple classes can be specified separated by spaces.
func IndicatorClassQueryParent ¶
IndicatorClassQueryParent creates an indicator that adds CSS classes to a parent element. Starting from the target element's parent, it finds the closest ancestor matching the CSS query. Multiple classes can be specified separated by spaces.
func IndicatorClassRemove ¶
IndicatorClassRemove creates an indicator that removes CSS classes from the target element. Multiple classes can be specified separated by spaces. This is a convenience function equivalent to ClassRemoveIndicator{SelectorTarget(), class}.
func IndicatorClassRemoveQuery ¶
IndicatorClassRemoveQuery creates an indicator that removes CSS classes from an element selected by CSS query. The query parameter should be a valid CSS selector string. Multiple classes can be specified separated by spaces.
func IndicatorClassRemoveQueryParent ¶
IndicatorClassRemoveQueryParent creates an indicator that removes CSS classes from a parent element. Starting from the target element's parent, it finds the closest ancestor matching the CSS query. Multiple classes can be specified separated by spaces.
func IndicatorContent ¶
IndicatorContent creates an indicator that changes the content of the target element. This is a convenience function equivalent to ContentIndicator{SelectorTarget(), content}.
func IndicatorContentQuery ¶
IndicatorContentQuery creates an indicator that changes the content of an element selected by CSS query. The query parameter should be a valid CSS selector string.
func IndicatorContentQueryParent ¶
IndicatorContentQueryParent creates an indicator that changes the content of a parent element. Starting from the target element's parent, it finds the closest ancestor matching the CSS query.
type InputEvent ¶
type InputEvent = front.InputEvent
type JSX ¶
type KeyboardEvent ¶
type KeyboardEvent = front.KeyboardEvent
type LatestScope ¶
type LatestScope struct {
// contains filtered or unexported fields
}
LatestScope cancels previous events and only processes the most recent one. When a new event arrives, any currently processing event is cancelled and the new event takes priority. This is useful for search-as-you-type or real-time filtering scenarios.
type Location ¶
Location represents a URL location within the application's routing system. It encapsulates the path and query parameters encoded from a path model.
Location provides methods for URL manipulation and can be used with navigation functions or href attributes.
func NewLocation ¶
NewLocation creates a Location from a model using the registered path adapter for that model's type. The adapter encodes the model's fields into a URL according to the path patterns defined in struct tags.
Path models use struct tags to define routing patterns:
- `path:"/pattern"` tags on bool fields define path variants
- `:FieldName` in patterns captures path segments to struct fields
- `query:"name"` tags capture query parameters
- `:Field+` captures remaining path segments
Example:
type ProductPath struct { List bool `path:"/products"` Item bool `path:"/products/:Id"` Id int Sort string `query:"sort"` } // Create location for product item loc, err := doors.NewLocation(ctx, ProductPath{ Item: true, Id: 123, Sort: "price", }) // loc.String() returns "/products/123?sort=price"
Returns an error if no adapter is registered for the model's type or if encoding fails due to invalid model data.
type Mod ¶
Mod represents a router modification that can be applied to configure routing behavior.
func EnableCSP ¶
EnableCSP configures Content Security Policy headers for enhanced security. This helps prevent XSS attacks and other security vulnerabilities.
func ServeDir ¶
ServeDir serves static files from a local directory using os.DirFS. This creates a filesystem from the directory and serves it at the prefix.
Parameters:
- prefix: URL prefix (e.g., "/public/")
- path: Local directory path
func ServeFS ¶
ServeFS serves static files from an embedded filesystem at the specified URL prefix. This is useful for serving embedded assets using Go's embed.FS.
Parameters:
- prefix: URL prefix (e.g., "/assets/")
- fs: Filesystem to serve from (typically embed.FS)
func ServeFallback ¶
ServeFallback sets a fallback handler for requests that don't match any routes. This is useful for integrating with other HTTP handlers or serving custom 404 pages.
func ServeFile ¶
ServeFile serves a single file at the specified URL path.
Parameters:
- path: URL path (e.g., "/favicon.ico")
- localPath: Local file path
func ServePage ¶
func ServePage[M any](handler func(p PageRouter[M], r RPage[M]) PageRoute) Mod
ServePage registers a page handler for a specific path model type. The model type M defines URL patterns through struct field tags, allowing the router to decode request URIs into structured data. Path patterns are declared using `path` tags on boolean fields, with parameter capture using `:FieldName` syntax.
Example:
type BlogPath struct { Home bool `path:"/"` // Match root path Post bool `path:"/post/:ID"` // Match /post/123, capture ID List bool `path:"/posts"` // Match /posts ID int // Captured from :ID parameter Tag string `query:"tag"` // Query parameter ?tag=golang } router.Use(ServePage(func(p PageRouter[BlogPath], r RPage[BlogPath]) PageRoute { return p.Page(&blog{}) }))
func SetESConf ¶
SetESConf configures esbuild profiles for JavaScript/TypeScript processing. Different profiles can be used for development vs production builds.
func SetErrorPage ¶
SetErrorPage sets a custom error page component for handling internal errors. The component receives the error message as a parameter.
func SetGoroutineLimitPerInstance ¶
SetGoroutineLimitPerInstance sets the maximum number of goroutines per instance. This controls resource usage for concurrent operations within each page instance.
func SetSessionHooks ¶
SetSessionHooks registers callbacks for session lifecycle events. The create callback is called when a new session is created. The delete callback is called when a session is removed.
func SetSystemConf ¶
func SetSystemConf(conf SystemConf) Mod
SetSystemConf applies system-wide configuration including timeouts, limits, and other framework behavior settings.
type OnError ¶
func OnErrorCall ¶
type Page ¶
type Page[M any] interface { Render(SourceBeam[M]) templ.Component }
Page defines the interface for page components that can be rendered with reactive data. Pages receive a SourceBeam containing the model data and return a templ.Component.
Example:
type BlogPage struct { beam doors.SourceBeam[BlogPath] } func (p *BlogPage) Render(beam doors.SourceBeam[BlogPath]) templ.Component { p.beam = beam return common.Template(p) } func (p *BlogPage) Body() templ.Component { return doors.Sub(p.beam, func(path BlogPath) templ.Component { switch { case path.Home: return homePage() case path.Post: return postPage(path.ID) } }) }
type PageRoute ¶
PageRoute represents a response that can be returned from page handlers. This includes page responses, redirects, reroutes, and static content.
type PageRouter ¶
type PageRouter[M any] interface { // Serve page Page(page Page[M]) PageRoute // Serve page with custom status PageStatus(page Page[M], status int) PageRoute // Serve func page PageFunc(pageFunc func(SourceBeam[M]) templ.Component) PageRoute // Serve func page and custom status PageFuncStatus(pageFunc func(SourceBeam[M]) templ.Component, status int) PageRoute // Serve static page StaticPage(content templ.Component) PageRoute // Serve static page with custom status StaticPageStatus(content templ.Component, status int) PageRoute // Internal reroute to different model (detached=true disables path synchronization) Reroute(model any, detached bool) PageRoute // HTTP redirect to model URL Redirect(model any) PageRoute // HTTP redirect with custom status RedirectStatus(model any, status int) PageRoute }
PageRouter provides methods for creating different types of page responses. It allows rendering pages, redirecting, rerouting, and serving static content.
type ParsedForm ¶
type ParsedForm interface { FormValues() url.Values // Returns all form values FormValue(key string) string // Returns a single form value FormFile(key string) (multipart.File, *multipart.FileHeader, error) // Returns an uploaded file Form() *multipart.Form // Returns the underlying multipart form }
ParsedForm provides access to parsed form data including values and files.
type PathMatcher ¶
type PathMatcher interface {
// contains filtered or unexported methods
}
func PathMatcherFull ¶
func PathMatcherFull() PathMatcher
func PathMatcherParts ¶
func PathMatcherParts(n int) PathMatcher
func PathMatcherStarts ¶
func PathMatcherStarts() PathMatcher
type PointerEvent ¶
type PointerEvent = front.PointerEvent
type QueryMatcher ¶
type QueryMatcher interface {
// contains filtered or unexported methods
}
func QueryMatcherAll ¶
func QueryMatcherAll() QueryMatcher
func QueryMatcherIgnore ¶
func QueryMatcherIgnore() QueryMatcher
func QueryMatcherSome ¶
func QueryMatcherSome(params ...string) QueryMatcher
type RAfter ¶
RAfter provides the ability to set an After action to execute client-side after the request completes.
type RCall ¶
type RCall interface { RRawForm Body() io.ReadCloser // Returns the request body RAfter }
RCall represents a request context for direct HTTP calls with full access to the response writer and request body. This provides the most control over the HTTP request/response cycle.
type REvent ¶
REvent represents a request context for event handlers with typed event data. The generic type E represents the structure of the event data.
type RForm ¶
RForm represents a request context for form submissions with typed form data. The generic type D represents the structure of the parsed form data.
type RHook ¶
RHook represents a request context for hook handlers with typed data. The generic type D represents the structure of the hook data.
type RPage ¶
type RPage[M any] interface { R // Returns the decoded URL model GetModel() M // Access to incoming request headers RequestHeader() http.Header // Access to outgoing response headers ResponseHeader() http.Header }
RPage provides access to request data and response control for page handlers. It combines basic request/response functionality with model access.
type RRawForm ¶
type RRawForm interface { R W() http.ResponseWriter Reader() (*multipart.Reader, error) // Returns a multipart reader for streaming ParseForm(maxMemory int) (ParsedForm, error) // Parses form data with memory limit RAfter }
RRawForm provides access to raw multipart form data and parsing capabilities. This is used when you need direct access to the form parsing process or when working with file uploads.
type RRawHook ¶
type RRawHook interface { RRawForm Body() io.ReadCloser // Returns the request body }
RRawHook provides access to raw request data for hook handlers without automatic data parsing. This gives full control over request processing.
type Router ¶
Router represents the main HTTP router that handles all requests. It implements http.Handler and provides configuration through Use().
type Scope ¶
Scope controls event processing concurrency by managing how multiple events are queued, debounced, blocked, or serialized. Scopes provide fine-grained control over event handling behavior to prevent race conditions and improve UX.
func ScopeBlocking ¶
func ScopeBlocking() []Scope
ScopeBlocking creates a blocking scope that cancels subsequent events while one is already processing. Use this to prevent duplicate operations like double form submissions or multiple API calls from rapid clicking.
func ScopeDebounce ¶
ScopeDebounce creates a debounced scope that delays event execution. Events are delayed by duration, but will always execute within limit time. This is useful for preventing excessive API calls during rapid user input.
Parameters:
- duration: How long to wait after the last event before executing
- limit: Maximum time to wait before forcing execution
func ScopeLatest ¶
func ScopeLatest() []Scope
ScopeLatest creates a scope that only processes the most recent event, cancelling any previous events that are still processing. This ensures only the latest user action is processed.
func ScopeSerial ¶
func ScopeSerial() []Scope
ScopeSerial creates a serial scope that processes events one at a time in order. Events are queued and executed sequentially.
type ScopeSet ¶
ScopeSet represents the configuration data for a specific scope instance. It contains the scope type, ID, and any additional parameters needed for execution.
type Selector ¶
type Selector interface {
// contains filtered or unexported methods
}
Selector defines how to target DOM elements for indication. Elements can be selected by targeting the event source, CSS queries, or parent traversal.
func SelectorParentQuery ¶
SelectorParentQuery creates a selector that finds the closest ancestor element matching the CSS sele 2 ctor. Starting from the target element's parent, it traverses up the DOM tree to find the first matching ancestor. The query parameter should be a valid CSS selector string.
func SelectorQuery ¶
SelectorQuery creates a selector that targets the first element matching the CSS selector. The query parameter should be a valid CSS selector string (e.g., "#myId", ".myClass", "div.container").
func SelectorTarget ¶
func SelectorTarget() Selector
SelectorTarget creates a selector that targets the element that triggered the event. This is the most common selector type for interactive elements like buttons.
type SerialScope ¶
type SerialScope struct {
// contains filtered or unexported fields
}
SerialScope processes events one at a time in the order they were received. Events are queued and processed sequentially.
type SourceBeam ¶
type SourceBeam[T any] = beam.SourceBeam[T]
SourceBeam is the initial Beam (others are derived from it), which, in addition to its core functionality, includes the ability to update values and propagate changes to all subscribers and derived beams. It serves as the root of a reactive value chain. Updates and mutations are synchronized across all subscribers, ensuring consistent state during rendering cycles. During a render cycle, all consumers will see a consistent view of the latest value. The source maintains a sequence of values for synchronization purposes.
IMPORTANT: For reference types (slices, maps, pointers, structs), do not modify the data directly. Instead, create a new instance and update the reference itself. Direct modification can break the consistency guarantees since subscribers may observe partial changes or inconsistent state.
func NewSourceBeam ¶
func NewSourceBeam[T comparable](init T) SourceBeam[T]
NewSourceBeam creates a new SourceBeam with the given initial value. Updates are only propagated when the new value passes the default distinct function with != comparison to the old value
Parameters:
- init: the initial value for the SourceBeam
Returns:
- A new SourceBeam[T] instance
func NewSourceBeamExt ¶
func NewSourceBeamExt[T any](init T, distinct func(new T, old T) bool) SourceBeam[T]
NewSourceBeamExt creates a new SourceBeam with a custom distinct function.
The distinct function receives new and old values and should return true if the new value is considered different and should be propagated to subscribers. If distinct is nil, every update will be propagated regardless of value equality.
Parameters:
- init: the initial value for the SourceBeam
- distinct: a function to determine if updates should propagate, or nil to always propagate
Returns:
- A new SourceBeam[T] instance that uses the distinct function for update filtering
type SystemConf ¶
type SystemConf = common.SystemConf
SystemConf contains system-wide configuration options for the framework.