Skip to main content

Crate gpui_ce_motion

Crate gpui_ce_motion 

Source
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§

AnchorElement
Frame-scoped measuring wrapper created by MotionAnchor::element.
Animation
A prepared, cheaply cloned clip. Construct once outside rendering; clones share keyframes.
AnimationState
Retained playback for a prepared clip. New clips interrupt from current presentation.
AutoScroll
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.
AutoSize
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.
ColorState
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.
CustomEasing
Prepared application easing. Copies preserve identity so repeated declarations do not restart. Call new once, 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.
DragBounds
Allowed drag offsets relative to an element’s untranslated layout rectangle.
DragEvent
Structured pointer information in logical window pixels.
FixedNumber
Exact signed decimal coefficient with zero through eighteen fractional places. For example FixedNumber::new(12345, 2) represents 123.45 without float rounding.
FormattedNumber
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.
GeometryError
Invalid finite geometry, scroll range, or edge-scroll configuration.
GestureElement
Frame-scoped input/motion wrapper produced by GestureState::bind.
GestureState
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.
GestureTargets
Partial interaction targets. Priority is in-view, hover, focus, press, then drag.
GraphState
View-owned native clock for a portable motion-value graph. Keep this state alive and notify after source/control changes.
GraphSubscription
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.
InvalidEasing
Invalid cubic Bezier controls or custom easing endpoint/derivative contract.
InvalidSpring
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.
LayoutGroup
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.
LayoutPositionElement
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.
LayoutPositionFrame
A measured position and the offset needed to display its animated presentation. Units are logical pixels in a consistent caller-chosen coordinate space.
LayoutPositionState
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 LayoutGroup supplies measurements automatically.
LayoutRect
Window-space logical-pixel rectangle. Dimensions are finite and non-negative.
Motion
A disposable declaration of desired state. Keep its MotionState alive.
MotionAnchor
Retained measurement of one native element in logical window coordinates. Mount each anchor once. Clones share storage. clear releases a stale measurement before reusing the owner in another window.
MotionConfig
Explicit application-owned defaults. Pass this value through render helpers; it does not install a global provider or override the OS reduced-motion policy.
MotionEvent
One sampled graph event. Velocity uses value units per second.
MotionGraph
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.
MotionNode
One prepared node. Add parents before children, making cycles impossible.
MotionState
Retained motion for one logical object, owned by a view or keyed collection.
MotionTree
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.
MotionTreeState
Native owner for a portable variant tree; shares the graph’s explicit clock contract.
MotionValue
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.
NumberElement
Styled count declaration. Number formatting reserves at most 256 minimum digits.
NumberFormat
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.
NumberFormatError
An invalid fixed-point scale or number-format configuration.
NumberMotionState
Retained count animation. Unchanged digits match by place value, from the right.
PathFrame
Borrowed sampled geometry. Stroke length is approximate; fills retain curves.
PathMeasure
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.
PathMorphState
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.
PathPoint
A position and forward tangent on a prepared path.
PathShape
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.
PinchGesture
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 PresenceGroup until 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 the Element trait.
PresenceChild
A retained key and its requested presence. Exiting keys stay mounted.
PresenceGroup
Keyed enter/exit coordination. Allocates only on membership changes, never on sampling. Call finish_exit after a child’s Frame::is_mounted becomes false.
ReorderElement
Native spatial reorder item.
ReorderGroup
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.
RichText
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.
ScrollEdge
Fractional intersection of a target and its container, with a pixel adjustment. Fractions may be outside 0..=1, permitting anticipation and overscroll ranges.
ScrollFrame
Native scroll sample, also suitable for feeding a portable graph or typed track.
ScrollMotion
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.
ScrollOffsets
Two measured scroll intersections, independent of browser string parsing.
ScrollTracker
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.
SharedElement
Native position/crossfade appearance constructed by SharedLayout::member.
SharedLayout
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. Call remove when a logical shared identity is finished.
SharedOverlay
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.
SharedOverlayElement
Frame-scoped, window-coordinate position/crossfade appearance.
Spring
A settling damped spring. Parameters use seconds and animated logical units.
StrokeReveal
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.
StyleFrame
Sampled style properties, ready to apply with the native feature.
StyleMotion
Disposable declaration of style destinations and timing.
StyleMotionState
Retained allocation-free style sampler. Springs preserve each channel’s momentum; fields omitted after introduction retain their destination.
StyleTarget
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 SvgMotionState per logical SVG. This does not transform a GPUI subtree or add native children to an SVG.
SvgMotionState
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 -> 720 makes two turns; use 350 -> 370 to cross zero by the short route.
Target
Opacity, offsets, and optional width, height, and border radius in logical pixels.
TextElement
Styled native text declaration created by TextMotionState::element. Layout takes destination sizes immediately; use reflow for position motion. This is display text, not an editable or selectable input implementation.
TextLayoutUnit
A renderer-prepared text unit. Geometry is relative to the complete text element.
TextMotionState
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.
TextOptions
Portable text configuration. Native element builders expose the same options.
TextPlaybackState
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.
TextPresentation
A sampled unit. Geometry and opacity are drawing values; retained spring state remains unclamped so reversals preserve its momentum.
TextSpan
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.
TextTarget
Text-relative offsets, opacity, and horizontal reveal fraction. Builders panic on non-finite offsets or fractions outside zero through one.
TextUnitInfo
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.
TypedAnimation
Immutable typed clip. Channels use the same solver as ordinary Animation; interruption preserves each spring channel’s own velocity. Prepare once.
TypedFrame
Sampled typed presentation and scheduling state.
TypedKeyframe
A normalized typed keyframe; current captures each channel’s presentation.
TypedState
Retained independent channel trajectories. No allocation occurs in sampling.
TypedTimeline
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.
ValueFrame
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.
VectorElement
Fixed-size native vector drawing. This paints vector geometry, not an SVG sprite or a GPUI subtree; it does not install pointer semantics.
VectorState
Retain one vector state per drawing. Clones share morph/reveal storage. Path sampling allocates no memory; native tessellation/paint preparation does.

Enums§

AnimationError
Invalid prepared animation, timing, or orchestration input.
Axis
Native scroll axis.
ChildrenOrder
Timing relationship between an element and its direct children.
ColorProperty
Native color tracks, interpolated in linear light.
CompletionStatus
Result of a trajectory observed by a completion future.
Easing
Easing curves for duration-based transitions.
GesturePhase
Native pointer/pinch lifecycle phase.
GraphError
A graph operation referred to another owner or attempted to edit a derived value.
MotionEventKind
Coalesced lifecycle event delivered after a graph’s entire dependency pass.
NumberEffect
Digit transitions. Rolling and sliding retain unchanged digits by place value.
PathCommand
Absolute path commands in logical pixels. Subpaths start with Move.
PathError
Recoverable geometry, topology, tessellation or dash-budget failure.
Presence
Lifecycle of a retained element. Exit completes only after all channels settle.
PresenceMode
How new keys enter while removed children finish exiting.
Property
A typed property for per-property transition configuration.
ReorderAxis
Reorder detection mode, independent of native scroll axes.
Repeat
Additional cycles after the first cycle.
RepeatMode
How repeated clips travel between their endpoints.
SizeAxis
Which measured dimensions interpolate. Other dimensions follow content immediately.
StaggerFrom
Origin of a staggered group.
StyleProperty
Scalar style properties in logical pixels. Margins and shadow offsets/spread may be negative; the other properties require non-negative targets.
SvgPathError
SVG grammar or bounded-geometry preparation failure.
TextClip
Stationary clipping around each unit’s final layout reservation.
TextError
Native text failures, independent of the chosen GPUI backend.
TextMatch
Identity policy when the requested text changes.
TextPreset
Convenience effects. A subsequent enter or exit overrides that target.
TextRevealAxis
Axis of an axis-aligned text reveal mask.
TextUnit
Grouping for text motion. Native adapters merge boundaries inside shaped clusters.
Transition
A transition between presentation and target values.
TreeError
Invalid tree identity or a variant missing from an affected node.

Traits§

MotionData
Fixed numeric representation of a typed animation value. Implementations must return finite channels and reconstruct drawable values without allocating. compatible identifies 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. Lines here 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.