ds

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package ds provides helpers for building Datastar (https://data-star.dev/) reactive attributes.

This package includes:

  • Signal management: Signal, Signals, Computed, Bind, BindKey
  • Event handlers: On, OnClick, OnSubmit, OnInput, OnChange, OnLoad, OnIntersect, OnInterval, OnSignalPatch
  • Reactive display: Show, Text, Class, Classes, Style, Styles, Attribute, Attrs
  • DOM control: Ref, Indicator, IndicatorKey, Ignore, IgnoreSelf, IgnoreMorph, PreserveAttr, Effect, Init
  • HTTP actions: Get, Post, Put, Patch, Delete (and Dynamic variants)
  • HTTP options: RequestOptions, ContentType, FilterSignals, Headers, OpenWhenHidden, retry config
  • Core actions: Peek, SetAll, ToggleAll
  • Modifiers: Debounce, Throttle, Delay, Duration, Once, PreventDefault, ViewTransition, etc.

Pro attributes (require commercial license) are available in this package but documented as requiring a Datastar Pro license: Animate, CustomValidity, OnRAF (requestAnimationFrame), OnResize (element resize observation), Persist, QueryString, ReplaceURL, ScrollIntoView, ViewTransitionName.

Pro actions (require commercial license): Clipboard, ClipboardBase64, Fit, FitClamped, FitRounded, FitClampedRounded.

Pro Datastar attributes require a commercial license from https://data-star.dev/ These attributes provide additional functionality beyond the free tier.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Str creates a JavaScript string literal, properly escaped.
	Str = js.String
	// Int creates a JavaScript number literal from an integer.
	Int = js.Int
	// Int64 creates a JavaScript number literal from an int64.
	Int64 = js.Int64
	// Float creates a JavaScript number literal from a float64.
	Float = js.Float
	// Bool creates a JavaScript boolean literal.
	Bool = js.Bool
	// Null creates a JavaScript null literal.
	Null = js.Null
	// Undefined creates a JavaScript undefined literal.
	Undefined = js.Undefined
	// JSON creates a JavaScript value from a Go value using JSON encoding.
	JSON = js.JSON
	// Array creates a JavaScript array literal from expressions.
	Array = js.Array
	// Object creates a JavaScript object literal from key-value pairs.
	Object = js.Object
	// Pair creates a key-value pair for Object().
	Pair = js.Pair
	// Ident creates a JavaScript identifier reference.
	Ident = js.Ident
	// This creates the special "this" identifier.
	This = js.This
	// ToJS converts an expression to its JavaScript string representation.
	ToJS = js.ToJS
	// ToJSStmt converts a statement to its JavaScript string representation.
	ToJSStmt = js.ToJSStmt
)

Re-export js value constructors

View Source
var (
	Add             = js.Add
	Sub             = js.Sub
	Mul             = js.Mul
	Div             = js.Div
	Mod             = js.Mod
	Eq              = js.Eq
	NotEq           = js.NotEq
	Lt              = js.Lt
	LtEq            = js.LtEq
	Gt              = js.Gt
	GtEq            = js.GtEq
	JSAnd           = js.And
	JSOr            = js.Or
	JSNot           = js.Not
	Ternary         = js.Ternary
	NullishCoalesce = js.NullishCoalesce
	Group           = js.Group
)

Re-export js operators

View Source
var (
	Prop         = js.Prop
	Method       = js.Method
	Index        = js.Index
	Call         = js.Call
	New          = js.New
	OptionalProp = js.OptionalProp
	OptionalCall = js.OptionalCall
)

Re-export js property/method access

View Source
var (
	ExprStmt   = js.ExprStmt
	Let        = js.Let
	Const      = js.Const
	Assign     = js.Assign
	AddAssign  = js.AddAssign
	SubAssign  = js.SubAssign
	Incr       = js.Incr
	Decr       = js.Decr
	PreIncr    = js.PreIncr
	PreDecr    = js.PreDecr
	PostIncr   = js.PostIncr
	PostDecr   = js.PostDecr
	Return     = js.Return
	ReturnVoid = js.ReturnVoid
)

Re-export js statements

View Source
var (
	Console      = js.Console
	Document     = js.Document
	JSWindow     = js.Window
	Event        = js.Event
	JSConsoleLog = js.ConsoleLog
	ConsoleError = js.ConsoleError
	EventTarget  = js.EventTarget
	EventValue   = js.EventValue
)

Re-export js builtins

Functions

func ActionClipboard added in v0.2.0

func ActionClipboard(text js.Expr) js.Callable

ActionClipboard creates @clipboard(text) Datastar Pro action

func ActionClipboardBase64 added in v0.2.0

func ActionClipboardBase64(text js.Expr) js.Callable

ActionClipboardBase64 creates @clipboard(text, true) Datastar Pro action for Base64-decoded content

func ActionDelete added in v0.2.0

func ActionDelete(path js.Expr) js.Callable

ActionDelete creates @delete(path) Datastar action

func ActionFit added in v0.2.0

func ActionFit(v, oldMin, oldMax, newMin, newMax js.Expr) js.Callable

ActionFit creates @fit(v, oldMin, oldMax, newMin, newMax) Datastar Pro action

func ActionFitClamped added in v0.2.0

func ActionFitClamped(v, oldMin, oldMax, newMin, newMax js.Expr) js.Callable

ActionFitClamped creates @fit(v, oldMin, oldMax, newMin, newMax, true) with clamping

func ActionFitClampedRounded added in v0.2.0

func ActionFitClampedRounded(v, oldMin, oldMax, newMin, newMax js.Expr) js.Callable

ActionFitClampedRounded creates @fit(v, oldMin, oldMax, newMin, newMax, true, true) with clamping and rounding

func ActionFitRounded added in v0.2.0

func ActionFitRounded(v, oldMin, oldMax, newMin, newMax js.Expr) js.Callable

ActionFitRounded creates @fit(v, oldMin, oldMax, newMin, newMax, false, true) with rounding

func ActionGet added in v0.2.0

func ActionGet(path js.Expr) js.Callable

ActionGet creates @get(path) Datastar action

func ActionPatch added in v0.2.0

func ActionPatch(path js.Expr) js.Callable

ActionPatch creates @patch(path) Datastar action

func ActionPeek added in v0.2.0

func ActionPeek(expr js.Expr) js.Callable

ActionPeek creates @peek(() => expr) Datastar action for debugging

func ActionPost added in v0.2.0

func ActionPost(path js.Expr) js.Callable

ActionPost creates @post(path) Datastar action

func ActionPut added in v0.2.0

func ActionPut(path js.Expr) js.Callable

ActionPut creates @put(path) Datastar action

func ActionSetAll added in v0.2.0

func ActionSetAll(value js.Expr, filter *FilterOptions) js.Callable

ActionSetAll creates @setAll(value, filter) Datastar action

func ActionToggleAll added in v0.2.0

func ActionToggleAll(filter *FilterOptions) js.Callable

ActionToggleAll creates @toggleAll(filter) Datastar action

func And

func And(actions ...js.Expr) js.Callable

And creates a JavaScript && expression from multiple expressions. Example: And(Raw("$a"), Raw("$b")) produces: $a && $b

func Animate

func Animate(options ...AttrMutator) h.Attribute

Animate enables reactive animations on element attributes. Requires Datastar Pro license. Produces: data-animate

func Attribute

func Attribute(name string, value ...AttrMutator) h.Attribute

Attribute sets a single HTML attribute value reactively. Example: Attribute("title", Raw("$foo")) Produces: data-attr:title="$foo"

func Attrs

func Attrs(attrs map[string]string) h.Attribute

Attrs sets multiple HTML attributes reactively using object syntax. Example: Attrs(map[string]string{"title": "$foo", "disabled": "$bar"}) Produces: data-attr="{\"title\":\"$foo\",\"disabled\":\"$bar\"}"

func Bind

func Bind(signalName string) h.Attribute

Bind sets a signal to be used as the value of the element. Updates to the element will be reflected in the signal. The signal name will automatically be prefixed with "$".

func BindKey

func BindKey(signalName string, options ...AttrMutator) h.Attribute

BindKey creates a two-way data binding using key syntax (signal name in key). Example: BindKey("foo", Case(CamelCase)) Produces: data-bind:foo__case.camel

func Class

func Class(clsName string, value ...AttrMutator) h.Attribute

Class sets a class to be used as the value of the element. Updates to the class will be reflected in the element.

func Classes

func Classes(classes map[string]string) h.Attribute

Classes sets multiple CSS classes conditionally using object syntax. Example: Classes(map[string]string{"hidden": "$foo", "font-bold": "$bar"}) Produces: data-class="{\"hidden\":\"$foo\",\"font-bold\":\"$bar\"}"

func Computed

func Computed(name string, expression Value) h.Attribute

Computed creates a read-only signal computed from an expression. The signal auto-updates when dependencies change. Example: Computed("total", Raw("$price * $quantity")) Produces: data-computed:total="$price * $quantity"

func ComputedExpr

func ComputedExpr(name string, options ...AttrMutator) h.Attribute

ComputedExpr creates a computed signal with modifiers. Example: ComputedExpr("total", Case(CamelCase), Raw("$price * $quantity"))

func CustomValidity

func CustomValidity(expression ...AttrMutator) h.Attribute

CustomValidity adds custom validation messages to form inputs. Empty strings indicate valid; non-empty strings are shown as validation errors. Requires Datastar Pro license. Example: CustomValidity(Raw("$password === $confirmPassword ? ” : 'Passwords must match'")) Produces: data-custom-validity="$password === $confirmPassword ? ” : 'Passwords must match'"

func DatastarAction

func DatastarAction(name string, args ...js.Expr) js.Callable

DatastarAction creates a Datastar action call: @action(args...) Example: DatastarAction("get", js.String("/api")) produces @get("/api")

func Effect

func Effect(values ...AttrMutator) h.Attribute

Effect runs an expression reactively whenever dependencies change.

func Hide

func Hide() h.Attribute

Hide returns a style attribute that hides the element. For reactive hiding, use Show() with a negated condition instead.

func Ignore

func Ignore() h.Attribute

Ignore marks an element to be ignored by Datastar.

func IgnoreMorph

func IgnoreMorph() h.Attribute

IgnoreMorph prevents the element from being morphed during backend patches. Produces: data-ignore-morph

func IgnoreSelf

func IgnoreSelf() h.Attribute

IgnoreSelf ignores only the element itself, not its descendants. Produces: data-ignore__self

func Indicator

func Indicator(signalName string) h.Attribute

Indicator creates a fetch indicator signal.

func IndicatorKey

func IndicatorKey(signalName string, options ...AttrMutator) h.Attribute

IndicatorKey creates a fetch indicator signal using key syntax. Example: IndicatorKey("fetching", Case(CamelCase)) Produces: data-indicator:fetching__case.camel

func Init

func Init(options ...AttrMutator) h.Attribute

Init runs an expression when the element loads into the DOM. Example: Init(Raw("$count = 1")) Produces: data-init="$count = 1"

func JsonSignalsDebug

func JsonSignalsDebug(options *FilterOptions, modifiers ...AttrMutator) h.Attribute

JsonSignalsDebug displays reactive JSON stringified signals for debugging. Use with FilterOptions to include/exclude specific signals. Example: JsonSignalsDebug(nil) or JsonSignalsDebug(&FilterOptions{IncludeReg: ptr("user")}) Produces: data-json-signals or data-json-signals="{include: /user/}"

func Navigate(path string, values ...any) string

Navigate generates JavaScript to navigate to a URL. Example: Navigate("/users/%d", 42) produces: window.location.href = "/users/42"

func On

func On(eventName string, options ...AttrMutator) h.Attribute

Sets an action to be executed when the event is triggered. The action will be encoded as a JavaScript expression.

func OnChange

func OnChange(options ...AttrMutator) h.Attribute

Sets an action to be executed when the change is detected. The action will be encoded as a JavaScript expression.

func OnClick

func OnClick(options ...AttrMutator) h.Attribute

Sets an action to be executed when the element is clicked. The action will be encoded as a JavaScript expression.

func OnInput

func OnInput(options ...AttrMutator) h.Attribute

Sets an action to be executed when the input is changed. The action will be encoded as a JavaScript expression.

func OnIntersect

func OnIntersect(options ...AttrMutator) h.Attribute

OnIntersect runs an expression when the element intersects the viewport. Use Half() for 50% visibility, Full() for 100% visibility. Example: OnIntersect(Once(), Raw("$seen = true")) Produces: data-on-intersect__once="$seen = true"

func OnInterval

func OnInterval(options ...AttrMutator) h.Attribute

OnInterval executes an expression at regular intervals. Default interval is 1 second. Use Duration() to customize. Example: OnInterval(Duration(500*time.Millisecond), Raw("$count++")) Produces: data-on-interval__duration.500ms="$count++"

func OnLoad

func OnLoad(options ...AttrMutator) h.Attribute

Sets an action to be executed when the element is loaded. The action will be encoded as a JavaScript expression.

func OnRAF

func OnRAF(options ...AttrMutator) h.Attribute

OnRAF executes an expression on every requestAnimationFrame event. Requires Datastar Pro license. Example: OnRAF(Throttle(100*time.Millisecond), Raw("$frameCount++")) Produces: data-on-raf__throttle.100ms="$frameCount++"

func OnResize

func OnResize(options ...AttrMutator) h.Attribute

OnResize runs an expression when element dimensions change. Requires Datastar Pro license. Example: OnResize(Debounce(200*time.Millisecond), Raw("$width = el.offsetWidth")) Produces: data-on-resize__debounce.200ms="$width = el.offsetWidth"

func OnSignalPatch

func OnSignalPatch(options ...AttrMutator) h.Attribute

OnSignalPatch runs an expression whenever signals are updated. A "patch" variable is available containing signal patch details. Example: OnSignalPatch(Raw("console.log('Signal changed!')")) Produces: data-on-signal-patch="console.log('Signal changed!')"

func OnSignalPatchFilter

func OnSignalPatchFilter(options *FilterOptions) h.Attribute

OnSignalPatchFilter filters which signals trigger OnSignalPatch handlers. Example: OnSignalPatchFilter(&FilterOptions{IncludeReg: ptr("^counter$")}) Produces: data-on-signal-patch-filter="{include: /^counter$/}"

func OnSubmit

func OnSubmit(options ...AttrMutator) h.Attribute

Sets an action to be executed when the form is submitted. The action will be encoded as a JavaScript expression.

func Persist

func Persist(options *FilterOptions, modifiers ...AttrMutator) h.Attribute

Persist persists signals in local or session storage. Use Session() modifier for session storage instead of local storage. Requires Datastar Pro license. Example: Persist(nil) or Persist(&FilterOptions{IncludeReg: ptr("user")}) Produces: data-persist or data-persist="{include: /user/}"

func PersistKey

func PersistKey(key string, modifiers ...AttrMutator) h.Attribute

PersistKey persists signals using a custom storage key. Requires Datastar Pro license. Example: PersistKey("mykey", Session()) Produces: data-persist:mykey__session

func PreserveAttr

func PreserveAttr(attrs ...string) h.Attribute

PreserveAttr preserves specified attribute values during DOM morphing. Example: PreserveAttr("open", "class") Produces: data-preserve-attr="open class"

func QueryString

func QueryString(options *FilterOptions, modifiers ...AttrMutator) h.Attribute

QueryString syncs query parameters to/from signal values. Use Filter() to filter empty values, History() for browser history integration. Requires Datastar Pro license. Example: QueryString(nil) or QueryString(&FilterOptions{IncludeReg: ptr("search")}) Produces: data-query-string or data-query-string="{include: /search/}"

func Ref

func Ref(signalName string, options ...AttrMutator) h.Attribute

Ref creates a signal referencing a DOM element. Example: Ref("myElement") Produces: data-ref:myElement

func ReplaceURL

func ReplaceURL(expression ...AttrMutator) h.Attribute

ReplaceURL replaces the browser URL without page reload. Accepts relative or absolute URLs as evaluated expressions. Requires Datastar Pro license. Example: ReplaceURL(Raw("`/page${$page}`")) Produces: data-replace-url="`/page${$page}`"

func ScrollIntoView

func ScrollIntoView(options ...AttrMutator) h.Attribute

ScrollIntoView scrolls the element into viewport view. Use scroll behavior and alignment modifiers. Requires Datastar Pro license. Example: ScrollIntoView(Smooth(), VCenter()) Produces: data-scroll-into-view__smooth__vcenter

func Show

func Show(value ...AttrMutator) h.Attribute

Show conditionally shows/hides the element based on a signal.

func Signal

func Signal(name string, defaultJsValue any) h.Attribute

Signal defines a signal with a default value. The signal's default value will be encoded as a JSON value. The signal name will automatically be prefixed with "$".

func SignalExpr

func SignalExpr(name string, defaultExpression Value) h.Attribute

SignalExpr sets a signal to an arbitrary JavaScript expression. The signal's default value will be appended to the attribute name. The signal name will automatically be prefixed with "$".

func Signals

func Signals(signals map[string]any) h.Attribute

Signals defines multiple signals with default values using object syntax. The signals will be encoded as a JSON object. Example: Signals(map[string]any{"foo": 1, "bar": "hello"}) Produces: data-signals="{\"foo\":1,\"bar\":\"hello\"}"

func Style

func Style(property string, expression ...AttrMutator) h.Attribute

Style sets an inline CSS style property reactively. Example: Style("background-color", Raw("$isRed ? 'red' : 'blue'")) Produces: data-style:background-color="$isRed ? 'red' : 'blue'"

func Styles

func Styles(styles map[string]string) h.Attribute

Styles sets multiple inline CSS styles reactively using object syntax. Example: Styles(map[string]string{"display": "$hidden ? 'none' : 'block'", "color": "$red ? 'red' : 'green'"})

func Text

func Text(value ...AttrMutator) h.Attribute

Text sets the text of the element to be the value of the signal. Updates to the signal will be reflected in the element.

func ViewTransitionName

func ViewTransitionName(expression ...AttrMutator) h.Attribute

ViewTransitionName sets explicit view-transition-name for CSS animations. Requires Datastar Pro license. Example: ViewTransitionName(Raw("$itemId")) Produces: data-view-transition="$itemId"

func WithChains

func WithChains(action js.Callable, chains ...PromiseChain) js.Callable

WithChains adds promise chains to a Datastar action, returning a new Callable

Types

type AttrFunc

type AttrFunc func(*attrBuilder)

AttrFunc is a function that implements AttrMutator.

func (AttrFunc) Modify

func (f AttrFunc) Modify(attr *attrBuilder)

type AttrMutator

type AttrMutator interface{ Modify(*attrBuilder) }

AttrMutator modifies an attribute being built (name and/or statements).

func AndMutator

func AndMutator(actions ...js.Expr) AttrMutator

AndMutator creates an AttrMutator that combines expressions with &&. Example: AndMutator(Raw("$a"), Raw("$b")) produces an AttrMutator.

func Auto

func Auto() AttrMutator

Auto uses browser default scrolling behavior.

func Capture

func Capture() AttrMutator

Specifies that the event should not be captured. Only works for built-in events.

func Case

func Case(casing SignalCasing) AttrMutator

Specifies the casing of the signal/event name

func ConsoleLog

func ConsoleLog(values ...js.Expr) AttrMutator

ConsoleLog creates an AttrMutator that logs values to the console. Example: ConsoleLog(Signal("value"), Str("clicked"))

func Debounce

func Debounce(d time.Duration, opts ...TimingMutatorFunc) AttrMutator

Debounces the events triggered

func Delay

func Delay(d time.Duration) AttrMutator

Specifies the delay of the event triggered

func Duration

func Duration(d time.Duration, opts ...DurationMutatorFunc) AttrMutator

Duration sets the interval timing for data-on-interval. Default is 1 second if not specified. Example: Duration(500*time.Millisecond) produces __duration.500ms Example: Duration(2*time.Second, DurationLeading()) produces __duration.2s.leading

func Exit

func Exit() AttrMutator

Exit triggers when element exits viewport instead of entering. Used with data-on-intersect to detect when an element leaves view.

func Filter

func Filter() AttrMutator

Filter filters out empty values for QueryString.

func FilterOptionsValue

func FilterOptionsValue(o *FilterOptions) AttrMutator

FilterOptionsValue returns an AttrMutator that outputs FilterOptions as a JS object with regex literals.

func Focus

func Focus() AttrMutator

Focus focuses the element after scrolling into view.

func Full

func Full() AttrMutator

Full triggers intersection at 100% element visibility.

func HCenter

func HCenter() AttrMutator

HCenter aligns element to center of horizontal viewport.

func HEnd

func HEnd() AttrMutator

HEnd aligns element to end of horizontal viewport.

func HNearest

func HNearest() AttrMutator

HNearest aligns element to nearest edge of horizontal viewport.

func HStart

func HStart() AttrMutator

HStart aligns element to start of horizontal viewport.

func Half

func Half() AttrMutator

Half triggers intersection at 50% element visibility.

func History

func History() AttrMutator

History enables browser history integration for QueryString.

func IfMissing

func IfMissing() AttrMutator

IfMissing only patches signals if the keys don't already exist. Used with Signal/Signals attributes.

func Instant

func Instant() AttrMutator

Instant enables instant scrolling behavior.

func Once

func Once() AttrMutator

Prevents the event from being triggered multiple times. Only works for built-in events.

func Outside

func Outside() AttrMutator

Triggers when the event is triggered outside of the element

func Passive

func Passive() AttrMutator

Specifies that the event should not be canceled. Only works for built-in events.

func PreventDefault

func PreventDefault() AttrMutator

Prevents the default event behavior.

func Self

func Self() AttrMutator

Self modifier for data-ignore - ignores only the element, not descendants.

func Session

func Session() AttrMutator

Session uses session storage instead of local storage for Persist.

func SetSignal

func SetSignal(signalName string, jsValue any) AttrMutator

SetSignal creates an AttrMutator that sets a signal to a value. Use SetSignalExpr if you need to set the signal to a more complex expression. The signalName will automatically be prefixed with "$".

func SetSignalExpr

func SetSignalExpr(signalName string, expression js.Expr) AttrMutator

SetSignalExpr creates an AttrMutator that sets a signal to an expression. The signalName will automatically be prefixed with "$".

func Smooth

func Smooth() AttrMutator

Smooth enables smooth scrolling behavior.

func StopPropagation

func StopPropagation() AttrMutator

Stops the event from propagating

func Terse

func Terse() AttrMutator

Terse outputs compact JSON without whitespace for data-json-signals debug.

func Threshold

func Threshold(value float64) AttrMutator

Threshold sets a custom visibility threshold (0.0-1.0) for intersection. Use instead of Half() or Full() for precise control. Example: Threshold(0.25) triggers at 25% visibility.

func Throttle

func Throttle(d time.Duration, opts ...TimingMutatorFunc) AttrMutator

Throttles the events triggered

func VCenter

func VCenter() AttrMutator

VCenter aligns element to center of vertical viewport.

func VEnd

func VEnd() AttrMutator

VEnd aligns element to end of vertical viewport.

func VNearest

func VNearest() AttrMutator

VNearest aligns element to nearest edge of vertical viewport.

func VStart

func VStart() AttrMutator

VStart aligns element to start of vertical viewport.

func ViewTransition

func ViewTransition() AttrMutator

Wraps expression in document.startViewTransition() when View Transition API is supported

func Window

func Window() AttrMutator

Attaches event listener to the window element

type Callable

type Callable = js.Callable

Re-export js types for convenience

type DurationMutatorFunc

type DurationMutatorFunc func(*strings.Builder)

func DurationLeading

func DurationLeading() DurationMutatorFunc

DurationLeading causes the first interval to fire immediately.

type Expr

type Expr = js.Expr

Re-export js types for convenience

type ExprMutator

type ExprMutator struct {
	Expr js.Expr
}

ExprMutator wraps a js.Expr to satisfy AttrMutator

func E

func E(expr js.Expr) ExprMutator

E wraps a js.Expr to use as an AttrMutator Example: OnClick(PreventDefault(), E(Signal("count")))

func (ExprMutator) Modify

func (e ExprMutator) Modify(attr *attrBuilder)

type FilterOptions

type FilterOptions struct {
	IncludeReg *string
	ExcludeReg *string
}

FilterOptions specifies regex patterns for filtering signals.

type KV

type KV = js.KV

Re-export js types for convenience

type PromiseChain

type PromiseChain interface {
	// contains filtered or unexported methods
}

PromiseChain represents a chainable action for HTTP requests (then/catch)

func CatchChain

func CatchChain(expr js.Expr) PromiseChain

CatchChain creates a .catch() chain for error handling

func OnFailure

func OnFailure(expr Value) PromiseChain

OnFailure creates a .catch() chain for error handling. This is an alias for CatchChain for backward compatibility.

func OnSuccess

func OnSuccess(expr Value) PromiseChain

OnSuccess creates a .then() chain for successful request handling. This is an alias for ThenChain for backward compatibility.

func ThenChain

func ThenChain(expr js.Expr) PromiseChain

ThenChain creates a .then() chain for successful request handling

type RequestOption

type RequestOption interface {
	// contains filtered or unexported methods
}

RequestOption is an option for HTTP request actions.

type RequestOptionsBuilder

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

RequestOptionsBuilder collects request options.

func RequestOptions

func RequestOptions() RequestOptionsBuilder

RequestOptions creates a builder for HTTP request options. Use with GetWithOptions, PostWithOptions, etc. Example: GetWithOptions("/api", RequestOptions().ContentType("form").OpenWhenHidden(true))

func (RequestOptionsBuilder) ContentType

ContentType sets the request content type. Values: "json" (default) or "form"

func (RequestOptionsBuilder) FilterSignals

FilterSignals filters which signals are sent with the request.

func (RequestOptionsBuilder) Headers

Headers sets custom HTTP headers for the request.

func (RequestOptionsBuilder) OpenWhenHidden

func (b RequestOptionsBuilder) OpenWhenHidden(open bool) RequestOptionsBuilder

OpenWhenHidden keeps the connection alive when the tab is hidden.

func (RequestOptionsBuilder) Payload

Payload overrides the request body with custom JSON data. Use for POST/PUT/PATCH requests when you need a custom payload.

func (RequestOptionsBuilder) RequestCancellation

func (b RequestOptionsBuilder) RequestCancellation(mode string) RequestOptionsBuilder

RequestCancellation sets the request cancellation mode. Values: "auto" (default), "disabled"

func (RequestOptionsBuilder) Retry

Retry sets the retry strategy for the request. Values: "auto" (default, retry on network errors), "error" (retry on errors and non-2xx), "always" (always retry), "never" (never retry)

func (RequestOptionsBuilder) RetryInterval

func (b RequestOptionsBuilder) RetryInterval(ms int) RequestOptionsBuilder

RetryInterval sets the retry interval in milliseconds (default: 1000).

func (RequestOptionsBuilder) RetryMaxCount

func (b RequestOptionsBuilder) RetryMaxCount(count int) RequestOptionsBuilder

RetryMaxCount sets the maximum number of retry attempts (default: 10).

func (RequestOptionsBuilder) RetryMaxWaitMs

func (b RequestOptionsBuilder) RetryMaxWaitMs(ms int) RequestOptionsBuilder

RetryMaxWaitMs sets the maximum wait between retries in milliseconds (default: 30000).

func (RequestOptionsBuilder) RetryScaler

func (b RequestOptionsBuilder) RetryScaler(scaler float64) RequestOptionsBuilder

RetryScaler sets the exponential backoff multiplier (default: 2).

func (RequestOptionsBuilder) Selector

Selector specifies a CSS selector for form elements (when contentType is 'form').

type SignalCasing

type SignalCasing string
const (
	CamelCase  SignalCasing = "camel"  // myEvent
	KebabCase  SignalCasing = "kebab"  // my-event
	SnakeCase  SignalCasing = "snake"  // my_event
	PascalCase SignalCasing = "pascal" // MyEvent
)

type Stmt

type Stmt = js.Stmt

Re-export js types for convenience

type Stringer

type Stringer interface {
	String() string
}

type TimingMutatorFunc

type TimingMutatorFunc func(*strings.Builder)

func Leading

func Leading() TimingMutatorFunc

Leading causes the first trigger to fire immediately (for throttle)

func NoLeading

func NoLeading() TimingMutatorFunc

NoLeading prevents the first trigger from firing immediately (for debounce)

func NoTrailing

func NoTrailing() TimingMutatorFunc

NoTrailing prevents the final trigger from firing after the delay (for debounce)

func Trailing

func Trailing() TimingMutatorFunc

Trailing causes the final trigger to fire after the delay (for throttle)

type Value

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

Value wraps a js.Expr and implements AttrMutator. This allows expressions to be used directly with Datastar attribute functions.

func Clipboard

func Clipboard(text Value) Value

Clipboard copies text to the clipboard. Requires Datastar Pro license. Example: OnClick(Clipboard(Str("Hello, world!"))) Produces: data-on:click="@clipboard('Hello, world!')"

func ClipboardBase64

func ClipboardBase64(text Value) Value

ClipboardBase64 copies Base64-decoded text to the clipboard. Useful for content with special characters, quotes, or code fragments. Requires Datastar Pro license. Example: OnClick(ClipboardBase64(Str("SGVsbG8sIHdvcmxkIQ=="))) Produces: data-on:click="@clipboard('SGVsbG8sIHdvcmxkIQ==', true)"

func Delete

func Delete(path string, chains ...PromiseChain) Value

Delete performs a DELETE request. Returns a Value that can be used with event handlers.

func DeleteDynamic

func DeleteDynamic(path Value, chains ...PromiseChain) Value

DeleteDynamic performs a DELETE request with a dynamic path. Returns a Value that can be used with event handlers.

func DeleteWithOptions

func DeleteWithOptions(path string, opts RequestOptionsBuilder, chains ...PromiseChain) Value

DeleteWithOptions performs a DELETE request with options.

func Fit

func Fit(v, oldMin, oldMax, newMin, newMax Value) Value

Fit linearly interpolates a value from one range to another. Requires Datastar Pro license. Syntax: @fit(v, oldMin, oldMax, newMin, newMax) Example: Computed("rgb", Fit(Raw("$slider"), Raw("0"), Raw("100"), Raw("0"), Raw("255")))

func FitClamped

func FitClamped(v, oldMin, oldMax, newMin, newMax Value) Value

FitClamped linearly interpolates with clamping to keep results within the target range. Requires Datastar Pro license. Syntax: @fit(v, oldMin, oldMax, newMin, newMax, true)

func FitClampedRounded

func FitClampedRounded(v, oldMin, oldMax, newMin, newMax Value) Value

FitClampedRounded linearly interpolates with both clamping and rounding. Requires Datastar Pro license. Syntax: @fit(v, oldMin, oldMax, newMin, newMax, true, true)

func FitRounded

func FitRounded(v, oldMin, oldMax, newMin, newMax Value) Value

FitRounded linearly interpolates with rounding to nearest integer. Requires Datastar Pro license. Syntax: @fit(v, oldMin, oldMax, newMin, newMax, false, true)

func Get

func Get(path string, chains ...PromiseChain) Value

Get performs a GET request. Returns a Value that can be used with event handlers.

func GetDynamic

func GetDynamic(path Value, chains ...PromiseChain) Value

GetDynamic performs a GET request with a dynamic path. Returns a Value that can be used with event handlers.

func GetWithOptions

func GetWithOptions(path string, opts RequestOptionsBuilder, chains ...PromiseChain) Value

GetWithOptions performs a GET request with options.

func JsonValue

func JsonValue(value any) Value

JsonValue creates a JavaScript value from a Go value using JSON encoding. Panics if the value cannot be marshaled to JSON.

func Patch

func Patch(path string, chains ...PromiseChain) Value

Patch performs a PATCH request. Returns a Value that can be used with event handlers.

func PatchDynamic

func PatchDynamic(path Value, chains ...PromiseChain) Value

PatchDynamic performs a PATCH request with a dynamic path. Returns a Value that can be used with event handlers.

func PatchWithOptions

func PatchWithOptions(path string, opts RequestOptionsBuilder, chains ...PromiseChain) Value

PatchWithOptions performs a PATCH request with options.

func Peek

func Peek(action Value) Value

Peek creates a @peek(() => expr) Datastar action for debugging. Returns a Value that can be used with event handlers.

func Post

func Post(path string, chains ...PromiseChain) Value

Post performs a POST request. Returns a Value that can be used with event handlers.

func PostDynamic

func PostDynamic(path Value, chains ...PromiseChain) Value

PostDynamic performs a POST request with a dynamic path. Returns a Value that can be used with event handlers.

func PostWithOptions

func PostWithOptions(path string, opts RequestOptionsBuilder, chains ...PromiseChain) Value

PostWithOptions performs a POST request with options.

func Put

func Put(path string, chains ...PromiseChain) Value

Put performs a PUT request. Returns a Value that can be used with event handlers.

func PutDynamic

func PutDynamic(path Value, chains ...PromiseChain) Value

PutDynamic performs a PUT request with a dynamic path. Returns a Value that can be used with event handlers.

func PutWithOptions

func PutWithOptions(path string, opts RequestOptionsBuilder, chains ...PromiseChain) Value

PutWithOptions performs a PUT request with options.

func Raw

func Raw(s string) Value

Raw injects raw JavaScript code. This is the escape hatch for arbitrary JavaScript. Use with caution as this bypasses type safety.

func SetAll

func SetAll(value Value, options *FilterOptions) Value

SetAll creates a @setAll(value, filter) Datastar action. Returns a Value that can be used with event handlers.

func SignalRef

func SignalRef(name string) Value

SignalRef creates a Datastar signal reference: $name Use this to reference a signal value in expressions. Example: SignalRef("count") produces $count

func ToggleAll

func ToggleAll(options *FilterOptions) Value

ToggleAll creates a @toggleAll(filter) Datastar action. Returns a Value that can be used with event handlers.

func V

func V(expr js.Expr) Value

V wraps a js.Expr as a Value that can be used with Datastar attributes.

func (Value) Expr

func (v Value) Expr() js.Expr

Expr returns the underlying js.Expr

func (Value) Modify

func (v Value) Modify(attr *attrBuilder)

Modify implements AttrMutator

Jump to

Keyboard shortcuts

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