Expand description
§Whisker
Cross-platform mobile UI framework for Rust, built on the Lynx C++ engine.
Most users only need prelude:
ⓘ
use whisker::prelude::*;
#[whisker::main]
fn app() -> Element {
render! {
page(style: "background: white;") {
text(value: "Hello, Whisker")
}
}
}§What’s in this crate
The whisker crate is an umbrella — almost everything here is a
re-export from a more specialised companion crate, surfaced through
a single import root so app code never needs to know which inner
crate owns which symbol. The conceptual groupings:
- Macros (
component,main,module_component,render) — proc macros that lower component definitions and therender! { … }DSL into builder chains over the items in [__tags]. - Reactive primitives —
signal(),computed(),effect(),on_cleanup,on_mount,provide_context,use_context,resource(), and their handle types (Signal,ReadSignal,RwSignal,Resource, …). - Async —
spawn_local,run_blocking,run_on_main_thread. - Control flow — [
ForEach] (keyed list), [Show] (conditional). Both are written as ordinary#[component]functions. - CSS — the
csstype-safe builder + thecss!macro. - Built-in elements —
view,text,scroll_view,list,page,raw_text,fragment. Therender!macro lowers each tag invocation into a builder chain on the corresponding struct in [__tags]; the [__tags::ElementBuilder] trait provides the sharedstyle/class/on_<event>/ … methods. - Platform bridges —
PlatformModule+module!for function-shaped native modules,ElementReffor imperative methods on mounted components,ElementHandleet al for the typed return values. - Typed attribute enums — see
attrsfor the closed-set string attributes (attrs::ScrollOrientation, etc.).
Everything intended for direct user code is also pulled into
prelude; reaching into the long paths is only necessary when
writing framework-level extension code.
Re-exports§
pub use whisker_config as config;pub use whisker_runtime as runtime;pub use whisker_css as css;
Modules§
- arc_
signal - Refcount-backed signal primitives — the
Arc*family. - attrs
- Typed enums for built-in element attributes whose Lynx-side contract is a closed set of strings.
- computed
- Derived (computed) values.
- effect
- Side-effecting reactive computation.
- event
- Typed event objects handed to
on_<event>handlers on built-in elements and#[whisker::module_component]view methods. - owner
- Owner / scope API surface.
- platform_
module - Whisker platform module invocation entry point.
- prelude
- Common imports for Whisker app code.
- resource
- Async-data primitive — runs an
asyncfetcher on Whisker’s single-threaded task pool (crate::tasks) and exposes the loading / ready / error state through a [ReadSignal]-shaped handle. - signal
- Signal primitives:
ReadSignal,WriteSignal,RwSignal, and thesignalconstructor.
Macros§
- module
- Build a
PlatformModulehandle for the native module named$name, with the calling crate’s name prepended (<crate>:<$name>) so two crates can ship same-named modules without colliding in the dispatch registry.env!("CARGO_PKG_NAME")resolves in the calling crate, so the prefix is always the crate that wrote themodule!(...)call. - render
- Fine-grained renderer macro. Emits imperative element-creation
code that calls into [
whisker::runtime::view] through the thread-local installed renderer, and returns an [Element].
Structs§
- Animate
Options - Typed timing options for
animate_start. - ArcRead
Signal - Refcount-backed read-only handle. Clone-cheap (
Rcbump),!Copy. The companion toArcRwSignal::read_only. - ArcRw
Signal - Refcount-backed combined read/write signal.
- ArcWrite
Signal - Refcount-backed write-only handle. Clone-cheap (
Rcbump),!Copy. The companion toArcRwSignal::write_only. - Bounding
Client Rect - Result of
ElementHandle::bounding_client_rect— the element’s layout box in LynxView coordinates (Lynx’sboundingClientRectUI method). Every field is#[serde(default)], so any key the platform omits reads back as0.0rather than failing the decode. - EachFn
Fn() -> Vec<T>— the “what items to render” closure for a keyed-list control flow. Wrapping in a newtype gives typed-builder a concrete Props field type plus anIntopath from any matching closure literal.- Element
- The return type of a
#[component]/#[whisker::main]function — an opaque handle to a mounted view subtree. Re-exported at the crate root (and in theprelude) so component signatures read-> Elementwithout an internalruntime::viewimport. Backend-agnostic element handle.Copyso it threads through reactive closures without lifetime gymnastics. - Element
Handle - Imperative handle to any mounted element — the generic Lynx UI
methods that work regardless of tag. Allocate with
ElementHandle::new, bind viaview(ref: handle.r())(ortext,page, …) inrender!, then call the methods below. - Element
Ref - Framework-internal handle to a mounted platform element. Lives in
#[module_component]-emitted prop tables and the wrapping#[component]s that drive a Handle. Not part of an app-author’s surface — Handles wrap this. - Fallback
- The fallback branch of a
show-style conditional. Wraps an optionalFn() -> Elementclosure —Nonemeans “render nothing on false”;Some(closure)is what the user typed asfallback: || …. - ForEach
Props - ItemFn
Fn(T) -> Element— the “render one item” closure for a keyed-list control flow. The returnedElementis what gets attached to the surrounding fragment / list.- KeyFn
Fn(&T) -> K— the “key extractor” closure for a keyed-list control flow. Items whose keys match across reactive reruns reuse their owners + per-item state.- Owner
- Identifier for an
Ownerslot in the runtime’s owner map. Generational — disposing an owner invalidates outstandingOwners pointing at the same slot index. - Platform
Module - A handle to a native Whisker (function-only) module, identified by
its fully-qualified name (
<crate>:<Name>). - Read
Signal - Read-only signal handle.
Copy; safe to clone freely and move into closures. - Resource
- Copy handle to a deferred value. Wraps an
RwSignalwhose slot the worker thread writes into once the fetch completes; consumer code reads through the accessors below. - RwSignal
- Combined read-write signal handle. Equivalent to holding both a
ReadSignal<T>andWriteSignal<T>for the same underlying node. - Scroll
Info - Result of
ScrollViewHandle::get_scroll_info— the current scroll offset and scrollable range of a<scroll-view>(Lynx’sgetScrollInfoUI method). Every field is#[serde(default)], so whichever subset the platform’s scroll UI reports populates and the rest read back0.0:UIScrollViewfillsscroll_x/scroll_y/scroll_range; the internal scroller fillsscroll_x/scroll_yplusscroll_width/scroll_height. - Scroll
View Handle - Imperative handle to a mounted
<scroll-view>. Allocate withScrollViewHandle::new, bind viascroll_view(ref: handle.r())inrender!, then query scroll state. - Show
Props - Stored
Value - A non-reactive, owner-bound value slot.
Copy. - Text
Bounding Rect - Result of
TextHandle::get_text_bounding_rect— the layout boxes of a<text>substring (Lynx’sgetTextBoundingRect).bounding_rectis the union box covering[start, end);boxesis the per-line box list. All rects are in LynxView coordinates (same shape asBoundingClientRect). - Text
Handle - Imperative handle to a mounted
<text>. Allocate withTextHandle::new, bind viatext(ref: handle.r())inrender!, then drive / read text selection. - UiInfo
- Result of
ElementHandle::request_ui_info— the element’s id, layout box, size, and scroll offset in one call (Lynx’srequestUIInfo, requesting theid/rect/size/scrollOffsetfields). Every field is#[serde(default)], so whichever the platform reports populates and the rest read back empty /0.0. (rect+sizeoverlapBoundingClientRect;scroll_left/scroll_topoverlapScrollInfo—requestUIInfojust bundles them.) - WhenFn
Fn() -> bool— the predicate closure for ashow-style conditional control flow. Wrapping in a newtype gives typed-builder a concrete Props field type plus anIntopath from any matching closure literal.- Write
Signal - Write-only signal handle.
Copy. Setting or updating notifies all subscribers; the notifications are enqueued (not run synchronously) to support batched event-handler semantics — callflushto drain.
Enums§
- Animate
Op - Lynx-side animation lifecycle operations exposed by
Element::Animate. MatchesJavaScriptElement::AnimationOperationin the Lynx fork — same numeric values, same semantics. - Element
Tag - Element tag. Numeric repr stays in sync with
WhiskerElementTagincrates/whisker-driver-sys/bridge/include/whisker_bridge.h. - RefError
- Errors that can surface from imperative element-method dispatch.
- Resource
State - Three-state machine the
Resourcecycles through.Cloneso reads inside effects can take owned copies without borrowing the underlying signal slot. - Signal
- Prop value: either a static
Tor a reactiveReadSignal<T>. - Style
- Value the
style:builder method receives. One of the two variants below. - Whisker
Value - The universal tagged-union value model. Crosses the native
boundary as both module args/returns and event payloads, so it
lives at the crate root rather than buried under
platform_module(where it’s also re-exported for back-compat). Tagged-union variant set passed between Rust and the platform side — module args/returns and event payloads alike.
Functions§
- animate_
cancel - Cancel a running named animation — drops styles, clears state.
- animate_
start - High-level wrapper around
invoke_element_animatefor theSTARToperation: starts a named animation with explicit keyframes + timing. - apply_
style - Apply a
Styleto a Lynx element. TheStaticbranch sets the inline-styles attribute once; theDynamicbranch wraps the closure in aneffectso it re-applies whenever any signal it reads fires. - arc_
signal - Allocate a fresh Arc-backed signal and split into read/write
halves. The Arc analog of
signal: - computed
- Create a computed (derived) value.
fis run once immediately to seed the cache, then re-run whenever a tracked source changes. - effect
- Register
fas a reactive effect. Returns the node id (so tests can inspect it; user code generally discards the return value). - flush
- Drain the pending queue, re-running effects and computeds in the order they were scheduled. Skips entries whose node has been disposed.
- invoke_
element_ animate - Element-level animation dispatch — wraps
lynx_element_animateviawhisker_bridge_element_animate. - on_
cleanup - Register a callback to run when the current owner is disposed.
Calls accumulate in LIFO order, mirroring Solid / Leptos
onCleanupsemantics. - on_
mount - Register
fas a post-mount callback for the current owner. Fires once on the nextflush_mountscall (driven by the renderer after the component’s view is appended to its parent). - provide_
context - Provide a context value in the current owner. Subsequent
use_context::<T>/with_context::<T>calls inside this owner or any descendant find this value (unless a closer descendant shadows it). - resource
- Reactive async fetch. Drives
fetcher(anasync fnorasync move {…}block) on Whisker’s task pool and writes the resolvedResultinto the returnedResource’s signal — then re-runs the fetcher whenever any signal it read changes. - resource_
sync - Synchronous-fetch variant. Runs
fetcherinline on the calling thread and writes the result directly into the resource’s signal. No worker thread, no main-thread dispatcher needed — useful for tests, for cases where the value is already in memory, and for computed pseudo-resources (e.g. derive from a context value). - run_
blocking - Offload a synchronous closure to a fresh worker thread and return a future that resolves once the closure completes.
- run_
on_ main_ thread - Marshal a closure onto the main (Lynx) thread.
- signal
- Allocate a fresh signal in the current owner. Returns a
(ReadSignal, WriteSignal)pair — Solid-style separation. - spawn_
local - Queue
futurefor execution on Whisker’s task pool. - use_
context - Look up the nearest provided context of type
T, returning a clone. ReturnsNoneif no ancestor owner provides one. - with_
context - Look up the nearest provided context of type
Tand runfwith a borrow of it. ReturnsNoneif no ancestor owner provides one.
Type Aliases§
- Children
- Type used by
#[component]for the conventionalchildrenprop. Therender!macro routes a component invocation’s non-kwarg children into amove || View::Fragment(…)closure of this type; the component body invokes it to materialise the children at the point in the tree where they should appear.
Attribute Macros§
- component
- Mark a function as a Whisker reactive component.
- main
- Annotates the user’s app function (returning
whisker::Element) and generates the FFI symbols the iOS/Android host expects. - module_
component - Declare a Whisker-side wrapper for a Lynx-registered view module’s element.