Skip to main content

Stateful

Struct Stateful 

Source
pub struct Stateful<S>{ /* private fields */ }
Expand description

A stateful element with user-defined state type

The state type S must implement StateTransitions to define how events cause state changes. Use the on_state callback to apply visual changes based on state using pattern matching.

§Example

use blinc_layout::prelude::*;

let button = Stateful::new(ButtonState::Idle)
    .w(100.0).h(40.0)
    .on_state(|state, div| match state {
        ButtonState::Idle => { *div = div.swap().bg(Color::BLUE); }
        ButtonState::Hovered => { *div = div.swap().bg(Color::CYAN); }
        ButtonState::Pressed => { *div = div.swap().bg(Color::BLUE).scale(0.97); }
        ButtonState::Disabled => { *div = div.swap().bg(Color::GRAY); }
    });

Implementations§

Source§

impl<S> Stateful<S>

Source

pub fn new(initial_state: S) -> Stateful<S>

Create a new stateful element with initial state

Source

pub fn with_shared_state( shared_state: Arc<Mutex<StatefulInner<S>>>, ) -> Stateful<S>

Create a stateful element with externally-provided shared state

Use this when you need state to persist across rebuilds. The shared state can come from WindowedContext::use_stateful_state() or be created manually.

§Example
// State persists across rebuilds
let state = ctx.use_stateful_state("my_button", ButtonState::Idle);
button()
    .with_state(state)
    .on_state(|state, div| { ... })
Source

pub fn shared_state(&self) -> Arc<Mutex<StatefulInner<S>>>

Get a clone of the shared state handle

This can be stored externally for state persistence across rebuilds.

Source

pub fn default_state(self, state: S) -> Stateful<S>

Set the initial/default state

This is useful when using the generic stateful() constructor with a custom state type.

§Example
stateful()
    .default_state(MyState::Ready)
    .on_state(|state, div| { ... })
Source

pub fn state(&self) -> S

Get the current state

Source

pub fn inner_render_props(&self) -> RenderProps

Get the render props of the inner Div

This allows accessing the accumulated layout properties.

Source

pub fn inner_layout_style(&self) -> Option<Style>

Get a clone of the inner Div’s layout style

This allows capturing the final taffy Style after all builder methods have been applied.

Source

pub fn apply_callback(&self)

Apply the state callback to update the inner div

This is useful when you need to manually trigger a callback application, for example in a custom ElementBuilder::build() implementation.

Source

pub fn set_state(&self, state: S)

Set the current state directly

Source

pub fn on_state<F>(self, callback: F) -> Stateful<S>
where F: Fn(&S, &mut Div) + Send + Sync + 'static,

Set the state change callback

The callback receives the current state for pattern matching and a mutable reference to a Div for applying visual changes. The callback is immediately applied to set the initial visual state, and event handlers are automatically registered to trigger state transitions.

§Example
.on_state(|state, div| match state {
    ButtonState::Idle => { *div = div.swap().bg(Color::BLUE); }
    ButtonState::Hovered => { *div = div.swap().bg(Color::CYAN); }
    // ...
})
Source

pub fn deps(self, signals: &[SignalId]) -> Stateful<S>

Set signal dependencies for this stateful element

When any of the specified signals change, the on_state callback will be re-run to update the element’s visual props.

§Example
let direction = ctx.use_state_keyed("direction", || Direction::Vertical);

stateful(button_state)
    .deps(&[direction.signal_id()])
    .on_state(move |state, div| {
        // Read direction here - will be current on each refresh
        let label = match direction.get() { ... };
        div.set_child(span(label));
    })
Source

pub fn ensure_state_handlers_registered(&self)

Ensure state transition handlers are registered (idempotent)

This is public so that wrappers like Button can call it to ensure the hover/press state handlers are registered even when not using on_state().

Source

pub fn dispatch_state(&self, new_state: S) -> bool

Dispatch a new state

Updates the current state and applies the callback if the state changed. Uses incremental prop/subtree updates instead of full tree rebuild. Returns true if the state changed.

Source

pub fn handle_event(&self, event: u32) -> bool

Handle an event and potentially transition state

Returns true if the state changed.

Source

pub fn id(self, id: &str) -> Stateful<S>

Source

pub fn class(self, name: &str) -> Stateful<S>

Add a CSS class name for selector matching

Source

pub fn w(self, px: f32) -> Stateful<S>

Set width (builder pattern)

Source

pub fn h(self, px: f32) -> Stateful<S>

Set height (builder pattern)

Source

pub fn w_full(self) -> Stateful<S>

Set width to 100% (builder pattern)

Source

pub fn min_w(self, px: f32) -> Stateful<S>

Set minimum width (builder pattern)

Source

pub fn h_full(self) -> Stateful<S>

Set height to 100% (builder pattern)

Source

pub fn size(self, w: f32, h: f32) -> Stateful<S>

Set both width and height (builder pattern)

Source

pub fn square(self, size: f32) -> Stateful<S>

Set square size (builder pattern)

Source

pub fn flex_row(self) -> Stateful<S>

Set flex direction to row (builder pattern)

Source

pub fn flex_col(self) -> Stateful<S>

Set flex direction to column (builder pattern)

Source

pub fn flex_grow(self) -> Stateful<S>

Set flex grow (builder pattern)

Source

pub fn w_fit(self) -> Stateful<S>

Set width to fit content (builder pattern)

Source

pub fn h_fit(self) -> Stateful<S>

Set height to fit content (builder pattern)

Source

pub fn p(self, units: f32) -> Stateful<S>

Set padding all sides (builder pattern)

Source

pub fn px(self, units: f32) -> Stateful<S>

Set horizontal padding (builder pattern)

Source

pub fn py(self, units: f32) -> Stateful<S>

Set vertical padding (builder pattern)

Source

pub fn padding(self, len: Length) -> Stateful<S>

Set padding using a semantic Length value (builder pattern)

Source

pub fn padding_x(self, len: Length) -> Stateful<S>

Set horizontal padding using a semantic Length value (builder pattern)

Source

pub fn padding_y(self, len: Length) -> Stateful<S>

Set vertical padding using a semantic Length value (builder pattern)

Source

pub fn pt(self, units: f32) -> Stateful<S>

Set padding top (builder pattern)

Source

pub fn pb(self, units: f32) -> Stateful<S>

Set padding bottom (builder pattern)

Source

pub fn pl(self, units: f32) -> Stateful<S>

Set padding left (builder pattern)

Source

pub fn pr(self, units: f32) -> Stateful<S>

Set padding right (builder pattern)

Source

pub fn mt(self, units: f32) -> Stateful<S>

Set margin top (builder pattern)

Source

pub fn mb(self, units: f32) -> Stateful<S>

Set margin bottom (builder pattern)

Source

pub fn ml(self, units: f32) -> Stateful<S>

Set margin left (builder pattern)

Source

pub fn mr(self, units: f32) -> Stateful<S>

Set margin right (builder pattern)

Source

pub fn mx(self, units: f32) -> Stateful<S>

Set horizontal margin (builder pattern)

Source

pub fn my(self, units: f32) -> Stateful<S>

Set vertical margin (builder pattern)

Source

pub fn m(self, units: f32) -> Stateful<S>

Set margin all sides (builder pattern)

Source

pub fn gap(self, units: f32) -> Stateful<S>

Set gap (builder pattern)

Source

pub fn items_start(self) -> Stateful<S>

Align items to start (builder pattern)

Source

pub fn items_center(self) -> Stateful<S>

Center items (builder pattern)

Source

pub fn items_end(self) -> Stateful<S>

Align items to end (builder pattern)

Source

pub fn justify_start(self) -> Stateful<S>

Justify content start (builder pattern)

Source

pub fn justify_center(self) -> Stateful<S>

Center justify (builder pattern)

Source

pub fn justify_end(self) -> Stateful<S>

Justify content end (builder pattern)

Source

pub fn justify_between(self) -> Stateful<S>

Space between (builder pattern)

Source

pub fn bg(self, color: impl Into<Brush>) -> Stateful<S>

Set background (builder pattern)

Source

pub fn rounded(self, radius: f32) -> Stateful<S>

Set corner radius (builder pattern)

Source

pub fn border(self, width: f32, color: Color) -> Stateful<S>

Set border with color and width (builder pattern)

Source

pub fn border_color(self, color: Color) -> Stateful<S>

Set border color only (builder pattern)

Source

pub fn border_width(self, width: f32) -> Stateful<S>

Set border width only (builder pattern)

Source

pub fn shadow(self, shadow: Shadow) -> Stateful<S>

Set shadow (builder pattern)

Source

pub fn shadow_sm(self) -> Stateful<S>

Set small shadow (builder pattern)

Source

pub fn shadow_md(self) -> Stateful<S>

Set medium shadow (builder pattern)

Source

pub fn shadow_lg(self) -> Stateful<S>

Set large shadow (builder pattern)

Source

pub fn shadow_xl(self) -> Stateful<S>

Set extra-large shadow (builder pattern)

Source

pub fn opacity(self, opacity: f32) -> Stateful<S>

Set opacity (builder pattern)

Source

pub fn flex_shrink(self) -> Stateful<S>

Set flex shrink (builder pattern)

Source

pub fn flex_shrink_0(self) -> Stateful<S>

Set flex shrink to 0 (no shrinking) (builder pattern)

Source

pub fn transform(self, transform: Transform) -> Stateful<S>

Set transform (builder pattern)

Source

pub fn overflow_clip(self) -> Stateful<S>

Set overflow to clip (clips children to container bounds)

Source

pub fn cursor(self, cursor: CursorStyle) -> Stateful<S>

Set cursor style (builder pattern)

Source

pub fn cursor_pointer(self) -> Stateful<S>

Set cursor to pointer (hand) - convenience for clickable elements

Source

pub fn cursor_text(self) -> Stateful<S>

Set cursor to text (I-beam) - for text input areas

Source

pub fn absolute(self) -> Stateful<S>

Set position to absolute (builder pattern)

Source

pub fn relative(self) -> Stateful<S>

Set position to relative (builder pattern)

Source

pub fn top(self, px: f32) -> Stateful<S>

Set top position (builder pattern)

Source

pub fn bottom(self, px: f32) -> Stateful<S>

Set bottom position (builder pattern)

Source

pub fn left(self, px: f32) -> Stateful<S>

Set left position (builder pattern)

Source

pub fn right(self, px: f32) -> Stateful<S>

Set right position (builder pattern)

Source

pub fn child(self, child: impl ElementBuilder + 'static) -> Stateful<S>

Add child (builder pattern)

Source

pub fn children<I>(self, children: I) -> Stateful<S>
where I: IntoIterator, <I as IntoIterator>::Item: ElementBuilder + 'static,

Add children (builder pattern)

Source

pub fn on_click<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a click handler (builder pattern)

Source

pub fn on_mouse_down<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a mouse down handler (builder pattern)

Source

pub fn on_mouse_up<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a mouse up handler (builder pattern)

Source

pub fn on_hover_enter<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a hover enter handler (builder pattern)

Source

pub fn on_hover_leave<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a hover leave handler (builder pattern)

Source

pub fn on_focus<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a focus handler (builder pattern)

Source

pub fn on_blur<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a blur handler (builder pattern)

Source

pub fn on_mount<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a mount handler (builder pattern)

Source

pub fn on_unmount<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register an unmount handler (builder pattern)

Source

pub fn on_key_down<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a key down handler (builder pattern)

Source

pub fn on_key_up<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a key up handler (builder pattern)

Source

pub fn on_scroll<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a scroll handler (builder pattern)

Source

pub fn on_mouse_move<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a mouse move handler (builder pattern)

Source

pub fn on_drag<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a drag handler (builder pattern)

Drag events are emitted when the mouse moves while a button is pressed. Use EventContext::local_x/y to get the current position during drag.

Source

pub fn on_drag_end<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a drag end handler (builder pattern)

Called when the mouse button is released after a drag operation.

Source

pub fn on_resize<F>(self, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a resize handler (builder pattern)

Source

pub fn on_event<F>(self, event_type: u32, handler: F) -> Stateful<S>
where F: Fn(&EventContext) + Send + Sync + 'static,

Register a handler for a specific event type (builder pattern)

Source

pub fn on_layout<F>(self, callback: F) -> Stateful<S>
where F: Fn(ElementBounds) + Send + Sync + 'static,

Set a layout callback that fires synchronously after each layout computation

Unlike on_ready which fires once with a delay, on_layout fires immediately and synchronously every time the element’s bounds are computed. This is useful for position-dependent operations like dropdown positioning.

§Example
let trigger_bounds: State<(f32, f32, f32, f32)> = ...;
Stateful::new(())
    .w(200.0)
    .h(40.0)
    .on_layout(move |bounds| {
        trigger_bounds.set((bounds.x, bounds.y, bounds.width, bounds.height));
    })
Source

pub fn bounds_storage(&self) -> Arc<Mutex<Option<ElementBounds>>>

Get the layout bounds storage for reading current bounds

Returns a shared reference to the storage that is updated after each layout. Use this to read the current bounds in event handlers.

Source

pub fn bind(self, element_ref: &ElementRef<Stateful<S>>) -> BoundStateful<S>

Bind this element to an ElementRef for external access

Returns a BoundStateful that continues the fluent API chain while also making the element accessible via the ref.

§Example
let button_ref = ElementRef::<Button>::new();

let ui = div()
    .child(
        button()
            .bind(&button_ref)  // Binds and continues chain
            .on_state(|state, div| { ... })
    );

// Later, access via the ref
button_ref.with_mut(|btn| {
    btn.dispatch_state(ButtonState::Pressed);
});

Trait Implementations§

Source§

impl<S> Default for Stateful<S>

Source§

fn default() -> Stateful<S>

Returns the “default value” for a type. Read more
Source§

impl<S> ElementBuilder for Stateful<S>

Source§

fn build(&self, tree: &mut LayoutTree) -> LayoutNodeId

Build this element into a layout tree, returning the node ID
Source§

fn render_props(&self) -> RenderProps

Get the render properties for this element
Source§

fn children_builders(&self) -> &[Box<dyn ElementBuilder>]

Get children builders (for recursive traversal)
Source§

fn element_type_id(&self) -> ElementTypeId

Get the element type identifier
Source§

fn element_id(&self) -> Option<&str>

Get the element ID for selector API queries Read more
Source§

fn element_classes(&self) -> &[String]

Get the element’s CSS class list for selector matching
Source§

fn event_handlers(&self) -> Option<&EventHandlers>

Get event handlers for this element Read more
Source§

fn layout_style(&self) -> Option<&Style>

Get the layout style for this element Read more
Source§

fn layout_bounds_storage(&self) -> Option<Arc<Mutex<Option<ElementBounds>>>>

Get layout bounds storage for this element Read more
Source§

fn layout_bounds_callback( &self, ) -> Option<Arc<dyn Fn(ElementBounds) + Send + Sync>>

Get layout bounds change callback for this element Read more
Source§

fn layout_animation_config(&self) -> Option<LayoutAnimationConfig>

Get layout animation configuration for this element Read more
Source§

fn visual_animation_config(&self) -> Option<VisualAnimationConfig>

Get visual animation config for new FLIP-style animations (read-only layout) Read more
Source§

fn scroll_physics(&self) -> Option<Arc<Mutex<ScrollPhysics>>>

Get scroll physics handle if this is a scroll element
Source§

fn text_render_info(&self) -> Option<TextRenderInfo>

Get text render info if this is a text element
Source§

fn styled_text_render_info(&self) -> Option<StyledTextRenderInfo>

Get styled text render info if this is a styled text element (rich_text)
Source§

fn svg_render_info(&self) -> Option<SvgRenderInfo>

Get SVG render info if this is an SVG element
Source§

fn image_render_info(&self) -> Option<ImageRenderInfo>

Get image render info if this is an image element
Source§

fn canvas_render_info( &self, ) -> Option<Rc<dyn Fn(&mut dyn DrawContext, CanvasBounds)>>

Get canvas render info if this is a canvas element
Source§

fn scroll_info(&self) -> Option<ScrollRenderInfo>

Get scroll render info if this is a scroll element
Source§

fn motion_animation_for_child( &self, _child_index: usize, ) -> Option<MotionAnimation>

Get motion animation config for a child at given index Read more
Source§

fn motion_bindings(&self) -> Option<MotionBindings>

Get motion bindings for continuous animation Read more
Source§

fn motion_stable_id(&self) -> Option<&str>

Get stable ID for motion animation tracking Read more
Source§

fn motion_should_replay(&self) -> bool

Check if this motion should replay its animation Read more
Source§

fn motion_is_suspended(&self) -> bool

Check if this motion should start in suspended state Read more
Source§

fn motion_is_exiting(&self) -> bool

👎Deprecated since 0.1.0:

Use query_motion(key).exit() to explicitly trigger motion exit

DEPRECATED: Check if this motion should start its exit animation Read more
Source§

fn semantic_type_name(&self) -> Option<&'static str>

Semantic HTML-like tag name for CSS type selectors (e.g., “button”, “a”, “ul”) Read more
Source§

fn set_auto_id(&mut self, _id: String) -> bool

Set an auto-generated element ID (used by stateful containers for stable child IDs). Read more
Source§

fn children_builders_mut(&mut self) -> &mut [Box<dyn ElementBuilder>]

Get mutable access to children for auto-ID assignment
Source§

fn bound_scroll_ref(&self) -> Option<&ScrollRef>

Get the bound ScrollRef for programmatic scroll control Read more
Source§

fn motion_on_ready_callback( &self, ) -> Option<Arc<dyn Fn(ElementBounds) + Send + Sync>>

Get the on_ready callback for this motion container Read more

Auto Trait Implementations§

§

impl<S> !Freeze for Stateful<S>

§

impl<S> !RefUnwindSafe for Stateful<S>

§

impl<S> !Send for Stateful<S>

§

impl<S> !Sync for Stateful<S>

§

impl<S> Unpin for Stateful<S>

§

impl<S> UnsafeUnpin for Stateful<S>

§

impl<S> !UnwindSafe for Stateful<S>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more