ds

package
v0.15.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 22, 2026 License: MIT Imports: 10 Imported by: 7

Documentation

Overview

Package ds provides typed helpers for Datastar HTML attributes.

Datastar's parameterized plugins use a colon separator (e.g. data-on:click), NOT a hyphen (data-on-click). A hyphen is silently ignored as an unknown plugin. This package makes that mistake impossible by construction.

Index

Constants

View Source
const DrawerContainerID = "drawer-panel"

DrawerContainerID is the fixed ID of the drawer container in the base template.

View Source
const ModalContainerID = "modal-panel"

ModalContainerID is the fixed ID of the modal container in the base template.

View Source
const ToastContainerID = "toast-container"

ToastContainerID is the fixed ID of the toast container in the base template.

Variables

View Source
var Send = &Sender{}

Send provides backend SSE operations (drawer, toast, etc.). Frontend attribute helpers remain as top-level ds.XXX functions.

Functions

func Attr

func Attr(name, expr string) templ.Attributes

Attr returns a data-attr:<name> attribute.

func Bind

func Bind(componentID, field string) templ.Attributes

Bind returns a data-bind:<componentID>.<field> attribute. The componentID is sanitized (hyphens → underscores) to match the signal namespace. This pairs with ReadSignals(componentID, r, &signals) on the handler side.

func BuildConditional

func BuildConditional(condition, trueExpr, falseExpr string) string

BuildConditional creates a standalone ternary expression.

func Class

func Class(value string) templ.Attributes

Class returns a data-class attribute (object syntax).

func ClassToggle

func ClassToggle(name, expr string) templ.Attributes

ClassToggle returns a data-class:<name> attribute (single class toggle).

func Computed

func Computed(name, expr string) templ.Attributes

Computed returns a data-computed:<name> attribute.

func Delete

func Delete(url string, opts ...ActionOption) string

Delete returns a @delete('url') expression with the CSRF token header.

func DeleteOnce

func DeleteOnce(url string) string

DeleteOnce returns a @delete('url') expression with CSRF but without retries.

func Effect

func Effect(expr string) templ.Attributes

Effect returns a data-effect attribute.

func Get

func Get(url string, opts ...ActionOption) string

Get returns a @get('url') expression.

ds.Get("/api/data")                // → @get('/api/data')
ds.Get("/api/data", ds.WithRetries(3)) // → @get('/api/data', {retryMaxCount: 3})

func GetOnce

func GetOnce(url string) string

GetOnce returns a @get('url') expression without retries.

ds.GetOnce("/api/data") // → @get('/api/data', {retryMaxCount: 0})

func Indicator

func Indicator(name string) templ.Attributes

Indicator returns a data-indicator:<name> attribute.

func Init

func Init(expr string) templ.Attributes

Init returns a data-init attribute.

func Merge

func Merge(attrs ...templ.Attributes) templ.Attributes

Merge combines multiple templ.Attributes into one. Later values overwrite earlier ones for the same key.

func On

func On(event, expr string) templ.Attributes

On returns a data-on:<event> attribute.

ds.On("click", expr) → {"data-on:click": expr}

func OnClick

func OnClick(expr string) templ.Attributes

OnClick is shorthand for On("click", expr).

func Patch

func Patch(url string, opts ...ActionOption) string

Patch returns a @patch('url') expression with the CSRF token header.

func PatchOnce

func PatchOnce(url string) string

PatchOnce returns a @patch('url') expression with CSRF but without retries.

func Post

func Post(url string, opts ...ActionOption) string

Post returns a @post('url') expression with the CSRF token header.

ds.Post("/api/submit")                // → @post('/api/submit', {headers: {…}})
ds.Post("/api/submit", ds.WithRetries(5)) // → @post('/api/submit', {headers: {…}, retryMaxCount: 5})

func PostOnce

func PostOnce(url string) string

PostOnce returns a @post('url') expression with CSRF but without retries.

func Put

func Put(url string, opts ...ActionOption) string

Put returns a @put('url') expression with the CSRF token header.

func PutOnce

func PutOnce(url string) string

PutOnce returns a @put('url') expression with CSRF but without retries.

func RawSignals

func RawSignals(value string) templ.Attributes

RawSignals returns a data-signals attribute with a raw JSON string. Prefer NewSignals(componentID, struct) for type-safe namespaced signals.

func ReadAndSSE

func ReadAndSSE(componentID string, w http.ResponseWriter, r *http.Request, dest any) (*datastar.ServerSentEventGenerator, error)

ReadAndSSE reads namespaced signals from a Datastar request and then creates the SSE writer. This enforces the correct ordering — ReadSignals must happen before NewSSE because SSE creation consumes the request body.

sse, err := ds.ReadAndSSE("my-form", w, r, &signals)
if err != nil { ... }
sse.MarshalAndPatchSignals(...)

func ReadRaw

func ReadRaw(r *http.Request, dest *map[string]json.RawMessage) error

ReadRaw reads all signal namespaces from a Datastar request as raw JSON. Returns a map keyed by namespace (sanitized component ID) with raw JSON values.

Call this BEFORE datastar.NewSSE() — SSE creation consumes the request body.

This is useful when you need to discover which namespace was sent (e.g. with filterSignals) rather than reading a known component ID.

var raw map[string]json.RawMessage
if err := ds.ReadRaw(r, &raw); err != nil { ... }

func ReadSignals

func ReadSignals(componentID string, r *http.Request, dest any) error

ReadSignals reads namespaced signals from a Datastar request. The componentID is sanitized (hyphens → underscores) to match the JS namespace. dest must be a pointer to a struct with json tags matching the signal shape.

Call this BEFORE datastar.NewSSE() — SSE creation consumes the request body.

var signals commandbar.CommandBarSignals
if err := ds.ReadSignals("my-bar", r, &signals); err != nil { ... }
input := signals.Text

func Ref

func Ref(name string) templ.Attributes

Ref returns a data-ref:<name> attribute.

func Show

func Show(expr string) templ.Attributes

Show returns a data-show attribute.

func Style

func Style(prop, expr string) templ.Attributes

Style returns a data-style:<prop> attribute.

func Text

func Text(expr string) templ.Attributes

Text returns a data-text attribute.

Types

type ActionOption

type ActionOption func(*actionConfig)

ActionOption customizes a backend action expression (@get, @post, etc.).

func WithContentType

func WithContentType(ct string) ActionOption

WithContentType sets the content type for the action. Use "form" to send multipart/form-data (file uploads).

func WithFilterSignals

func WithFilterSignals(componentID string) ActionOption

WithFilterSignals limits which signals are sent with the request. Pass a component ID — only signals in that namespace are included. Hyphens are automatically converted to underscores.

ds.Post("/api/send", ds.WithFilterSignals("my-bar"))
// → @post('/api/send', {..., filterSignals: {include: /^my_bar\./}})

func WithRequestCancellation

func WithRequestCancellation(mode string) ActionOption

WithRequestCancellation controls whether other SSE requests cancel this one. Use "disabled" for persistent stream connections that should not be interrupted.

func WithRetries

func WithRetries(n int) ActionOption

WithRetries sets the maximum number of retry attempts. Use 0 to disable retries entirely.

type ConfirmOption

type ConfirmOption func(*confirmConfig)

ConfirmOption customizes the confirm dialog.

func WithCancelLabel

func WithCancelLabel(label string) ConfirmOption

WithCancelLabel sets the cancel button text (default: "Cancel").

func WithConfirmClass

func WithConfirmClass(class string) ConfirmOption

WithConfirmClass sets the confirm button class (default: "btn btn-primary").

func WithConfirmGet

func WithConfirmGet() ConfirmOption

WithConfirmGet uses GET instead of POST for the confirm action. By default, confirm uses POST with CSRF protection since confirmations typically trigger destructive/mutating operations.

func WithConfirmLabel

func WithConfirmLabel(label string) ConfirmOption

WithConfirmLabel sets the confirm button text (default: "Confirm").

func WithConfirmMaxWidth

func WithConfirmMaxWidth(class string) ConfirmOption

WithConfirmMaxWidth sets the dialog max-width class (default: "max-w-sm").

func WithConfirmTitle

func WithConfirmTitle(title string) ConfirmOption

WithConfirmTitle sets the dialog title (default: "Confirm").

type DataClass

type DataClass struct {
	// contains filtered or unexported fields
}

DataClass builds data-class attribute values: JS objects mapping CSS class names to signal conditions.

func NewDataClass

func NewDataClass() *DataClass

NewDataClass creates a new DataClass builder.

func (*DataClass) Add

func (d *DataClass) Add(className, condition string) *DataClass

Add maps a CSS class name to a signal condition.

func (*DataClass) Build

func (d *DataClass) Build() string

Build returns the JS object string for the data-class attribute.

type DatastarExpression

type DatastarExpression struct {
	// contains filtered or unexported fields
}

DatastarExpression builds composable multi-statement Datastar expressions.

func NewExpression

func NewExpression() *DatastarExpression

NewExpression creates a new expression builder.

func (*DatastarExpression) Build

func (e *DatastarExpression) Build() string

Build joins all statements with "; " and returns the final expression.

func (*DatastarExpression) Conditional

func (e *DatastarExpression) Conditional(condition, trueExpr, falseExpr string) *DatastarExpression

Conditional adds a ternary expression.

func (*DatastarExpression) SetSignal

func (e *DatastarExpression) SetSignal(signal, value string) *DatastarExpression

SetSignal adds a signal assignment: $signal = value

func (*DatastarExpression) Statement

func (e *DatastarExpression) Statement(stmt string) *DatastarExpression

Statement adds a raw statement to the expression.

type DrawerOption

type DrawerOption func(*drawerConfig)

DrawerOption customizes drawer appearance.

func WithDrawerExpandable added in v0.9.2

func WithDrawerExpandable() DrawerOption

WithDrawerExpandable adds an expand/collapse toggle button to the drawer header. When expanded, the drawer fills the full viewport width. When collapsed, it returns to the configured max-width.

func WithDrawerMaxWidth

func WithDrawerMaxWidth(class string) DrawerOption

WithDrawerMaxWidth sets the panel max-width class (default "max-w-lg").

type ModalOption

type ModalOption func(*modalConfig)

ModalOption customizes modal appearance.

func WithModalMaxWidth

func WithModalMaxWidth(class string) ModalOption

WithModalMaxWidth sets the modal max-width class (default "max-w-lg").

type Sender

type Sender struct{}

Sender groups backend SSE operations that send events to the browser.

func (*Sender) Confirm

func (s *Sender) Confirm(sse *datastar.ServerSentEventGenerator, message string, confirmURL string, opts ...ConfirmOption) error

Confirm shows a confirmation dialog via SSE using the modal container. When the user clicks confirm, it triggers a POST request (with CSRF) to confirmURL. Use WithConfirmGet() to use GET instead. Cancel closes the dialog without any request.

func (*Sender) Download

func (s *Sender) Download(sse *datastar.ServerSentEventGenerator, url string, filename string) error

Download triggers a file download in the browser via SSE without navigating away. It creates a temporary anchor element, triggers a click, and removes it.

func (*Sender) Drawer

func (s *Sender) Drawer(ctx context.Context, sse *datastar.ServerSentEventGenerator, content templ.Component, opts ...DrawerOption) error

Drawer renders a templ component inside a slide-in drawer panel and patches it into #drawer-panel via SSE.

func (*Sender) HideDrawer

func (s *Sender) HideDrawer(sse *datastar.ServerSentEventGenerator) error

HideDrawer patches #drawer-panel back to its empty placeholder via SSE. Useful for server-initiated close (e.g. after a form submit inside the drawer).

func (*Sender) HideModal

func (s *Sender) HideModal(sse *datastar.ServerSentEventGenerator) error

HideModal patches #modal-panel back to its empty placeholder via SSE. Useful for server-initiated close (e.g. after a form submit inside the modal).

func (*Sender) Modal

func (s *Sender) Modal(ctx context.Context, sse *datastar.ServerSentEventGenerator, content templ.Component, opts ...ModalOption) error

Modal renders a templ component inside a centered modal dialog and patches it into #modal-panel via SSE.

func (*Sender) Patch

Patch renders a templ component and patches it into the DOM via SSE. The component's root element must have an id attribute for Datastar to find the target. Additional options (selector, mode) can be passed through.

func (*Sender) Redirect

func (s *Sender) Redirect(sse *datastar.ServerSentEventGenerator, url string) error

Redirect sends an SSE event that navigates the browser to the given URL. Wraps the Datastar SDK's sse.Redirect() which handles Firefox quirks automatically.

func (*Sender) Toast

func (s *Sender) Toast(sse *datastar.ServerSentEventGenerator, level ToastLevel, message string, opts ...ToastOption) error

Toast appends a toast notification via SSE. Default behavior: auto-dismiss after 3 seconds with a close button.

func (*Sender) ToastComponent

func (s *Sender) ToastComponent(ctx context.Context, sse *datastar.ServerSentEventGenerator, component templ.Component) error

ToastComponent appends a custom templ component as a toast via SSE.

type SignalManager

type SignalManager struct {
	ID          string
	Signals     any
	DataSignals string
}

SignalManager provides a structured way to manage Datastar signals. It namespaces signals by ID so multiple instances of the same component on a page don't collide.

func NewSignals

func NewSignals(id string, signalsStruct any) *SignalManager

NewSignals creates a new SignalManager with the given ID and initial state. The ID is sanitized (hyphens → underscores) for JavaScript compatibility. The signalsStruct should have json tags for each property.

func (*SignalManager) Conditional

func (sm *SignalManager) Conditional(property, trueValue, falseValue string) string

Conditional returns a ternary expression based on a signal property.

func (*SignalManager) ConditionalAction

func (sm *SignalManager) ConditionalAction(condition, property, value string) string

ConditionalAction executes an action only when a condition is true.

func (*SignalManager) Equals

func (sm *SignalManager) Equals(property, value string) string

Equals returns a strict equality comparison expression.

func (*SignalManager) NotEquals

func (sm *SignalManager) NotEquals(property, value string) string

NotEquals returns a strict inequality comparison expression.

func (*SignalManager) Set

func (sm *SignalManager) Set(property, value string) string

Set returns an assignment expression for a signal property.

func (*SignalManager) SetString

func (sm *SignalManager) SetString(property, value string) string

SetString returns an assignment expression with proper JS string quoting.

func (*SignalManager) Signal

func (sm *SignalManager) Signal(property string) string

Signal returns a reference to a signal property: "$componentID.property"

func (*SignalManager) Toggle

func (sm *SignalManager) Toggle(property string) string

Toggle returns an expression that flips a boolean signal.

type ToastLevel

type ToastLevel string

ToastLevel represents the severity of a toast notification.

const (
	ToastInfo    ToastLevel = "info"
	ToastSuccess ToastLevel = "success"
	ToastWarning ToastLevel = "warning"
	ToastError   ToastLevel = "error"
)

type ToastOption

type ToastOption func(*toastConfig)

ToastOption customizes a toast notification.

func WithToastAction

func WithToastAction(label, url string) ToastOption

WithToastAction adds an action button that triggers a Datastar GET. The toast stays until the action or close button is clicked.

func WithToastDuration

func WithToastDuration(ms int) ToastOption

WithToastDuration sets the auto-dismiss duration in milliseconds. Default is 3000ms. Use WithToastPersistent() to disable auto-dismiss.

func WithToastLink(text, url string) ToastOption

WithToastLink adds a clickable link to the toast message.

func WithToastPersistent

func WithToastPersistent() ToastOption

WithToastPersistent makes the toast stay until the user clicks the close button.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL