gpui-ce-motion
Declarative animation for native Rust apps on GPUI CE.
Describe the next state. Keep the motion state in your view. The library handles transitions, springs, and interruptions using stock GPUI CE—no React or renderer fork.
Crates.io · API examples · API reference · Demos · GPUI Kit setup · Changelog
Version 0.4.0 adds Motions<K> for keyed transitions, synchronized batch
sampling, and explicit cleanup. Explore it in scene 10 Collection of motion_lab.
Install
For GPUI Kit, use gpui-motion-kit. The installation below is for GPUI CE.
[]
= { = "0.4", = ["gpui"] }
Requires Rust 1.95+. Native adapters use registry gpui-ce =0.2.2. Use the
same CE source and version throughout your app so its element types match.
| Feature | Use it for |
|---|---|
| Default (none) | Portable animation math, explicit clocks, no third-party dependencies |
text |
Portable Unicode text lifecycle and prepared text sampling |
gpui |
Native adapters, text, SVG parsing, input, and automatic frame scheduling |
svg-path |
Portable SVG path-data parser, including arcs |
demo |
Running this repository's examples; adds the platform backends |
native-tests |
Development checks using CE's TestPlatform |
Quick start
This is a GPUI component for an existing app. Click the card to change its width. Changing a target during animation continues from the displayed position; springs preserve velocity too.
use ;
use ;
Motion is a declaration you can recreate every render. MotionState is its
retained history. Keep one state per logical object; key list items by stable IDs.
Native adapters request frames while active. Notify the view after input changes.
See a complete runnable app or try the showcase:
API
The examples below cover every public API family. Each example stands on its own.
Native elements require the gpui feature and an existing GPUI view.
Keep states, groups, clips, and timelines in your view between renders. Build new targets as the UI changes. The native helpers below receive that retained state as a function argument; the portable examples use an explicit clock.
With portable sampling, sample(..., now, reduced_motion) takes elapsed time and
the user's reduced-motion preference. In a GPUI view, frame(..., window, cx)
handles the clock, frame requests, and that preference for you.
- Animation: Targets, timing, enter and exit, multiple animations, keyed presence.
- Playback: Clips, timelines and stagger, variants.
- Interaction: Gestures, dragging, scroll and visibility, reordering.
- Layout: Positions, popped exits, content sizing, shared visuals.
- Drawing: Styles, text and numbers, SVG transforms, vector paths, motion values, colors.
- New shared tools: Reactive values, nested sequences, typed timelines, completion, measured interaction, spatial reorder, cross-container movement, path preparation, rich text.
- Reference: Lifecycle and accessibility, validation, all public exports.
Targets and transitions
Target supports x, y, opacity, width, height, and border_radius.
Offsets and sizes are logical pixels. A changed destination interrupts from the
current presentation; springs retain velocity. Ordinary motion defaults to a spring.
use ;
use Duration;
let mut state = default;
let start = default
.x
.width
.height;
let destination = default
.x
.width
.height;
let motion = new.initial;
// Use one clock for every sample. Keep state between calls.
state.sample;
let frame = state.sample;
let current_width = frame.target.width_px;
In a GPUI view, use state.frame(motion, window, cx), then frame.apply(element).
Position uses relative left/top offsets. Width and height affect layout, so text
and siblings can reflow as they change. Use an outer wrapper if the element also
needs absolute positioning.
Give dimensions an initial numeric value to animate them on first mount.
Otherwise, the first value is applied immediately. Border radius does not clip
children automatically. Target::overlay combines partial targets, and the
getters on frame.target() let you read the current values.
Timing
Use a tween when you want an exact duration, or a spring when you want movement
that responds naturally to interruption. Transition::Instant skips animation.
Tweens
use ;
use Duration;
let slide = Tween;
let motion = new
.transition
.delay;
Built-in easing includes Linear, EaseIn, EaseOut, EaseInOut,
CircIn / CircOut / CircInOut, BackIn / BackOut / BackInOut,
and Anticipate. An interrupted tween keeps its current position; its velocity
can change.
Springs
Set stiffness, damping, and mass directly:
use ;
let spring = new.expect;
let motion = new.transition;
Or describe the spring with a visual duration and bounce. Prepare it once and reuse it in your view:
use ;
use Duration;
let spring = visual
.expect;
let spring = spring
.rest
.expect;
let motion = new.transition;
The visual duration is the time to reach 90% of a resting step. The spring can continue settling afterward. Springs preserve both position and velocity when you change their target.
Timing per property
A card can move with a spring and fade with a short tween:
use ;
use Duration;
let fade = Tween;
let motion = new
.initial
.transition
.transition_for;
Property selects X, Y, Opacity, Width, Height, or BorderRadius.
The last argument to transition_for is that property's delay.
Custom easing
Use a cubic Bézier curve for a familiar easing editor workflow:
use ;
use Duration;
let curve = new.expect;
let transition = Tween;
A custom function returns the easing value and its derivative. Prepare the
CustomEasing once; creating it again gives it a new identity.
use ;
use Duration;
let ease_in = new
.expect;
let transition = Tween;
Enter and exit
Keep declaring the element while present(false) so its exit can finish.
Frame::render returns an empty element after the exit completes. Re-entry during
exit continues from the current presentation, using the same retained state.
use ;
use ;
Use frame.presence() to inspect Entering, Present, Exiting, or Absent.
Before removing a focused control, restore focus elsewhere. Guard outgoing event
handlers with frame.is_present(); rendering an exit does not disable its input.
Multiple animations with Motions
Keep one Motions<Part> field when a component animates several independent
parts. Each key owns its own ordinary MotionState internally. The collection
simplifies ownership; it does not make independent trajectories share a spring.
use ;
use ;
Change expanded from your input handler and call cx.notify(). Both entries
sample at one timestamp. Springs preserve position and velocity on interruption;
per-entry delays, transitions, property overrides, and presence work as usual.
A native batch queues at most one animation-frame request, and none when all
returned frames are settled or absent. Reduced motion snaps submitted entries.
Results follow the array order; history belongs to the keys. Reordering entries
is safe. Keys need Eq + Hash, not Clone or Default; use enums or stable item
IDs rather than a list's current indices. Duplicate keys in one batch panic as a
programmer error. A batch is not transactional: earlier entries may be sampled
before a duplicate is encountered. Use small array batches for fixed parts;
frame_one is also convenient for individual entries or dynamic list loops.
Explicit cleanup
Omitting a key neither deletes it nor pauses its clock. It does not request frames
while omitted; when submitted again, its old trajectory is evaluated at the new
time. To animate removal, keep declaring present(false) until its frame is
absent, then remove the key. Do not recreate an already-cleaned outgoing entry:
use ;
use ;
Re-entry during an exit preserves momentum. Removing a key cancels it immediately;
reusing it starts fresh from initial. Guard input and restore focus for interactive
exits, just as with individual states.
| Method | Contract |
|---|---|
new() / default() |
Empty owner; no allocation |
with_capacity(n) / reserve(additional) |
Reserve table storage without creating trajectories |
frame([(key, motion), ...], window, cx) |
Fixed-size array in, same-size array of native frames out |
frame_one(key, motion, window, cx) |
Sample one native entry |
sample(batch, now, reduced_motion) / sample_one(key, motion, now, reduced_motion) |
Explicit elapsed Duration; backward times clamp; do not mix with native clocks |
len() / is_empty() / contains_key(&key) |
Inspect retained membership, including settled and absent entries |
remove(&key) |
Cancel immediately; return whether the key existed |
retain(keep) |
Cancel entries rejected by the predicate; does not wait for exits |
clear() |
Cancel all entries; keep allocated table capacity and the clock |
capacity() / shrink_to_fit() |
Inspect capacity / release unused table storage |
Existing entries reuse storage. Each new key allocates one state; the table may
also grow. with_capacity reserves table space, not those states. Keys that
allocate when constructed remain the caller's cost. Array inputs and outputs use O(batch size)
stack storage. retain visits table capacity; do cleanup/reservation outside hot
loops. Dropping the owner releases all its storage. Motions covers ordinary
six-channel Motion declarations; text, SVG, styles and typed playback retain
their specialized APIs. A graph is still useful when many effects derive from
one progress value.
Try 10 Collection in motion_lab on either backend: expand/reverse the panel,
watch its independently animated title and progress, and dismiss/re-enter the notice.
Its outgoing state is removed only after the exit completes. See the
sampling, memory and native measurements.
Keyed presence
PresenceGroup<K> retains removed keys until you acknowledge their completed
exits. Use Sync to enter/exit together or Wait to delay new keys until exits finish.
use ;
let mut notifications = new;
notifications
.update
.expect;
// Notification 1 stays mounted for its exit. Notification 3 waits.
notifications
.update
.expect;
let outgoing = notifications
.children
.iter
.find
.expect;
assert!;
// Call this only after notification 1's motion reaches Presence::Absent.
notifications.finish_exit;
Keep each child's motion state in a map keyed by its domain ID. Iterate
children(), pass child.is_present() into Motion::present, and remove the
state only after finish_exit. See the native gallery.
Clips and playback
Prepare the clip once. Its clones share keyframes; constructing a new clip means
a replacement trajectory. Keyframe times increase strictly from 0 to 1.
Keyframe::current(0.) captures the displayed start; a later current holds the
previous target. Segment easing belongs to the keyframe ending that segment.
use ;
use Duration;
let keyframes = ;
let clip = keyframes
.expect
.delay
.repeat
.expect;
let mut player = new;
player.sample;
// In an input handler, pause and scrub using the same clock.
let now = from_millis;
player.pause;
player.seek;
player.set_speed.expect;
player.play;
let frame = player.sample;
Also available: Animation::to for a two-endpoint tween, Animation::spring for
a physical spring with an explicit deadline, Repeat::Count(n) for n extra
cycles, and Loop/Reverse/Mirror repeat modes. Loop can jump at its boundary.
| Control/readout | Meaning |
|---|---|
pause(now) / stop(now) |
Hold the current playhead; stop is a pause alias |
play(now) |
Resume |
seek(playhead, now) |
Scrub, including backward seeks |
set_speed(speed, now) |
Change rate; negative values play backward |
restart(now) / finish() |
Start over / complete an AnimationState |
iteration() / is_playing() |
Read cycle count / playback state |
Playback |
A standalone clock with time, pause/play, seek, and speed controls |
For native rendering, call player.frame(&clip, window, cx).apply(element).
Use player.now() in its input handlers, rather than another epoch. Notify the
view after controls change. Portable calls use one application epoch consistently.
Timelines and stagger
Use a timeline to start animations together, one after another, or relative to a named point. Each track returns an index you can use to read its current frame. Build the timeline once and keep it in your view.
use ;
use Duration;
let slide = to;
let mut timeline = default;
let first_card = timeline.at;
// Place a label at the end of the first animation.
timeline.label.expect;
// The second card starts when the first finishes.
let second_card = timeline
.then
.expect;
// The third card starts 80 ms after the label, overlapping the second.
let third_card = timeline
.at_label
.expect;
timeline.restart;
let frames = timeline.sample;
let first_card_position = frames.target.x_px;
To stagger a group, calculate a delay for each item:
use ;
use Duration;
let keyframes = ;
let fade_in =
keyframes.expect;
let mut timeline = default;
for index in 0..5
StaggerFrom::Start, End, and Center choose where the stagger begins.
Timeline controls include pause/play, seek, speed, and restart. In native
rendering, apply each frame to its matching element and request another frame
while timeline.is_animating().
Variants
Give reusable states names such as "idle" and "expanded". Each variant stores
both a target and its timing. Keys can also be enums or another type you choose.
Here, the expanded variant determines the width, while hover changes the opacity.
with_target keeps the variant's timing when applying the combined target.
use ;
let variants = new
.expect;
let expanded = variants.get.expect;
let mut interaction = default;
interaction.hovered = true;
let gestures = default
.while_hover
.while_focus;
let target = gestures.resolve;
let motion = expanded.with_target;
Native gestures
GestureState connects native input to animation targets. Store it in your view,
then bind it to the element you want to animate:
use ;
use ;
You can also set while_drag and while_in_view targets. If several interactions
set the same property, drag wins over press, hover, focus, and in-view, in that order.
Read interaction() for input state, presented() for the current position, and
focus_handle() for focus management. Use cancel(cx) when switching contexts.
.enabled(false) cancels input and removes tab stops; the app supplies disabled
semantics and restores focus. Mouse/keyboard dragging and native trackpad pinch are supported. Raw CE touch
dispatch remains pending upstream. Reorder edge scrolling is opt-in; OS-wide
pointer capture remains application/platform work.
Dragging
Attach a Drag to your gesture state to make its element draggable. This example
allows horizontal movement from 0 to 300 pixels, with a 20-pixel snap grid.
Keeping the minimum and maximum Y coordinates equal locks vertical movement.
use ;
let start = ;
let min = ;
let max = ;
let drag = new
.elasticity
.snap_grid
.momentum;
let gestures = default.with_drag;
// Store gestures in the view, then use gestures.bind(...) when rendering.
The portable Drag exposes begin, move_to, end, cancel, move_by (keyboard
movement), sample, and is_dragging. Its host must supply pointer timestamps,
release/cancellation handling, focus, and frame requests. A still hold before
release clears stale momentum. Re-grabbing starts at the displayed position.
Scroll and visibility
Use a retained native ScrollHandle for both the scroll container and its progress
binding. Mapping is instant by default; .transition(...) adds smoothing.
use ;
use ;
native_scroll_progress(handle, axis) exposes measured progress separately.
Portable helpers accept measured metrics directly; visibility bounds are
[x, y, width, height] in one coordinate space:
use ;
// The viewport is 400 px tall, with 1,000 px of scrollable content.
let progress = scroll_progress;
let offset = transform;
// Trigger at 50% visibility and stay triggered after the first entry.
let mut visibility = new;
let viewport_bounds = ;
let item_bounds = ;
visibility.update;
let is_visible = visibility.is_visible;
For automatic native visibility, initialize GestureState::default().in_view(0.5, true) and bind GestureTargets::while_in_view(...). The native adapter measures
clipped bounds. InView::is_visible reads the portable observer's latest result.
Reordering
Use a retained ReorderGroup for lists or draggable tabs. Render in order() and
keep each item's IDs and key stable. Group items accept a Stateful<Div>.
use ;
use ;
// Create this once and store it in your view.
let tabs = new.expect;
Choose Axis::Y for a vertical list. The group animates measured reflow and handles
pointer release outside the item, keyboard reorder, and Escape cancellation.
On macOS, keyboard reorder is Option (⌥) + arrows; elsewhere it is Alt + arrows.
A tab strip's active selection and panel content remain application state keyed by ID.
Use on_change(|keys, window, cx| ...) to persist a changed order; capture application
entities weakly. Call set_order for external model changes, not every render.
is_dragging reports pointer ownership. The host restores focus after removal.
See spatial reorder for grids, handles and edge scrolling. For custom bindings, reorder_index finds the nearest measured center
and move_item rearranges a slice while preserving identity.
Layout positions
Retain one LayoutGroup and wrap elements with stable IDs. Change order, wrapping,
alignment, or parent layout normally; the group measures and animates positions.
use ;
use LayoutGroup;
.transition(...) changes timing; .enabled(false) snaps. Share the same group
through nested animated elements to avoid double movement. First mounts and size
changes are immediate; keyed history ends at unmount/reparenting. This translates
paint, hitboxes, and accessibility bounds, with ordinary ancestor clipping.
Avoid competing x/y motion on the same element. Portable LayoutPositionState
accepts measured origins via sample/sample_axes; its frame reports layout origin,
presented position, offset, velocity, activity, and completion. reset clears history.
Popped exits
PopLayout removes outgoing items from flow immediately and retains their visible
position while their opacity exit plays. It owns positional reflow too.
use ;
use ;
Get frame from the retained child's MotionState, with an opacity exit and
present flag as in enter and exit. Keep the child until absent;
then call PresenceGroup::finish_exit if using keyed presence. Do not add another
LayoutGroup::position wrapper to the same item. For x/y exits, animate inner
content in a fixed-size wrapper. Input suppression and focus restoration are yours.
Content sizing
AutoSize measures intrinsic content and animates its reserved size. Supply the
available width for wrapping text. It defaults to height; SizeAxis::Width or
Both selects other axes.
use ;
use ;
let content = div.w_64.child;
let panel = new
.width
.axis;
Keep the element ID stable. .height(...) supplies a height constraint,
.transition(...) changes timing, and .initial([width, height]) opts into
entrance. It clips paint/input while resizing. Paint an outer card around the
reservation if its background should follow the animated bounds. This is real
layout sizing, not subtree scaling or automatic ancestor constraint discovery.
Shared visuals
Retain a SharedLayout<K> and declare exactly one active destination per shared
key in a common overlay. The outgoing position/crossfade belongs to that shared
identity; content lifetime and input policy remain explicit.
use ;
use SharedLayout;
let shared = default;
let previous = div.absolute.left.child;
let destination = div.absolute.left.child;
// Both members represent the same key. Only the destination is active.
let outgoing = shared.member;
let incoming = shared.member;
let overlay = div.relative.child.child;
Members accept .transition(...). Call remove(&key) when that identity is no
longer needed; len/is_empty inspect retained entries. Sizes change immediately,
normal clipping applies, and independent scrolling coordinate spaces are not
reconciled. This is position/crossfade, not full shared-element size projection.
Style animation
Retain StyleMotionState for typed scalar/color tracks. Use StyleTarget for
individual corners, borders, spacing, one shadow, blur, and backdrop blur.
Colors are background, text, border, and shadow; they interpolate in linear light.
use ;
use ;
Corners run top-left, top-right, bottom-right, bottom-left. Edge arrays run top,
right, bottom, left. value addresses individual StyleProperty channels,
including BackdropBlur. initial, transition, transition_for, and
color_transition set timing. Portable sample returns a StyleFrame with target,
activity, and completion. StyleTarget::get/get_color inspect declared channels.
Omitted styles remain unchanged until introduced, then retain their last target. Reset the state to release overrides. Shadow/filter declarations replace their lists. Spacing reflows layout; blur requires separate GPU profiling.
Text motion
Retain a TextMotionState per label. The element measures and shapes complete text,
then coordinates its units, outgoing content, and interrupted transitions.
The native gpui feature enables text automatically; portable consumers can enable
text alone. Kit consumers import native states from gpui_motion_kit.
use *;
use ;
use Duration;
Groupings are Whole, Words, Graphemes, and measured Lines. Presets are
Fade, FadeUp, SlideUp, WipeRight, WipeLeft, and discrete Typewriter.
animate_initial(false) skips the first entrance while preserving later changes.
Custom poses and matching compose independently:
use ;
let state = default;
let text = state
.element
.units
.matching
.reflow
.enter
.exit
.opacity_transition
.clip
.presence_mode;
TextTarget supplies x_em, y_em, measured-height y_relative, opacity,
and horizontal/vertical reveal. SlideUp clears the entire measured unit; SlideUp and
wipes fade outgoing text over 100 ms. opacity_transition(...) changes that
opacity timing while transition(...) keeps control of movement and reveal.
TextMatch::Content preserves matching occurrences; Replace replaces changed
content and Position matches slots. PresenceMode::Wait waits for exits and
keeps the latest pending text. Font metrics and sizes change immediately.
Prepare a scramble alphabet once, or calculate each unit's entrance:
use ;
use Duration;
let state = default;
let scramble = new
.duration
.seed;
let scrambled = state
.element
.units
.scramble;
let another_state = default;
let alternating = another_state
.element
.units
.enter_with;
TextUnitInfo provides index, count, and text. A retained prepared
Animation can be passed to animation(&clip) for keyframes and repeating
waves/pulses. Its x/y channels use logical pixels and opacity multiplies presence.
Playback controls work from ordinary event handlers:
use TextMotionState;
seek holds a normalized finite entrance cursor and returns false for infinite
clips. progress(value) declaratively scrubs entrances including stagger; it
rejects infinite clips. Spring scrubbing uses a two-second horizon. presentation
copies diagnostics, is_animating reports activity, and error reports native
shaping/paint failures. Reduced motion settles without ongoing frame requests.
Counts have a separate retained state and place-value matching:
use *;
use ;
let counter = default;
let count = counter
.element
.effect
.min_digits
.transition
.opacity_transition
.text_2xl;
Number effects are Roll, Crossfade, Slide, and rounded numeric Interpolate.
Counts accept i64, including exact endpoints at its limits. Intermediate numeric
interpolation uses f64. text_state() exposes the digit layer's controls and
diagnostics, independently of numeric interpolation.
The text contracts cover shaping, clipping, playback, accessibility,
portable TextPlaybackState/TextOptions, errors, costs, and limits. This is
single-style display text; editing, selection, and inline rich text stay with GPUI.
Run the Kit text gallery or stock-CE
cargo run --features demo --example text_motion for interactive examples.
SVG transforms
Retain SvgMotionState; apply its frame to a normal GPUI SVG. Keep the asset path
and base dimensions stable so CE can reuse its cached drawing.
use ;
use ;
The app supplies the SVG asset through its normal AssetSource. scale sets both
axes; signed scale_xy allows mirroring. Angles are absolute and unwrapped:
0 → 720 makes two turns, and 350 → 370 crosses zero by twenty degrees.
transition/delay set timing. SvgFrame exposes target, scale/rotation velocity,
translation velocity, activity, completion, and transformation().
transformation_about(size, pivot) accepts a logical-pixel pivot for
Svg::with_transformation. Portable sample works without GPUI.
Only the SVG drawing transforms. Native children, layout, clipping, and hitboxes do not scale or rotate. Use a fixed, sufficiently padded native interaction parent. Large zooms can soften the cached raster drawing. Add outer ordinary motion for opacity/presence; arbitrary GPUI subtree transforms remain deferred.
Vector paths
Prepare absolute commands once. Move, Line, Quadratic, Cubic, and Close
are supported. A morph needs the same command sequence and coordinate topology.
use ;
let horizontal = new
.expect;
let diagonal = new
.expect;
// Store this in the view so changes to the target path can animate.
let vector = new;
let reveal =
new.expect;
let drawing = vector
.element
.expect
.stroke
.reveal;
Use .fill() for a filled path, .transition(...) for timing, and VectorState::error
for the most recent tessellation error. Reveal affects strokes only.
StrokeReveal specifies normalized length, offset in path lengths, and spacing;
values() reads them. At most 4096 reveal periods are accepted. Stroke curves
use 32 segments per curve; fills retain curve commands. See SVG preparation for path parsing, arcs,
normalization and path-following queries.
For portable/custom rendering, PathShape::commands/compatible inspect shapes.
Retain PathMorphState, call validate/sample, then read the borrowed PathFrame's
commands, length, activity, and completion. stroke_segments(reveal, callback)
emits line segments. Invalid topology does not partially mutate the sampler.
Motion values
MotionValue handles a scalar in your own units. set records a directly driven
value and velocity; jump resets velocity. animate/animate_delayed follow a
target; coast applies bounded inertia. get/velocity read the latest sample.
use ;
use Duration;
let mut progress = new;
progress.animate;
let now = from_millis;
let frame = progress.sample;
let opacity = transform;
// Continue from the current velocity, staying within these bounds.
let inertia = new.bounds;
progress.coast;
ValueFrame reports value, velocity, activity, and completion. Inertia::spring
sets the boundary spring; project estimates its destination. Derive dependent
values directly in Rust, or use the retained motion graph
when automatic dependency updates and subscriptions are useful.
Colors
Colors are typed sRGB inputs with linear-light interpolation. Use rgb(0xRRGGBB),
rgba(r, g, b, a) in 0..=1, channels() for sRGB values, and mix for a direct blend.
use ;
use Duration;
let mut background = new;
let destination = rgb;
let transition = default;
background.sample;
let =
background.sample;
let native_color = current.to_rgba;
Retain the state for interruptible color springs/tweens. sample returns the
sampled color and an activity flag. to_rgba() converts it to a GPUI color.
Lifecycle and accessibility
Frame, ValueFrame, SvgFrame, StyleFrame, LayoutPositionFrame, and
PathFrame expose is_animating() and just_completed(). Completion is a sampled
edge, not a replay of every missed repeat; read AnimationState::iteration() for cycles.
Frame additionally reports ordinary/layout velocities and presence state.
Native adapters honor App::reduce_motion() and stop requesting frames after
settling. Portable APIs take a reduced_motion flag:
use ;
use Duration;
let mut state = default;
let motion = new.initial;
let reduced_motion = true;
let frame = state.sample;
// Reduced motion reaches the destination without playing the transition.
assert_eq!;
assert!;
Reduced motion completes even exits and infinite clips; a completed clip stays complete until restart/replacement. The app synchronizes OS preferences, notifies on input changes, restores focus on removal, and scopes keyboard shortcuts around text editing. No per-animation task, global registry, or platform bootstrap is added.
Validation
| Error type | Returned by |
|---|---|
InvalidSpring |
Invalid physical parameters, visual timing, or settling tolerances |
InvalidEasing |
Invalid Bézier controls or custom easing preparation |
AnimationError |
Invalid keyframes/times, repeats, speed, labels, keys, or indices |
PathError |
Invalid path geometry/topology, reveal, drawing bounds, or tessellation |
All four implement std::error::Error. The examples use expect for fixed,
valid inputs; propagate errors when values come from users. Builders such as
Target::width assert their contracts: pass finite values, nonnegative dimensions,
and opacity within 0..=1. See the linked source declarations for each constructor's details.
Reactive values and subscriptions
MotionGraph retains sources, derived values, and subscriptions. A sample updates
all dependencies before dispatching events. Keep the subscription handle alive;
dropping it unsubscribes. Prepare mappings once, outside rendering.
use ;
use Duration;
let mut graph = default;
let progress = graph.source;
let x = graph.derive.unwrap;
let opacity = graph.derive.unwrap;
let subscription = graph.subscribe.unwrap;
graph.animate.unwrap;
graph.sample;
let position = graph.get.unwrap;
let alpha = graph.get.unwrap;
set records direct input velocity; jump resets momentum. animate preserves
spring momentum. Events are Start, Cancel, Change, and Complete. Multiple
writes coalesce per sample. Callbacks may cancel subscriptions or update another
owner; defer edits to the graph being sampled until callbacks return.
Use typed_source, animate_typed, and typed_value for colors, Target,
StyleTarget, SvgTarget, TextTarget, arrays, or your own MotionData<N> type.
target(base, &[(Property, ValueId)]) binds graph values to native target fields.
Parent and child sequences
A retained MotionTree propagates variants, staggers siblings, and sequences
parents before or after children. Add parents first. Keys are application data.
use ;
use Duration;
let variants = ;
let mut tree = default
.config;
tree.add.unwrap;
tree.add.unwrap;
tree.set_variant.unwrap;
tree.sample;
let retain_panel = tree.is_mounted;
let title = tree.get.unwrap;
Together, BeforeChildren, and AfterChildren choose the timing relationship.
exit_when optionally chooses a separate policy for leaving.
inherit(false) blocks ancestor variant propagation into that subtree;
set_node_variant explicitly selects one subtree. set_motion accepts a dynamic
Rust-computed declaration for one node. Identical declarations do not restart.
Gated animations hold their local clock and momentum. Nested exits keep a parent
mounted until every participating descendant exits; a non-exiting child keeps it
mounted. The application removes the view and restores focus afterward.
MotionConfig::transition(...).motion(target) supplies explicit defaults to your
render helpers. It installs no global provider and does not override OS preferences.
Typed clips and mixed timelines
TypedAnimation<T, N> supports scalars, colors, numeric targets, styles, SVG
transforms, text targets, and arrays. Implement MotionData<N> for another fixed
numeric representation. Seed and clip must declare the same property mask.
use ;
use Duration;
let mut timeline = default;
let color = timeline.at;
timeline.label.unwrap;
let icon = timeline.at_label.unwrap;
timeline.sample;
let background = timeline.value.unwrap;
let transform = timeline.value.unwrap;
Use TypedKeyframe::new/current/easing, TypedAnimation::keyframes/to/spring,
delay, and repeat to prepare clips. TypedState::sample plays one typed value
with per-channel spring interruption. TypedTimeline::after accepts signed
seconds for gaps or overlaps; adding after a forever track returns an error.
Track IDs belong to their creating timeline. Setup allocates; sampling reuses state.
Both owners support pause, play, seek, restart, speed (including reverse), and
completion. TypedState::finish finishes even a forever clip. Applying sampled
values uses the existing numeric/style/SVG/text adapters. Kit still rejects blur
and backdrop blur through StyleFrame::try_apply; typed tracks add no renderer hooks.
Completion futures
AnimationState, TypedState, TypedTimeline, and MotionTree expose
completion(). Requesting a future allocates observer storage; ordinary sampling
does not. Await it on your application's executor while native frames drive the
animation. Completion, replacement, explicit cancellation, restart, and owner drop
all resolve the observer instead of leaving a waiting task behind.
use ;
use Duration;
let clip = to;
let mut state = default;
state.sample;
let finished = state.completion;
state.sample;
async move ;
SVG path preparation and following
PathShape::parse_svg accepts SVG path data, including relative, smooth, implicit,
and elliptical arc commands. Enable svg-path for portable use; the native
adapters enable it. This parses path data, not an SVG document or CSS.
use ;
let circle = parse_svg.unwrap;
let triangle = parse_svg.unwrap;
let = circle.normalize_for_morph.unwrap;
let path = parse_svg.unwrap;
let measure = new.unwrap;
let point = measure.point;
let position = point.position;
let angle_degrees = point.tangent_degrees;
Feed the normalized pair to PathMorphState or VectorState; feed measured
position/tangent to a numeric target or SVG transform. Normalize and measure once.
Queries allocate nothing. Curves use 32 subdivisions; normalization resamples to
line contours with your chosen point budget. Contour count, order, open/closed
status, start points, and winding must correspond. It does not infer semantic
shape correspondence. Subpath gaps do not become visible connecting segments.
Rich text, vertical reveals, and decimal counters
use ;
let title = new;
let euros = default
.prefix
.decimal
.grouping;
let value = new.unwrap;
let formatted = euros.format;
assert_eq!;
TextSpan::font_family and font_weight choose native faces per span. The full
string is shaped before units split. Font size and line height remain label-wide.
This is a display-label API; selection/editing and variable-font-axis interpolation
are outside its contract. Numeric endpoints use an exact i64 coefficient plus
0–18 decimal places. Separators, affixes, digit alphabets, and 3/3 or 3/2 grouping
are explicit; it does not bundle automatic CLDR/ICU locale rules. Currency conversion
and rounding remain application decisions. Digit identities follow decimal places
across grouping/affix changes and integer growth. Affixes and separators have
distinct identities; the chosen effect applies to changed glyphs.
Native graph and tree owners
Retain GraphState or MotionTreeState in your view. Call frame once before
reading bound values. Use now(cx) for input/control timestamps; do not mix that
executor clock with an unrelated Instant or a manually sampled epoch. Notify
the owning view after edits. Idle or paused owners stop requesting frames.
use ;
use MotionTree;
let graph = default;
let tree = new;
TypedState and TypedTimeline also provide native frame and now methods.
Reduced motion settles pending transitions and bypasses tree gates/staggers.
Measured scroll targets and viewport roots
Retain one MotionAnchor per measured element and mount each once. Anchors use
logical window coordinates, keep native input/accessibility, and request a follow-up
frame after changed measurements. Clear an anchor before reusing it in another window.
use ;
use ;
use ;
let scroll = new;
let viewport = default;
let target = default.scroll_source;
let mut tracker = new
.offsets
.margins;
let panel = viewport.element;
Call tracker.frame(window, cx) during rendering. The returned ScrollFrame
contains readiness, progress, velocity, offsets, and active status; target(from, to) maps progress to numeric targets. Optional transition smooths with the shared
solver. Negative margins expand the viewport; ScrollOffsets::unclamped permits
anticipation. Explicit scroll_source avoids stale measurements between prepaints.
For nested scrolling, track the nearest source and measure again after ancestor
scrolling/layout; this is not an automatic browser-style ancestor observer.
GestureState::view_root(anchor).view_margins([top, right, bottom, left]) customizes
in-view observation while preserving normal ancestor clipping.
Measured drag bounds, handles, and pinch
use ;
use ;
let bounds = default;
let gesture = default
.with_drag
.constraints
.on_drag
.on_pinch;
Mount bounds.element(...), then wrap the control with gesture.bind(...).
Measured constraints update on resize. Set .drag_listener(false) on the binding
and call gesture.start_drag([x, y], window, cx) from a separate handle's mouse-down
handler. Focus, keyboard equivalents, cancellation, release outside, and smooth
inertial interruption remain supported. DragEvent reports phase, point, delta,
offset, velocity, and direction lock. Callbacks run after internal borrows end;
use weak view/entity captures rather than retaining the same owner in its callback.
Pinch reports native trackpad lifecycle; mapping its scale to an SVG or another
supported property is explicit. It cannot scale an ordinary element subtree.
Stock CE 0.2.2 exposes pinch input, but its raw-touch dispatch is pending upstream. There is no CE touch-pan binding; mouse/keyboard dragging and native trackpad pinch are supported.
Spatial reorder and edge scrolling
use ScrollHandle;
use ;
use ;
let scroll = new;
let viewport = default;
let group = spatial
.unwrap
.autoscroll;
Render group.order() inside your ordinary row/column/wrapped grid, wrapping each
stable-key item with group.item(...). Auto measures whether it is a row,
column, or grid; explicit X, Y, and XY are available. Pointer collisions use
nearest measured slots. Batched pointer/key input keeps the latest measured slot
map stable until layout catches up. Option/Alt + arrows choose a physical neighbor
in grids. Auto chooses its axis at acquisition.
Use .drag_listener(false) plus start_drag(&key, point, window, cx) for handles. External set_order changes require a fresh layout before acquiring
another drag.
Edge scrolling uses elapsed time and native bounds, and stops on release, Escape,
blur, deactivation, or reaching a limit. One pointer owns a group. This is a measured
reorder list/grid, not a virtualized arbitrary drag/drop data-transfer framework.
Cross-container shared movement
use ;
use SharedOverlay;
let overlay = default;
let source = overlay.anchor;
let destination = overlay.anchor;
overlay.select;
let floating = overlay.element;
Anchors may live in separate clipped containers. Render floating appearances in
an unclipped window-root overlay so movement can cross them. scroll_anchor
tracks a scroll source; measurements must belong to the same native window.
active(false) crossfades a retiring appearance; retain it while exiting, disable
its input, and manage focus in the host. match_size(true) uses destination sizes
immediately through real layout. Position uses interruptible shared springs;
this provides no GPU size projection. remove(&key) releases completed history.
Native rich text and formatted numbers
use ;
use ;
use ;
let text = default;
let number = default;
let rich = new;
let label = text.rich_element
.preset
.color_transition
.animate_font_size;
let format = default.prefix.grouping;
let count = number.formatted_element;
let content = div.font_family.text_size
.child
.child;
WipeDown and WipeUp complement existing horizontal reveals;
reveal_axis(TextRevealAxis::Vertical) configures custom wipes. Colors interpolate
in linear light, retaining per-glyph state. NumberElement also forwards
color_transition and animate_font_size. Font size animates by native shaping
and layout, so it costs more than opacity/translation. Pause/play freezes glyph
motion, font-size and color transitions; normalized seek/restart controls the
entrance sequence, not style history. Keep one mounted element per text state.
Public export index
The current public export families are listed below. Native methods and returned
wrapper types live beside their owners. Hidden adapter macros are implementation
details. Generate current method documentation with
cargo doc --no-deps --features gpui --open; hosted docs still describe the
latest published version until this checkout is released.
| Group | Public exports | Feature |
|---|---|---|
| collection | Motions |
None; native frame with gpui |
| motion | Frame, Motion, MotionState, Presence, Property, Target |
None |
| transitions | Bezier, CustomEasing, Easing, InvalidEasing, InvalidSpring, Spring, Transition |
None |
| values | Inertia, MotionValue, ValueFrame |
None |
| playback | Animation, AnimationError, AnimationState, Keyframe, Playback, Repeat, RepeatMode, StaggerFrom, Timeline, stagger |
None |
| colors | Color, ColorState |
None |
| interaction | Drag, GestureTargets, InView, Interaction, Variants, move_item, reorder_index, scroll_progress, transform |
None |
| presence | PresenceChild, PresenceGroup, PresenceMode |
None |
| SVG | SvgFrame, SvgMotion, SvgMotionState, SvgTarget |
None |
| position | LayoutPositionFrame, LayoutPositionState |
None |
| styles | ColorProperty, StyleFrame, StyleMotion, StyleMotionState, StyleProperty, StyleTarget |
None |
| graph | GraphError, GraphSubscription, MotionEvent, MotionEventKind, MotionGraph, ValueId |
None |
| orchestration | ChildrenOrder, MotionConfig, MotionNode, MotionTree, TreeError |
None |
| completion | Completion, CompletionStatus |
None |
| typed playback | MotionData, TrackId, TypedAnimation, TypedFrame, TypedKeyframe, TypedState, TypedTimeline |
None |
| geometry/input | AutoScroll, DragBounds, GeometryError, LayoutRect, ReorderAxis, ScrollEdge, ScrollOffsets, ScrollFrame, DragEvent, GesturePhase, PinchGesture |
None |
| vectors | PathCommand, PathError, PathFrame, PathMorphState, PathShape, StrokeReveal |
None |
| vector preparation | PathMeasure, PathPoint |
None |
| SVG parser | SvgPathError |
svg-path |
| text options | NumberEffect, Scramble, TextClip, TextError, TextMatch, TextOptions, TextPreset, TextRevealAxis, TextTarget, TextUnit, TextUnitInfo, text_ranges |
text |
| text lifecycle | TextLayoutUnit, TextPlaybackState, TextPresentation |
text |
| text formatting | FixedNumber, FormattedNumber, NumberFormat, NumberFormatError, RichText, TextSpan |
text |
| native layout | LayoutGroup, LayoutPositionElement |
gpui |
| native sizing | AutoSize, SizeAxis |
gpui |
| native exits | PopElement, PopLayout, PopRequest |
gpui |
| native gestures | GestureElement, GestureState |
gpui |
| native scroll | Axis, ScrollMotion, native_scroll_progress |
gpui |
| native shared | SharedElement, SharedLayout |
gpui |
| native reorder | ReorderElement, ReorderGroup |
gpui |
| native vectors | VectorElement, VectorState |
gpui |
| native text | NumberElement, NumberMotionState, TextElement, TextMotionState |
gpui |
| native spatial | AnchorElement, GraphState, MotionAnchor, MotionTreeState, ScrollTracker, SharedOverlay, SharedOverlayElement |
gpui |
Ownership in four rules
- Retain state. Store motion states, groups, clips, and timelines in the view. Creating a new state resets its history; creating a new clip replaces playback.
- Declare the destination. Build targets during render. First mounts snap
unless you provide
initial; undeclared dimensions preserve existing styles. - Keep exits mounted. Continue declaring
present(false)until the exit is absent. Restore focus and guard outgoing input yourself. - Use one clock. Portable
sampleand controls use one monotonic epoch. Native clip controls usestate.now(). Native adapters honorcx.reduce_motion(); your app synchronizes the OS preference.
What stock GPUI CE can animate
| Supported | Boundary |
|---|---|
| Dimensions, spacing, and measured content sizing | Real layout; text and siblings can reflow |
| Automatic position animation and shared position/crossfade | Sizes change immediately; no size projection |
| SVG scale and rotation | Drawing only; native hitboxes, clipping, and children stay untransformed |
| Native paths and stroke reveal | Parsed path data/arcs, bounded corresponding-contour normalization, prepared following queries |
| Blur and backdrop blur | Need separate GPU profiling; CPU sampling timings do not measure these effects |
Arbitrary element-tree scale/rotation/skew/perspective and full layout projection are deferred. This is a Motion-inspired Rust API, not JavaScript/React API parity. Read COVERAGE.md for exact contracts and exclusions.
GPUI Kit
Use gpui-motion-kit in a Kit application.
It connects this same animation engine to Kit's elements and frame scheduler.
No direct gpui-ce-motion dependency or CE-specific gpui feature is needed.
[]
= "0.5"
= { = "=0.7.3", = ["component", "assets"] }
Requires Rust 1.95+ and GPUI Kit 0.7.3's default gpui-pre backend. Kit and CE
native types cannot be mixed; import native states from gpui_motion_kit and
portable declarations from gpui_motion_kit::core. The CE-native examples above
use a different integration.
The Kit README includes a complete runnable
button/panel application and examples for enter/exit, animated text and numbers,
position-only layout, and scalar values. Kit 0.3.0 added native style,
gesture/scroll, measured sizing, reorder/popped-exit/shared-position, clip/timeline
and SVG helpers. Kit 0.4.0 added the expanded shared engine and Motion lab;
Kit 0.5.0 adds keyed Motions collections over core 0.4.0.
The API reference
and Kit README document these helpers and the stock renderer's filter/transform
limits.
The Motion / Kit showcase contains six interactive flows: inbox and undo, asset inspection, downloads, document search, a draggable planner, and an automation runner. Run from this checkout:
Explore and contribute
- Demos and showcase controls
- Tests and benchmarks
- Measured performance and its limits
- Publishing procedure
- Changes by version
MIT OR Apache-2.0. The library and demos were extracted from 1keep at commit
0cb95d0; the original MIT and Apache-2.0
notices are retained.
The expanded engine's CPU benchmarks, allocation checks and native acceptance are recorded in the performance report.