Skip to content

Primitives

The internal building blocks M3 components are made from, exported for custom controls.

import { useM3SpringValue, useM3SpringValues, useEntrance, useKeepPressedInPlace, useNearestReveal, usePageHeight, useReorder, useSliderTouchTrack, useScrollRestoration, useScrollKeys, useLabels, useRevealEntering, useM3Interaction, useM3Morph, useM3Spring, usePresence, useKeyboardInset, useTriggerProps } from '@windmorph/react/primitives';

Hooks

useM3SpringValue

useM3SpringValue signature
useM3SpringValue(target: number, options?: M3SpringValueOptions): MotionValue<number>

A Motion value that springs to each new target on the theme's spring (the nearest ThemeScope's motion scheme), from where it is and at the speed it has: a new target mid-move doesn't restart from rest. Under prefers-reduced-motion a spatial value jumps to each target, as the spatial tokens are 0ms there; an effects value keeps its spring, as fades do. On the server and in the first render it is the target.

  • targettype numberRequired

    Where the value goes; each new one starts a move.

  • optionstype M3SpringValueOptions
  • options.familytype "spatial" | "effects"default "spatial"

    Spatial for positions and sizes, effects for opacity and colour.

  • options.speedtype "fast" | "default" | "slow"default "default"
  • options.delaytype numberdefault 0

    Seconds a move from rest waits before it starts (an entrance one after another); a value already moving turns to a new target at once.

  • options.animatetype booleandefault true

    false jumps to each target: off screen, or in a hidden tab.

Returns MotionValue<number>

useM3SpringValues

useM3SpringValues signature
useM3SpringValues(targets: readonly number[], options?: M3SpringValuesOptions): MotionValue<readonly number[]>

A list of numbers that springs as one to each new targets, on the theme's spring: a line's points, a stack's bars. Each element keeps its own position and speed when a new list arrives mid-move, and a list of another length starts from the old one read at the new places (resample), so a 7-point line becomes an 84-point one by moving. One frame callback advances every element with the closed-form spring, so a long list is one loop. A spatial list under reduced motion and animate: false jump, as useM3SpringValue does. On the server and in the first render it is targets.

  • targetstype readonly number[]Required

    Where the elements go; a list with any element changed starts a move.

  • optionstype M3SpringValuesOptions
  • options.delaytype number | readonly number[]default 0

    Seconds each element waits before a move from rest: one for all, or one per element. An element already moving turns to its new target at once.

  • options.resttype number | readonly number[] | ((shown: readonly number[]) => readonly number[])default 0

    Where a new element starts: one for all, one per element (a point entering at its own place), or worked out from the list as it shows at the change (shown, in the old list's order: a point entering on a line where the line is), one entry per element of the new list, of which only new elements' are used; asked only when an element is new. Used for every element when there was no list before, and for each new key.

  • options.keystype readonly string[]

    Names each element (unique, one per target), so a new list is matched to the old one by name rather than by place: a kept key moves on from where its element is, at its speed, and a new key starts at rest (a window of a feed sliding on: kept bars carry on, a new one grows from the baseline). Without keys, elements match by place, and a list of another length starts from the old one read at the new places.

  • options.familytype "spatial" | "effects"default "spatial"

    Spatial for positions and sizes, effects for opacity and colour.

  • options.speedtype "fast" | "default" | "slow"default "default"
  • options.animatetype booleandefault true

    false jumps to each target: off screen, or in a hidden tab.

Returns MotionValue<readonly number[]>

useEntrance

useEntrance signature
useEntrance(ref: RefObject<Element | null>, options?: EntranceOptions): EntranceResult

Whether an element's entrance should play: once, when it first comes into view, so motion nobody saw isn't wasted. Never for content that was on screen as the page hydrated: its final picture was in the server's HTML, and replaying it from nothing would flash. Content server-rendered out of view switches to its start state unseen and enters when scrolled to; content the browser mounts later enters as it comes into view. A hidden tab waits until it shows. On beforeprint the element enters and is out of view until afterprint, committed before the print is laid out, so what React renders from entered (text, an attribute, a style or CSS variable) prints in its final state. A print runs no frames, though: a Motion value moved by it jumps to its target, but Motion writes the styles bound to that value on its next frame, so a mark drawn from a Motion value needs a print value in CSS (its resting geometry written as a CSS variable and applied under @media print), as AnimatedNumber prints its final value. Every entrance on the page commits in the same render, from one shared listener. A print begun inside React's own work (window.print() from an effect, as a print view does) is laid out before this update renders, and only CSS reaches it (React warns once that it couldn't flush): start a print from a press, or from an effect through a setTimeout, so what React renders from entered prints. On the server entered is true.

  • reftype RefObject<Element | null>Required

    The element whose entrance it is; it must be rendered by the time effects run.

  • optionstype EntranceOptions
  • options.amounttype numberdefault 0.25

    How far into the window an element must come before its entrance plays, from 0 (any part showing) to 1 (to the middle): past that share of half the window's height from its top or bottom, so 0.25 is an eighth of the window in. One shown whole enters wherever it is. The browser measures what shows, so an element of any size, one that changes size, or one in a box that clips it enters as it comes into view.

Returns EntranceResult

  • enteredtype booleanRequired

    Whether the element shows its final state. false only while an entrance is waiting to play: show the start state (bars at their baseline, a number at its start). It turns true once, as the element first comes into view or the page is printed; under reduced motion it is always true, so nothing waits at its start to jump in (a fade-in waiting for it doesn't play either). The preference is read as the element mounts (Motion's useReducedMotion doesn't follow a change), so a new setting reaches it on a remount; once entered under reduced motion, it stays entered.

  • inViewtype booleanRequired

    Whether the element is in view now, so a change is worth animating. false while the page prints, on screen or not: a print runs no frames to animate in.

useKeepPressedInPlace

useKeepPressedInPlace signature
useKeepPressedInPlace(selector: string, version: unknown, settling: boolean): KeepPressedInPlaceResult

Keeps the element a person pressed where it was on screen while the content above it changes size because of that press. When a press opens one item while an open item above it folds (a one-at-a-time tree or accordion), the pressed element would otherwise slide up by the folded height, off the window when the fold starts above it; with this hook its scroller scrolls by the folded height on every frame instead, so nothing moves out from under the person. The core List uses it for its tree grid (2026-10-17).

When to use it: in a container of your own whose items open and fold in response to a press, where an item above the pressed one can fold (or grow) at the same time. Pair it with overflow-anchor: none on the folding parts: the browser's scroll anchoring then holds the pressed element on its own whenever it is the first thing showing below them, and this hook covers the rest (the anchor the browser picks above it, such as the folding item's own header or content above the container) and browsers without scroll anchoring.

Wiring: put capture on the container as onPointerDownCapture and onKeyDownCapture, and release as onPointerUpCapture and onKeyUpCapture. A virtual click (assistive tech, event.detail === 0) presses with no pointer or key down before it, so onClickCapture calls capture for it, then release for every click.

What it notes: on a pointer down, a key down or a virtual click, the element selector finds from the event's target (closest), its top on screen, its scroller (the nearest scrolling ancestor, else the page) and the scroller's position. A press outside selector clears it.

When it acts: when version next changes (any value that changes whenever the content the press changed does, such as the open keys or the rows shown): in a layout effect, before the change paints, it scrolls by however far the element moved, which covers a change with no motion (reduced motion); then again on every animation frame while settling is true (the folding parts are still moving), and once more after.

When it lets go: on the next wheel, touch, pointer down or key down anywhere (the person is scrolling or acting again), when settling turns false, when the element leaves the page, or on unmount. It ignores a press after which the scroller moved before the change (the person scrolled), and forgets a press that changed nothing by the next task, so it never holds a later, unrelated change.

  • selectortype stringRequired

    A CSS selector for the pressable items ('[role=row]').

  • versiontype unknownRequired

    Changes whenever the content changes.

  • settlingtype booleanRequired

    Whether the content is still moving after the change (parts still folding).

Returns KeepPressedInPlaceResult: capture and release, the container's event handlers.

  • capturetype (event: React.SyntheticEvent<Element, Event>) => voidRequired

    Notes the pressed element: the container's onPointerDownCapture and onKeyDownCapture, and its onClickCapture for a virtual click (event.detail === 0).

  • releasetype () => voidRequired

    Forgets a press that changed nothing, by the next task: the container's onPointerUpCapture, onKeyUpCapture and onClickCapture.

useNearestReveal

useNearestReveal signature
useNearestReveal(rootRef: RefObject<HTMLElement | null>): void

Arrow keys must not jump the page. When keyboard focus moves to an item, React Aria reveals it by calling scrollIntoView({ block: 'center', inline: 'center' }) on the collection's root whenever the root isn't wholly on screen, which scrolls every ancestor, the window included, to centre the root (176px for a tab row, 200px for a list taller than the window), and then reveals the item. The root's own scrollIntoView asks for the nearest position instead, so the page moves only as far as the item needs (2026-10-15).

Public in /primitives (2026-11-17) for collections built on React Aria's hooks outside the core, such as a grid that scrolls inside a box of its own.

  • rootReftype RefObject<HTMLElement | null>Required

    The element React Aria's collection hook was given: a list, tab row or grid.

Returns void

usePageHeight

usePageHeight signature
usePageHeight(level: number): readonly [React.RefObject<T | null>, PageHeight]

Measures the pages of a popover whose submenus show in place (submenuPresentation="replace") for its surface, which holds their height: once as each page goes in (level changes), in the same commit, so the surface springs from the old height from the first frame on; and again whenever their size changes otherwise (a web font arriving, new text), which the surface follows at once, as useNaturalSize's resized does. The pages keep their natural height (capped by the popover's maximum), whatever the surface's.

  • leveltype numberRequired

Returns readonly [React.RefObject<T | null>, PageHeight]

useReorder

useReorder signature
useReorder(options: ReorderOptions<K>): ReorderResult<K>

The engine of a list whose rows a person puts in order (docs/plans/list-reorder.md): a drag from a row's handle that the row itself follows while the rows it passes slide out of its way, moves by action (up, down, to the top or the bottom), and a cancel. It has no look and no words: the component gives both, and keeps focus on lastMoved. The order is controlled: onReorder is called once, on the drop or the action.

  • optionstype ReorderOptions<K>Required
  • options.keystype readonly K[]Required

    The rows' keys, in the order shown (controlled).

  • options.listReftype React.RefObject<HTMLElement | null>Required

    The element holding the rows; each row carries itemProps(key).

  • options.onReordertype (keys: K[], move: ReorderMove<K>) => voidRequired

    Called once, on a drop or a move by action, with every key in the new order.

  • options.isMovabletype (key: K) => booleandefault every row

    Whether a row can move; one that can't is a wall nothing passes.

  • options.onDragChangetype (event: { key: K; phase: "start" | "drop" | "cancel"; to?: number | undefined; }) => void

    Called as a drag starts, ends (dropped or not) and when it's cancelled.

  • options.thresholdtype numberdefault 4

    How far the pointer moves before a press becomes a drag, in px.

  • options.scrollEdgetype numberdefault 48

    How near a scroller's edge it starts to scroll while dragging, in px.

  • options.slidetype { duration: string; easing: string; }

    The slide of rows changing place (a CSS transition's duration and easing); none: at once. The hook doesn't read reduced motion: pass a duration that resolves to 0 there (a motion token does), or leave the slide out.

Returns ReorderResult<K>

  • draggedtype K | nullRequired

    The row being dragged, once past the threshold.

  • targettype number | nullRequired

    Where the dragged row would land.

  • lastMovedtype { key: K; by: "drag" | "action"; } | nullRequired

    The row a move or a drop last moved, until the next; the caller keeps focus on it.

  • itemPropstype (key: K) => { 'data-reorder-key': string; 'data-dragged'?: true | undefined; style?: React.CSSProperties | undefined; }Required

    Props for a row's element.

  • handlePropstype (key: K) => { onPointerDown: (event: React.PointerEvent<HTMLElement>) => void; style: React.CSSProperties; }Required

    Props for a row's handle: the drag starts from it. Its style holds touch-action: none, since only CSS stops a finger on the handle from scrolling the page instead of dragging; merge it with the handle's own style.

  • movetype (key: K, where: ReorderWhere) => voidRequired

    Moves a row by action.

  • canMovetype (key: K, where: ReorderWhere) => booleanRequired

    Whether that move leads somewhere.

  • canceltype () => voidRequired

    Cancels a drag under way: the row goes back.

useSliderTouchTrack

useSliderTouchTrack signature
useSliderTouchTrack(trackProps: HTMLAttributes<HTMLElement>, options: SliderTouchTrackOptions): React.HTMLAttributes<HTMLElement>

Touch and pen presses on a slider's track, as Compose's slider takes them (Slider.kt: draggable(orientation) and a tap that sets the value on release). React Aria sets the value on pointer down and claims every move, so a vertical swipe that started on a horizontal slider changed its value and never scrolled the page. Here a touch changes nothing until it either lifts (a tap: the nearest thumb jumps there) or moves TOUCH_SLOP along the track (a drag: the nearest thumb follows the finger). A swipe across the track is left to the browser, which scrolls (the slider's touch-action allows the cross axis) and cancels the pointer. Mouse presses keep React Aria's handling.

With drawn stops (discrete), every press, the mouse's too, maps through the corner inset the stops and thumb are drawn with ((offset − corner) / (length − 2 × corner)), so a tap on a drawn stop selects that stop: React Aria's linear mapping picked the next one near the ends of a large slider, whose corners are wider than half a step (2026-10-17).

A press that starts on an element marked data-thumb is left to React Aria's thumb handling, which drags that thumb.

Returns handlers that wrap React Aria's trackProps. Public (@windmorph/react/primitives) for any slider built on React Aria's useSlider outside the core, so its track takes touches as this one does.

  • trackPropstype HTMLAttributes<HTMLElement>Required
  • optionstype SliderTouchTrackOptionsRequired
  • options.statetype SliderStateRequired

    The slider's state (React Stately's useSliderState), whose thumbs the touch moves.

  • options.trackReftype React.RefObject<HTMLElement | null>Required

    The element a press maps to a value along: the one given useSlider's trackProps.

  • options.orientationtype "vertical" | "horizontal"Required

    The way the track runs; a touch across it is left to the browser to scroll.

  • options.directiontype "ltr" | "rtl"Required

    The reading direction (React Aria's useLocale): a horizontal track runs from the right in right to left.

  • options.disabledtype booleanRequired

    Leaves every press to React Aria, which ignores it.

  • options.discretetype booleandefault false

    The values are spread between the track's corners, as a discrete slider's drawn stops are: a press maps back through the same inset, the corner read in px from the track's --m3-slider-corner (0 without it), so a tap on a drawn stop selects it.

Returns React.HTMLAttributes<HTMLElement>

useScrollRestoration

useScrollRestoration signature
useScrollRestoration(ref: RefObject<HTMLElement | null>, options: ScrollRestorationOptions): void

Keeps and restores the scroll position of an element that scrolls by itself (an app frame's pane), per page. Browsers restore only the window's scroll, so with client-side routing such an element comes back at its top, or wherever it was on the page just left, and a reload loses its position too.

A position is kept for each pageKey, in sessionStorage, so a reload restores it too.

A page's position is taken when the person sets off: a press, a key, or back and forward. Never from a scroll after the page changed, since a router can scroll the element to the new page's top first; and never while a restored position is still being held, nor after a hold that ended short of it until the person scrolls, since content still arriving can leave the page short of its position.

Going back or forward (the Navigation API's navigate event, or popstate where it's missing) restores the page's position and holds it for holdFor ms while content arrives; the hold ends the moment the person scrolls.

A new page starts at its top: every other change of pageKey, one of the query alone too.

The element can be left out on some pages (a frame that lays them out without its pane), arrive after the page has changed, or be replaced, while the component that calls the hook stays mounted: pages without it keep nothing, and a restored position is held on whichever element is behind the ref.

Call it in a component that stays mounted as the pages change (a layout): back and forward are seen only while it is mounted.

  • reftype RefObject<HTMLElement | null>Required
  • optionstype ScrollRestorationOptionsRequired
  • options.pageKeytype stringRequired

    Identifies the page shown: the router's path and query, so it works with any router. A position is kept for each key, and a new key starts at the top, so a change of the query alone (a filter, a sort, the next page of results) starts the pane at the top too, as following a link to a new address does. To keep the position while some of the query changes, leave those parts out of the key.

  • options.storageKeytype stringdefault "windmorph-scroll"

    The sessionStorage key the positions are kept under, for an app with more than one such element.

  • options.holdFortype numberdefault 1500

    How long, in ms, a restored position is held while content arrives (images, data): moved by anything but the person in that time (a router, a script), it is put back. The hold ends at once when the person scrolls.

Returns void

useScrollKeys

useScrollKeys signature
useScrollKeys(ref: RefObject<HTMLElement | null>): ScrollKeysResult

Sends the scroll keys to an element that scrolls by itself (an app frame's pane) while nothing has focus. Page Down, Page Up, Home, End, Space and the arrows otherwise go to the window, which has nothing to scroll in such a frame, so the page doesn't move until a click in the pane or a Tab to it. As one of those keys goes down with focus on the body and no Ctrl, Alt or Meta held, the element takes focus (without scrolling), and the browser scrolls it with that same press.

The keys stay with another scrolling element the person last pressed in (a side sheet's content, a list beside the pane): browsers scroll that one while nothing has focus, and the pane doesn't take the keys from it.

Put the returned tabIndex on the element: it is a tab stop only while it holds nothing Tab would reach (watched as its content changes), as browsers do for a scrolling region.

The hook follows the element behind the ref: it can arrive after the first render, go, or be replaced by another (a frame that leaves its pane out on some pages) while the component that calls the hook stays mounted.

  • reftype RefObject<HTMLElement | null>Required

Returns ScrollKeysResult

  • tabIndextype 0 | -1Required

    The tabIndex for the scrolling element: 0 while it holds nothing that takes focus, so a text-only page can be reached and scrolled from the keyboard, and -1 otherwise, so every other page has no extra tab stop. Either way the element can take focus.

useLabels

useLabels signature
useLabels(key: Key | readonly [...LabelsKey[], Key], defaults: Defaults, own: WindmorphLabels[Key]): Defaults & WindmorphLabels[Key] & {}

A component's words: its defaults, then the words a LabelsProvider above gives key (its key in WindmorphLabels; one built from another passes that one's key first), then its own labels. A word left undefined keeps the one below it. The result is the same object until one of the three changes. A component of your own adds its key to WindmorphLabels by declaration merging.

  • keytype Key | readonly [...LabelsKey[], Key]Required
  • defaultstype DefaultsRequired
  • owntype WindmorphLabels[Key]Required

Returns Defaults & WindmorphLabels[Key] & {}

useRevealEntering

useRevealEntering signature
useRevealEntering(placement: string | null, ref: RefObject<HTMLElement | null>): boolean

Holds a menu's reveal closed (data-entering) until React Aria has placed it, then lets it open, so it grows from the edge nearest its anchor.

The reveal's closed clip depends on data-placement (from the top below the anchor, from the bottom above it, from the side beside it). A @starting-style rule is read the first time the element's style is resolved, which React Aria's measuring forces before it has set the placement, so every menu used to open from its top edge. Instead, the closed state is a class with no transition: once the placement is known (before the first paint, as React Aria places in a layout effect), the closed clip for that edge is resolved and the class removed, and the clip and opacity transition open from there.

Should the placement never arrive, the menu opens on the next frame anyway.

  • placementtype string | nullRequired
  • reftype RefObject<HTMLElement | null>Required

Returns boolean

useM3Interaction

useM3Interaction signature
useM3Interaction(options: M3InteractionOptions, ref: RefObject<HTMLElement | null>): M3InteractionResult

M3 interaction states for any element: hover, press, focus-visible, selected, dragged and disabled, exposed as data-* attributes, plus the ripple origin. Pair with the state-layer and focus-ring utilities, which paint the state layer and ripple as background layers on the element itself (no child nodes).

  • optionstype M3InteractionOptionsRequired
  • options.isDisabledtype boolean
  • options.isSelectedtype boolean
  • options.isDraggedtype boolean
  • options.isPressedtype boolean

    Pressed state from another React Aria hook (e.g. useButton). When provided, this hook does not attach its own press handling.

  • options.withintype boolean

    Treat focus inside the element as focus on the element (e.g. text fields).

  • options.isTextInputtype boolean

    Whether the element is a text input; focus is then always visible.

  • options.autoFocustype boolean
  • reftype RefObject<HTMLElement | null>Required

Returns M3InteractionResult

  • interactionPropstype React.DOMAttributes<HTMLElement>Required

    Event handlers to spread on the interactive element.

  • dataAttributestype M3InteractionDataAttributesRequired
  • statetype M3InteractionStateRequired

useM3Morph

useM3Morph signature
useM3Morph(shapes: readonly MorphShape[], progress: MotionValue<number>, options?: M3MorphOptions): MotionValue<string>

Morphs through Material shapes with a Motion value, for an m.path's d. Shapes are the 35 MaterialShapes (by name) or any normalized RoundedPolygon; corners are matched between consecutive shapes as in Compose.

Reduced motion is the caller's call: snap progress instead of springing it.

  • shapestype readonly MorphShape[]Required
  • progresstype MotionValue<number>Required
  • optionstype M3MorphOptions
  • options.sizetype number

    Scales the unit-square shapes, e.g. to the SVG viewBox size. Default 1. Mid-morph control points can poke up to ~1% outside the square, so give the <svg> overflow="visible" or a little padding.

  • options.startAngletype number

    Rotates each frame so its first point sits at this angle (degrees). Default 0.

Returns MotionValue<string>

useM3Spring

useM3Spring signature
useM3Spring(family: SpringFamily, speed?: SpringSpeed): MotionSpring

The Motion spring for the active motion scheme (from ThemeProvider / ThemeScope). prefers-reduced-motion forces the standard scheme, which never visibly overshoots.

  • familytype SpringFamilyRequired
  • speedtype SpringSpeed

Returns MotionSpring

  • typetype "spring"Required
  • stiffnesstype numberRequired
  • dampingtype numberRequired
  • masstype numberRequired

usePresence

usePresence signature
usePresence(isOpen: boolean, property?: string | readonly string[], animated?: boolean): { isPresent: boolean; isExiting: boolean; exitProps: { onTransitionEnd: (event: React.TransitionEvent<HTMLElement>) => void; }; }

Keeps an overlay mounted while it animates out. isPresent turns true as soon as isOpen does and stays true until the exit transition ends (or a fallback timeout). Spread exitProps on the element whose transition of property (default opacity) marks the end; with several properties, the first of them to end does, so an exit that slides normally and fades under reduced motion passes both. With animated false there is no exit motion to wait for, so isPresent follows isOpen at once.

A transition still running in the element or its content when that property ends (a reveal's clip-path that outlasts the fade) is waited for too, within the fallback: removed mid-transition, an element never sends its transitionend, and React Aria, which tracks running transitions until they end, would keep it in memory.

  • isOpentype booleanRequired
  • propertytype string | readonly string[]
  • animatedtype boolean

Returns { isPresent: boolean; isExiting: boolean; exitProps: { onTransitionEnd: (event: React.TransitionEvent<HTMLElement>) => void; }; }

  • isPresenttype booleanRequired
  • isExitingtype booleanRequired
  • exitPropstype { onTransitionEnd: (event: React.TransitionEvent<HTMLElement>) => void; }Required

useKeyboardInset

useKeyboardInset signature
useKeyboardInset(): number

How far the on-screen keyboard covers the window's bottom edge, in px, followed as it opens and closes: where the page lays the keyboard over its content (navigator.virtualKeyboard .overlaysContent, Chromium), the distance from the top of the VirtualKeyboard API's boundingRect to the window's bottom (at most the window's height; 0 for an empty rect), so a floating keyboard partway up the screen counts from its top edge; else from the visual viewport. It reads again on the keyboard's geometrychange and the visual viewport's resize and scroll, which also catches overlaysContent turned on or off while the keyboard is open. 0 on the server, with no keyboard, and while the page is pinch-zoomed.

Returns number

useTriggerProps

useTriggerProps signature
useTriggerProps(own: TriggerContextValue): TriggerContextValue

The value a trigger gives its button: its own props merged into an enclosing trigger's, so triggers nest (a TooltipTrigger around a MenuTrigger, or the other way round) and the button gets both. Handlers are chained, refs merged and ids kept in sync (React Aria mergeProps); for other props the inner trigger wins.

  • owntype TriggerContextValueRequired
  • own.onPresstype (event: PressEvent) => void
  • own.onPressStarttype (event: PressEvent) => void

    Menus open on press start.

  • own.preventFocusOnPresstype boolean

    Menu triggers keep focus where it is on press (React Aria useMenuTrigger).

  • own.aria-haspopuptype boolean | "dialog" | "menu" | "listbox" | "tree" | "grid" | "true" | "false"
  • own.aria-expandedtype boolean
  • own.aria-controlstype string
  • own.data-menu-opentype true

    Set by MenuTrigger while its menu is open: the state layer keeps a pressed layer.

  • own.idtype string
  • own.reftype React.RefObject<HTMLElement | null> | ((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly))

    The trigger element, e.g. for positioning a menu next to it.

Returns TriggerContextValue

  • onPresstype (event: PressEvent) => void
  • onPressStarttype (event: PressEvent) => void

    Menus open on press start.

  • preventFocusOnPresstype boolean

    Menu triggers keep focus where it is on press (React Aria useMenuTrigger).

  • aria-haspopuptype boolean | "dialog" | "menu" | "listbox" | "tree" | "grid" | "true" | "false"
  • aria-expandedtype boolean
  • aria-controlstype string
  • data-menu-opentype true

    Set by MenuTrigger while its menu is open: the state layer keeps a pressed layer.

  • idtype string
  • reftype React.RefObject<HTMLElement | null> | ((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly))

    The trigger element, e.g. for positioning a menu next to it.

The exported surface

Everything re-exported from @windmorph/react/primitives, grouped by what it does:

@windmorph/react/primitives
import {
  // Interaction & structure
  useM3Interaction, ButtonBase, Surface, surfaceStyles, Overlay, TouchTarget,
  // Form field parts
  FieldLabel, SupportingText, ErrorText, CharacterCounter, FieldErrorIcon,
  SelectionControl, selectionControlStyles,
  // Motion
  useM3Spring, getM3Spring, springWithVelocityToLinearEasing, springProgressWithVelocity,
  useM3SpringValue, useM3SpringValues, resample, AnimatedNumber, staggerDelays, useEntrance,
  // Overlay plumbing
  TriggerContext, useTriggerProps, usePresence, DomDirectionLocale, localeWithDirection,
  // The on-screen keyboard
  useKeyboardInset,
  // Scrolling
  useKeepPressedInPlace, useNearestReveal, useScrollRestoration, useScrollKeys,
  useSliderTouchTrack, sliderThumbInputProps, sliderArrowRaises,
  // Building your own component
  splitRootProps, pickWidgetAria, pickDescriptionAria, type RootDOMProps, type WrapperRootDOMProps, type DescriptionAria,
  splitDataAttributes, mergeDataTokens, ThemeScopeContext, generateSchemeColors, themeSelector,
  useLabels, type LabelsKey, type LabelsOf,
  // Static shapes (precomputed outlines, no shape engine)
  type MaterialShapePath, materialShapeMask, materialShapePaths,
  circleShape, cookie12SidedShape, sunnyShape, /* … one <name>Shape per shape */
  // Morph & shapes
  useM3Morph, morphPathAt, getMorph,
  RoundedPolygon, CornerRounding, Cubic, Morph,
  MaterialShapes, materialShapeNames,
  circle, pill, pillStar, rectangle, star,
  polygonToPath, morphToPath, cubicsToPath,
} from '@windmorph/react/primitives';
  • useM3Interaction — wraps React Aria usePress / useHover / useFocusRing and emits data-pressed, data-hovered, data-focus-visible, data-dragged, data-disabled and data-selected. It owns the Compose ripple (fade-in 75ms, grow over 225ms, fade-out 150ms), restarting a fresh ripple on every press.
  • ButtonBase — unstyled button, link (href) or toggle (toggle) behaviour with useM3Interaction applied; Button, IconButton and the FAB only add styling on top.
  • Surface (container role + elevation 0–5 + shape, with its variants as surfaceStyles), TouchTarget (48×48px hit area) and Overlay (portals an overlay into its portalContainer, else an app's React Aria UNSAFE_PortalProvider container, else the element in full screen when it opened, where it stays until it closes, else body; re-applies the theme attributes and dir of where it was rendered; leaves behind the trigger and group contexts it was opened from; and as it closes, with focus inside it or in an overlay opened from it, gives focus back to where it was before it opened without passing through the page).
  • Field parts (FieldLabel, SupportingText, ErrorText with the alert role, CharacterCounter read as its label, and the named FieldErrorIcon) and SelectionControl (the shared Checkbox / Radio / Switch control, with its variants as selectionControlStyles).
  • useM3Spring and getM3Spring (an M3 spring, such as spatial fast, as Motion transition options: useM3Spring from the active motion scheme, getM3Spring from a scheme you name; both are also in the main entry), and for a transition that continues a gesture (a panel released mid-drag keeps its speed): springWithVelocityToLinearEasing (a spring token and a starting velocity, in whole distances per second towards the target, as a CSS linear() easing and its settle duration in ms) and springProgressWithVelocity (that spring's progress, 0 to 1, at a time in seconds), as the bottom sheet settles after a drag.
  • Motion on values, on the theme's springs: useM3SpringValue (a Motion value that springs to each new target from where it is and at the speed it has, so a new target mid-move doesn't restart it), useM3SpringValues (a list of numbers that moves as one, each keeping its speed; a list of another length starts from the old one read at the new places with resample, so a line of 7 points becomes one of 84 by moving, or, given keys, is matched by name, so a sliding window's kept elements carry on and new ones start at rest), AnimatedNumber (a number that counts between values, formatted in the page's locale or by your function; assistive technology reads only the value it settles on, and its box keeps that width), staggerDelays (when each of a row's items starts an entrance: the times a spring of the count passes it, as the FAB menu staggers, so any number of items arrives within one spring's time) and useEntrance (plays an entrance once, as an element first comes into view, and never for content on screen as the page hydrates; when the page is printed it enters, committed before the print is laid out, and reports itself out of view until the print ends, so what you render from entered prints in its final state). A delay waits only from rest: a value already moving turns to its new target at once. Under reduced motion a spatial value or list and a number change at once, an effects value keeps its fade, and useEntrance is always entered, so nothing waits in its start state to jump in. A print runs no frames, so a mark drawn from a Motion value needs its resting geometry in CSS under @media print, as AnimatedNumber prints its final value.
  • TriggerContext (an overlay trigger hands its press handler and ARIA to a button-like child) and useTriggerProps (a trigger of your own merges its props into an enclosing trigger's, so triggers nest), usePresence (keeps an overlay mounted until its exit transition ends), and DomDirectionLocale / localeWithDirection (give React Aria the keyboard direction of the DOM without changing the app's language).
  • useRevealEntering, toAriaPlacement and closedByOverlayOptions (the pieces an anchored overlay shares: its reveal, its side in right to left, and what closes it).
  • useKeepPressedInPlace (keeps the item a person pressed still on screen while an open item above it folds, by scrolling its scroller as much as the fold on every frame, as the List's tree grid does; pair it with overflow-anchor: none on the folding parts).
  • useReorder (the engine of a list whose rows a person puts in order: a drag from a row's handle that the row follows while the rows it passes slide aside, moves by action, a cancel, rows that can't move, and scrolling near an edge; it has no look and no words of its own, and calls onReorder once a move lands). Merge handleProps()'s style (its touch-action: none keeps a finger on the handle from scrolling the page). The slide adds to a row's own transitions, and the hook leaves reduced motion to you: give it a duration that resolves to 0 there (a motion token does), or no slide.
  • useKeyboardInset (how far the on-screen keyboard covers the bottom of the window, in px, followed as it opens and closes, from the visual viewport or, where the page lays the keyboard over its content with the VirtualKeyboard API, the keyboard's own size; 0 with no keyboard or a zoomed page), for a panel that sits above the keyboard or takes its place, as the bottom sheet does.
  • usePageHeight (measures the page shown in a surface whose pages replace each other, in the same commit as the page changes, so the surface's height springs from the old page's from the first frame, as the Menu's submenus in place do).
  • formatClock and formatDurationWords (a media's length as a clock in the locale's digits, "4:12" or "1:02:03", and in its words, "4 minutes, 12 seconds", as ListItemVideo says it).
  • useNearestReveal (give it the element a React Aria collection hook was given, such as a grid that scrolls inside a box of its own: arrow keys then bring the next item into view without first centring the whole collection, so the page moves only as far as the item needs, as in the List and Tabs).
  • useSliderTouchTrack (wraps React Aria's useSlider track props so touch and pen take a slider of your own as the Slider's do: a tap sets the value as the finger lifts, a drag starts after 8px along the track, and a swipe across it scrolls the page instead of moving the value), with sliderThumbInputProps (React Aria's thumb input props made right for assistive technology: named by a visible label, no empty descriptions, a screen reader's change committed as a key's) and sliderArrowRaises (which arrow keys raise the value, mirrored right to left).
  • useScrollRestoration and useScrollKeys, for a page that is a pane scrolling by itself, as in the app frame block. Browsers restore only the window's scroll, so the first keeps the pane's position for each page (pageKey, your router's path and query) and brings it back on back, forward and reload, holding it while content arrives. A new key starts at the top, so a change of the query alone (a filter, a sort) does too; leave out of the key what shouldn't. The second sends Page Down, End, Space and the arrows to the pane while nothing has focus (unless the person last pressed in another scrolling element, which keeps them), and returns the tabIndex for it: a tab stop only on a page with nothing of its own that takes focus. Call both in a component that stays mounted as the pages change, such as a layout. Both follow the element behind the ref, so a frame can leave its pane out on some pages, or put another in its place, while the component that calls the hooks stays mounted.
  • The morph engine (useM3Morph, morphPathAt, getMorph) and the shape library: RoundedPolygon, CornerRounding, Cubic, Morph, the 35 MaterialShapes (with materialShapeNames), the shape builders (circle, pill, pillStar, rectangle, star) and the path serialisers (polygonToPath, morphToPath, cubicsToPath).
  • useLabels, for a component of your own that shows words: it gives the component's English defaults, then the words a LabelsProvider above gives its key, then its own labels prop. Add the key to WindmorphLabels by declaration merging (LabelsKey and LabelsOf are its key and words types), as Windmorph Pro does for its components.
  • For a component of your own: splitRootProps and its RootDOMProps type (put data-*, aria-* other than the naming ones, global attributes such as title and pointer events on the root when the rest go to a React Aria hook, as the core components do; with { wrapper: true }, for a root that wraps the labelled element, the attributes that describe that element (aria-controls, aria-expanded, aria-invalid …) stay with it too, typed by WrapperRootDOMProps, as do the description attributes React Aria's hooks don't forward (DescriptionAria: aria-description, aria-roledescription and the braille labels), and pickWidgetAria hands over the ones a React Aria hook doesn't forward, pickDescriptionAria only the description ones, for an element whose widget attributes you set yourself; the result's rest is typed by what stays in it, for a wrapper or not), splitDataAttributes (only the data-* props), mergeDataTokens (adds your own token set after a component's, as the core components do with a data-tokens they are given), ThemeScopeContext (the theme of the nearest ThemeProvider or ThemeScope, to provide one for a subtree), generateSchemeColors (every colour role as a hex value, for checks such as contrast) and themeSelector (the selector of one theme, contrast level and mode in the theme CSS, for values of your own that follow the themes as the colour roles do, scoped themes and the system mode included).
  • Static shapes: the 35 M3 Expressive shapes precomputed as outlines, one MaterialShapePath constant each (circleShape … heartShape: a name and SVG path data in the unit square, 3 decimals), materialShapePaths (all of them by name) and materialShapeMask(shape) (an outline as a CSS mask-image: an SVG data: URI in a 1 × 1 box, so with mask-size: 100% 100% one outline serves every size). None of them loads the shape engine.

Usage

Interaction and structure: useM3Interaction gives a plain element M3 interaction state, and the token utilities (state-layer, focus-ring) draw it on the background layer with no child elements, so consumer layout can never break it (architecture §10).

useM3Interaction
function MyControl() {
  const ref = useRef<HTMLButtonElement>(null);
  // Emits data-pressed / data-hovered / data-focus-visible / data-disabled and
  // owns the Compose ripple. Style those data-attributes with the token utilities.
  const { interactionProps, dataAttributes } = useM3Interaction({}, ref);
  return (
    <button ref={ref} {...interactionProps} {...dataAttributes}
      className="state-layer focus-ring rounded-corner-full ...">
      ...
    </button>
  );
}
Surface + ButtonBase
// Surface owns elevation + shape + container colour role (there is no Elevation
// component). ButtonBase owns button/link/toggle behaviour with useM3Interaction applied.
<Surface container="surface-container" elevation={1} className="rounded-corner-large p-4">
  <ButtonBase onPress={save}>Save</ButtonBase>
</Surface>

Static shapes

A shape that never moves (an avatar, an icon container) needs only its outline, so the outlines are computed once at build time and exported as constants. Import the constant for each shape you draw: a bundler drops the others, and no shape engine loads. Import materialShapePaths only to pick a shape by name, since it holds all 35. The outlines aren't mirrored in right-to-left layouts, as in Compose: the shapes are glyph-like, not directional.

Static shapes
import { cookie12SidedShape, materialShapeMask, materialShapePaths } from '@windmorph/react/primitives';

// One constant per shape: a bundler keeps only the outlines you import (Cookie12Sided adds
// about 0.4 kB gzipped), and none of them loads the shape engine.
const mask = materialShapeMask(cookie12SidedShape);
// Inline styles get no vendor prefix, and Chrome and Edge before 120 read only -webkit-mask-*.
<div className="size-14 bg-primary-container [mask-size:100%_100%]"
  style={{ maskImage: mask, WebkitMaskImage: mask }} />

// Picking a shape by name (a gallery, a shape picker) costs all 35 outlines (about 11 kB gzipped).
const shape = materialShapePaths[name];

// Your own outline works too: a closed SVG path in the unit square.
const notch = { name: 'Notch', path: 'M0 0H1V1L.5 .8 0 1Z' };
Precomputed shape outlines
ShapeConstantname
circleShapeCircle
squareShapeSquare
slantedShapeSlanted
archShapeArch
fanShapeFan
arrowShapeArrow
semiCircleShapeSemiCircle
ovalShapeOval
pillShapePill
triangleShapeTriangle
diamondShapeDiamond
clamShellShapeClamShell
pentagonShapePentagon
gemShapeGem
sunnyShapeSunny
verySunnyShapeVerySunny
cookie4SidedShapeCookie4Sided
cookie6SidedShapeCookie6Sided
cookie7SidedShapeCookie7Sided
cookie9SidedShapeCookie9Sided
cookie12SidedShapeCookie12Sided
ghostishShapeGhostish
clover4LeafShapeClover4Leaf
clover8LeafShapeClover8Leaf
burstShapeBurst
softBurstShapeSoftBurst
boomShapeBoom
softBoomShapeSoftBoom
flowerShapeFlower
puffyShapePuffy
puffyDiamondShapePuffyDiamond
pixelCircleShapePixelCircle
pixelTriangleShapePixelTriangle
bunShapeBun
heartShapeHeart

Morphing shapes: the shape library is pure geometry ported from androidx.graphics.shapes and Compose's MaterialShapes. It imports nothing from the rest of the library, so primitives and components can both use it.

Shapes & morphing
// Pure geometry (src/shapes): no React, no tokens. useM3Morph returns a Motion value
// of SVG path data; morphPathAt is the same as a plain function at a fixed progress.
const d = morphPathAt(['Circle', 'Flower'], 0.5, { size: 48 });

// Render morphs with overflow visible: mid-morph control points can sit ~1% outside the box.
<svg viewBox="0 0 48 48" overflow="visible"><path d={d} /></svg>

Your own component's tokens

A component built on primitives can have tokens like the library's own. defineComponentTokens names them, and the value helpers write each default from a system token: color, colorAt, corner, px, spring, typescale and typeTokens. They come from the main entry, with componentTokensCss, which writes the CSS.

acme-badge-tokens.ts
import { color, componentTokensCss, corner, defineComponentTokens, px } from '@windmorph/react';

// A component of your own gets its own tokens (--acme-badge-*). Their defaults read the
// M3 system tokens, so it follows every theme, mode and contrast level.
export const acmeBadgeTokens = defineComponentTokens({
  name: 'acme-badge',
  tokens: {
    container: { value: color('tertiary-container'), description: 'The fill.' },
    corner: { value: corner('small'), description: 'The corner radius.' },
    height: { value: px(24), description: 'The height.' },
  },
});

// At build time, write the variables into your stylesheet.
const css = componentTokensCss(acmeBadgeTokens);