Expand description
Declarative transitions with retained, explicitly owned motion state.
Keep one MotionState per logical object in its owning view. Recreate the
Motion description each render; changing a target interrupts from the
current presentation. Springs also preserve velocity. No tasks, allocations,
global registries, or timers are needed to sample motion. Prepared clips and
timelines allocate during construction; their sampling reuses retained state.
use gpui_ce_motion::{Motion, MotionState, Target, Transition};
use std::time::Duration;
let mut state = MotionState::default();
let motion = Motion::new(Target::default().x(120.0).width(240.0).border_radius(12.0))
.initial(Target::default().width(0.0).border_radius(0.0).opacity(0.0))
.exit(Target::default().y(16.0).opacity(0.0))
.transition(Transition::default());
assert!(state.sample(motion, Duration::ZERO, false).is_animating());
let frame = state.sample(motion, Duration::from_secs(5), false);
assert_eq!(frame.target().x_px(), 120.0);
assert_eq!(frame.target().width_px(), Some(240.0));
assert!(!frame.is_animating());The optional gpui feature adds MotionState::frame and GPUI rendering
helpers. See the crate README for integration and publication constraints.
Prepared playback uses the same explicit clocks and ownership:
use gpui_ce_motion::{Animation, AnimationState, Easing, Repeat, RepeatMode, Target};
use std::time::Duration;
let clip = Animation::to(Target::default().x(120.0), Duration::from_millis(600), Easing::Linear)
.repeat(Repeat::Forever, RepeatMode::Mirror, Duration::ZERO)?;
let mut state = AnimationState::default();
state.sample(&clip, Duration::ZERO, false);
state.pause(Duration::from_millis(300));
let held = state.sample(&clip, Duration::from_millis(900), false);
assert_eq!(held.target().x_px(), 60.0);
assert!(!held.is_animating());Structs§
- Anchor
Element - Frame-scoped measuring wrapper created by
MotionAnchor::element. - Animation
- A prepared, cheaply cloned clip. Construct once outside rendering; clones share keyframes.
- Animation
State - Retained playback for a prepared clip. New clips interrupt from current presentation.
- Auto
Scroll - Edge autoscroll velocity policy. Use real elapsed time and the native scroll handle’s current bounds; do not integrate a fixed distance per rendered frame.
- Auto
Size - Measures content as a separate layout root, reserves its animated size, and clips painting/input to that reservation. This adds a layout node. Constraints are explicit because the content is measured before parent layout is resolved. This is real layout sizing, not GPU projection. Retain the same CE-scoped ID.
- Bezier
- A validated cubic Bezier easing curve. X controls are in
0..=1; Y may overshoot. - Color
- A linear-light RGBA color, constructed and read as sRGB channels in zero through one.
- Color
State - Retained, interruptible color motion. Each linear-light channel retains spring velocity.
- Completion
- A single observer of playback completion. Polling never starts a timer or executor; the retained player must continue being sampled by its host.
- Custom
Easing - Prepared application easing. Copies preserve identity so repeated declarations
do not restart. Call
newonce, not during rendering. Equality compares the generated identity rather than unreliable function-pointer equality. - Drag
- Bounded two-dimensional drag with explicit ownership of pointer capture/cancellation.
- Drag
Bounds - Allowed drag offsets relative to an element’s untranslated layout rectangle.
- Drag
Event - Structured pointer information in logical window pixels.
- Fixed
Number - Exact signed decimal coefficient with zero through eighteen fractional places.
For example
FixedNumber::new(12345, 2)represents 123.45 without float rounding. - Formatted
Number - Prepared text plus semantic place identities. Slot identities encode decimal place and token kind; affixes and separators remain distinct even with long UTF-8 prefixes.
- Frame
- A read-only presentation snapshot. It owns no tasks or GPUI resources.
- Geometry
Error - Invalid finite geometry, scroll range, or edge-scroll configuration.
- Gesture
Element - Frame-scoped input/motion wrapper produced by
GestureState::bind. - Gesture
State - Retain one handle per logical control. Clones share input/motion state. Mouse release outside the hitbox, lost button, Escape, blur and deactivation clear ownership. Pinch and supported native touch gestures are opt-in; raw multi-touch availability depends on the backend/platform.
- Gesture
Targets - Partial interaction targets. Priority is in-view, hover, focus, press, then drag.
- Graph
State - View-owned native clock for a portable motion-value graph. Keep this state alive and notify after source/control changes.
- Graph
Subscription - Retain this handle while listening. Dropping it disables the callback immediately.
- InView
- Retained visibility threshold with optional once-only triggering.
- Inertia
- Deceleration and optional hard bounds for inertial motion.
- Interaction
- Current input state supplied by normal native input/focus handlers.
- Invalid
Easing - Invalid cubic Bezier controls or custom easing endpoint/derivative contract.
- Invalid
Spring - Invalid physical parameters, visual timing, bounce, or settling tolerances.
- Keyframe
- One timed target. A missing target holds the previous value, or current presentation at zero.
- Layout
Group - A view-owned coordinate scope for automatic position-only layout animation. Clone shares the ancestor scope; retain one group across renders and use that same group for nested animated elements. Independent groups should not nest. Element history is owned by CE’s keyed element state and lasts while mounted.
- Layout
Position Element - Transparent native wrapper produced by
LayoutGroup::position. Its child’s paint, hitboxes and accessibility bounds receive the same prepaint translation. No scale/rotation, size projection, or cross-parent shared IDs. - Layout
Position Frame - A measured position and the offset needed to display its animated presentation. Units are logical pixels in a consistent caller-chosen coordinate space.
- Layout
Position State - Retained position-only layout sampler. First measurement snaps, later measurements
interrupt from the current presentation and preserve spring velocity. Sampling allocates
no memory. The optional native
LayoutGroupsupplies measurements automatically. - Layout
Rect - Window-space logical-pixel rectangle. Dimensions are finite and non-negative.
- Motion
- A disposable declaration of desired state. Keep its
MotionStatealive. - Motion
Anchor - Retained measurement of one native element in logical window coordinates.
Mount each anchor once. Clones share storage.
clearreleases a stale measurement before reusing the owner in another window. - Motion
Config - Explicit application-owned defaults. Pass this value through render helpers; it does not install a global provider or override the OS reduced-motion policy.
- Motion
Event - One sampled graph event. Velocity uses value units per second.
- Motion
Graph - Acyclic, insertion-ordered motion graph. Sources must precede their dependants. Setup allocates; sampling reuses nodes, scratch storage and listeners. Callbacks run after all derived values update. Defer edits to this graph until callbacks return; they may update other application state or cancel their subscriptions.
- Motion
Node - One prepared node. Add parents before children, making cycles impossible.
- Motion
State - Retained motion for one logical object, owned by a view or keyed collection.
- Motion
Tree - An explicitly retained tree of independently interruptible motion states. Variant changes validate before mutation and capture the old presentation at the change timestamp. Gated nodes hold their local clock and velocity until eligible. Sequencing starts at the next sampled frame boundary, not through a timer. Preparation allocates; normal sampling does not. Host owns focus policy.
- Motion
Tree State - Native owner for a portable variant tree; shares the graph’s explicit clock contract.
- Motion
Value - A retained scalar motion value, with no timers, observers, or heap allocations. Feed its samples into any native style, paint parameter, text, or derived value. Arithmetic at numeric extremes saturates to finite limits; indeterminate overflow resolves to zero. Use ordinary UI-sized units for meaningful physical trajectories.
- Number
Element - Styled count declaration. Number formatting reserves at most 256 minimum digits.
- Number
Format - Reusable locale-configurable formatting, with explicit separators, affixes, digit alphabet and primary/secondary groups. No implicit OS locale or CLDR dependency is installed. Currency/percent conversion and rounding belong to the caller; this formatter preserves the provided fixed-point value exactly.
- Number
Format Error - An invalid fixed-point scale or number-format configuration.
- Number
Motion State - Retained count animation. Unchanged digits match by place value, from the right.
- Path
Frame - Borrowed sampled geometry. Stroke length is approximate; fills retain curves.
- Path
Measure - Immutable arc-length lookup. Curves use the engine’s 32-step approximation. Separate subpaths do not introduce connecting segments. Setup allocates; repeated queries use binary search and allocate no memory.
- Path
Morph State - Retained compatible topology morph. Construction allocates its reusable scalar, command and length buffers. Sampling/reveal iteration do not allocate. Springs retain velocity for every control coordinate at interruption.
- Path
Point - A position and forward tangent on a prepared path.
- Path
Shape - Immutable shared absolute path. Curves retain their controls for exact native fill; stroke length/reveal uses 32 equal-parameter segments per curve. Prepare paths once. Coordinates are bounded to ±1e9 logical pixels to keep native tessellation and length arithmetic in a useful finite range.
- Pinch
Gesture - Native pinch event. Scale is relative to the beginning of this gesture; translating a normal subtree or scaling an SVG remains an application mapping.
- Playback
- An explicit monotonic playback clock. It performs no scheduling.
- PopElement
- Native wrapper constructed by
PopLayout. - PopLayout
- Retain in the view. A container records its origin; exiting items reserve no
flow space but remain at their last measured parent-relative bounds. Use the
same container and retain outgoing content with
PresenceGroupuntil exit finishes. Ancestor clipping still applies. Independent containers must use separate handles; this is not cross-parent projection. - PopRequest
- Per-frame layout data for a popped element. Native implementations should use
PopLayout::item; this type only appears through theElementtrait. - Presence
Child - A retained key and its requested presence. Exiting keys stay mounted.
- Presence
Group - Keyed enter/exit coordination. Allocates only on membership changes, never on sampling.
Call
finish_exitafter a child’sFrame::is_mountedbecomes false. - Reorder
Element - Native spatial reorder item.
- Reorder
Group - Retained logical order and measured spatial geometry. Mouse/keyboard input, cancellation and optional edge autoscroll share the portable engine. Automatic axis detection occurs on acquisition. Host owns model persistence and focus restoration after removal. Cross-list transfer and virtualization are separate application policies; keep this group’s mounted geometry in one scroll source.
- Rich
Text - Immutable, reusable styled display text. The complete string is shaped before animation units are split, preserving GPUI’s font fallback and cluster boundaries.
- Scramble
- Deterministic visual substitutions. The logical accessibility text is unchanged.
- Scroll
Edge - Fractional intersection of a target and its container, with a pixel adjustment.
Fractions may be outside
0..=1, permitting anticipation and overscroll ranges. - Scroll
Frame - Native scroll sample, also suitable for feeding a portable graph or typed track.
- Scroll
Motion - Binds native scroll progress to partial numeric targets. Defaults to instant mapping; choose a spring for smoothing. Layout extent changes trigger a follow-up frame, so the previous measurement cannot remain stale after resize. Preserve its CE-scoped ID and configure styles before wrapping.
- Scroll
Offsets - Two measured scroll intersections, independent of browser string parsing.
- Scroll
Tracker - Tracks an element’s progress through another measured element, with configurable intersections, margins and optional spring smoothing. Retain anchors and this state; render their wrappers in the same window.
- Shared
Element - Native position/crossfade appearance constructed by
SharedLayout::member. - Shared
Layout - View-owned shared identity registry. Exactly one active destination per key
is required. Render incoming/outgoing appearances in a common overlay; retain
outgoing content until its normal presence exit completes. Native clipping
still applies, sizes change immediately, and independent scrolling coordinate
spaces are not reconciled. This is position/crossfade, not full
layoutId. Clones share storage. Callremovewhen a logical shared identity is finished. - Shared
Overlay - Window-root coordinator connecting anchors in separate containers. Render its floating appearances in an unclipped root layer. Anchor geometry is reconciled in window coordinates, including explicitly tracked scrolling. Sizes can follow measured destinations through real layout; no scale projection or transformed clipping is installed. One active appearance per key is required. The host retains exits and owns focus/input policy.
- Shared
Overlay Element - Frame-scoped, window-coordinate position/crossfade appearance.
- Spring
- A settling damped spring. Parameters use seconds and animated logical units.
- Stroke
Reveal - Normalized line drawing. Length and gap are fractions of total path length; offset shifts the pattern along the path. Zero length paints nothing. A zero gap paints continuously. At most 4096 periods are allowed to bound paint cost.
- Style
Frame - Sampled style properties, ready to apply with the native feature.
- Style
Motion - Disposable declaration of style destinations and timing.
- Style
Motion State - Retained allocation-free style sampler. Springs preserve each channel’s momentum; fields omitted after introduction retain their destination.
- Style
Target - Partial style destination. Omitted properties preserve the element’s styles until introduced; subsequently they retain their last declared destination.
- SvgFrame
- A sampled SVG drawing transform. No layout, clipping, or hitbox changes are implied.
- SvgMotion
- Disposable SVG transform declaration; retain one
SvgMotionStateper logical SVG. This does not transform a GPUI subtree or add native children to an SVG. - SvgMotion
State - Allocation-free SVG transform state using the same analytic scalar engine as native motion. Springs preserve position and velocity at interruption; tweens preserve position.
- SvgTarget
- SVG-only scale, rotation and translation destination. Defaults to unit scale and zero rotation.
Negative scale mirrors an axis; zero collapses it. Rotation is unwrapped degrees:
0 -> 720makes two turns; use350 -> 370to cross zero by the short route. - Target
- Opacity, offsets, and optional width, height, and border radius in logical pixels.
- Text
Element - Styled native text declaration created by
TextMotionState::element. Layout takes destination sizes immediately; usereflowfor position motion. This is display text, not an editable or selectable input implementation. - Text
Layout Unit - A renderer-prepared text unit. Geometry is relative to the complete text element.
- Text
Motion State - View-owned native text motion. Clones share lifecycle and shape caches. Retain one state per logical label, with one mounted element per state. Fonts and full runs are shaped before splitting; native glyph atlas painting preserves kerning, contextual forms, bidi positions, and emoji.
- Text
Options - Portable text configuration. Native element builders expose the same options.
- Text
Playback State - Renderer-independent text lifecycle and playback. Retain it beside prepared
glyph data and reconcile only after content, configuration, or layout changes.
No allocations occur in
sample; reconciliation allocates membership storage. - Text
Presentation - A sampled unit. Geometry and opacity are drawing values; retained spring state remains unclamped so reversals preserve its momentum.
- Text
Span - One immutable display-text span. Font size and line height remain label-wide, matching the pinned GPUI shaping API. Selection and editing are not provided.
- Text
Target - Text-relative offsets, opacity, and horizontal reveal fraction. Builders panic on non-finite offsets or fractions outside zero through one.
- Text
Unit Info - Metadata supplied once when preparing each unit’s custom entrance.
- Timeline
- A retained, allocation-free-at-sample timeline. Tracks target separate caller-owned elements.
- TrackId
- Typed track identity, scoped to the timeline that created it.
- Typed
Animation - Immutable typed clip. Channels use the same solver as ordinary
Animation; interruption preserves each spring channel’s own velocity. Prepare once. - Typed
Frame - Sampled typed presentation and scheduling state.
- Typed
Keyframe - A normalized typed keyframe;
currentcaptures each channel’s presentation. - Typed
State - Retained independent channel trajectories. No allocation occurs in sampling.
- Typed
Timeline - A heterogeneous timeline of scalar, color, style, SVG and target tracks. Track setup allocates; samples reuse each track’s state. Deferred tracks keep scheduling even before their first visible sample. Ownership is explicit.
- Value
Frame - A scalar presentation and its velocity, in caller-chosen units per second.
- ValueId
- Identity of a value inside one graph. Values from different graphs cannot mix.
- Variants
- Named declarations. Keys can be application enums; propagation is explicit in Rust.
- Vector
Element - Fixed-size native vector drawing. This paints vector geometry, not an SVG sprite or a GPUI subtree; it does not install pointer semantics.
- Vector
State - Retain one vector state per drawing. Clones share morph/reveal storage. Path sampling allocates no memory; native tessellation/paint preparation does.
Enums§
- Animation
Error - Invalid prepared animation, timing, or orchestration input.
- Axis
- Native scroll axis.
- Children
Order - Timing relationship between an element and its direct children.
- Color
Property - Native color tracks, interpolated in linear light.
- Completion
Status - Result of a trajectory observed by a completion future.
- Easing
- Easing curves for duration-based transitions.
- Gesture
Phase - Native pointer/pinch lifecycle phase.
- Graph
Error - A graph operation referred to another owner or attempted to edit a derived value.
- Motion
Event Kind - Coalesced lifecycle event delivered after a graph’s entire dependency pass.
- Number
Effect - Digit transitions. Rolling and sliding retain unchanged digits by place value.
- Path
Command - Absolute path commands in logical pixels. Subpaths start with Move.
- Path
Error - Recoverable geometry, topology, tessellation or dash-budget failure.
- Presence
- Lifecycle of a retained element. Exit completes only after all channels settle.
- Presence
Mode - How new keys enter while removed children finish exiting.
- Property
- A typed property for per-property transition configuration.
- Reorder
Axis - Reorder detection mode, independent of native scroll axes.
- Repeat
- Additional cycles after the first cycle.
- Repeat
Mode - How repeated clips travel between their endpoints.
- Size
Axis - Which measured dimensions interpolate. Other dimensions follow content immediately.
- Stagger
From - Origin of a staggered group.
- Style
Property - Scalar style properties in logical pixels. Margins and shadow offsets/spread may be negative; the other properties require non-negative targets.
- SvgPath
Error - SVG grammar or bounded-geometry preparation failure.
- Text
Clip - Stationary clipping around each unit’s final layout reservation.
- Text
Error - Native text failures, independent of the chosen GPUI backend.
- Text
Match - Identity policy when the requested text changes.
- Text
Preset - Convenience effects. A subsequent
enterorexitoverrides that target. - Text
Reveal Axis - Axis of an axis-aligned text reveal mask.
- Text
Unit - Grouping for text motion. Native adapters merge boundaries inside shaped clusters.
- Transition
- A transition between presentation and target values.
- Tree
Error - Invalid tree identity or a variant missing from an affected node.
Traits§
- Motion
Data - Fixed numeric representation of a typed animation value. Implementations must
return finite channels and reconstruct drawable values without allocating.
compatibleidentifies an unchanged property mask; keyframes cannot silently introduce/remove properties. Implement this for application-owned value types.
Functions§
- move_
item - Moves an item without reallocating or changing its identity. Invalid indices return an error.
- native_
scroll_ progress - Reads native scroll offsets and extents; unscrollable content returns zero. Handles CE’s negative scroll offsets and positive maximum extents.
- reorder_
index - Finds the nearest destination in a sorted list of item centers, for native reorder UIs.
- scroll_
progress - Normalizes a positive scroll offset using measured content and viewport extents. An unscrollable viewport reports zero. Panics for invalid metrics.
- stagger
- Computes a child’s delay without allocating. Center origins support half-step offsets.
- text_
ranges - Unicode segmentation for a custom renderer.
Lineshere means explicit newline lines; native adapters replace these with measured visual wrapped lines. - transform
- Maps a finite scalar between ranges, optionally clamping progress. Supports reversed input/output ranges. Panics for non-finite or zero input span.