Skip to content

PairMotion.js

Viames Marino edited this page Nov 28, 2026 · 10 revisions

PairMotion.js

PairMotion is an optional browser library for animating values, selection, progress, ranked lists, disclosures, page entrances, chart reveals, and progressive regions. Pair includes it as static assets from 4.2.0. Page entrances and chart reveals are available from 4.3.0. Pair 4.4.0 adds configurable page tempo, chart updates, list exits, related-element transitions, action confirmation, and selection arrival accents. Pair 4.4.1 adds staged card contents, lift and flip entrances, and a settling motion for the sliding selection background. PairMotion also runs on plain HTML pages, without a build step or runtime dependencies.

Install

In a Pair application, the standard asset copy step copies both files from the installed package:

php vendor/viames/pair/scripts/copy-assets.php public/assets

Outside Pair, copy assets/PairMotion.js and assets/pair-motion.css to the directory served by the application. Load the stylesheet and deferred script on pages that use the components. Adapt the URLs to the application's public base path.

<link rel="stylesheet" href="/assets/pair-motion.css">
<script src="/assets/PairMotion.js" defer></script>

The same API is available as window.PairMotion and window.Pair.Motion. Use the source and documentation that match the Pair version installed in the application. Try the operations dashboard for a complete example, or open the individual component examples. The source is in the repository under docs/examples.

Rolling counter

<span id="contracts" data-pair-motion-counter>
  <span data-pair-motion-value aria-live="polite" aria-atomic="true">10</span>
</span>
PairMotion.counter.set(document.getElementById('contracts'), '50');

Give the helper the already formatted value. It updates the text in the DOM immediately and rolls the changed ASCII digits in a separate layer hidden from assistive technology. Add aria-live="polite" and aria-atomic="true" only where updates warrant an announcement. No-JavaScript rendering shows the server value directly.

The default is 340 ms. Each digit takes the shorter path, including wrapping between 9 and 0. A new update interrupts the current roll from the visible frame. Text, signs and separators are preserved exactly. Digits are matched from the right, so use consistent decimal precision for a series of formatted values. The counter keeps the widest value it has shown in font-relative space, so a shorter value keeps its units column after the roll and on fragment replacement. Set --pair-motion-counter-min-width to reserve the expected maximum from the first paint, including for numbers that grow.

Use PairMotion.counter.enter(root) to roll the server-rendered digits forward from zero on first view. Pass { after: PairMotion.page.ready(page, root) } when the reel should stay at zero until the surrounding entrance settles. Add { phase: 'reveal' } as the third argument to page.ready() to start the roll while that card is still entering. The formatted server value remains in the markup and stays available to assistive technology. Cancellation, reduced motion and unavailable animation show the final text. Use counter.set() for subsequent data changes. An unchanged value at rest has no roll.

For a more mechanical roll, pass a fourth options argument to counter.set(root, value, snapshot, options), or pass options as the second argument to counter.enter(). duration sets each reel's travel time. stagger offsets the changed reels starting with the units digit. rollNewDigits: true rolls a newly added digit from zero. The live component examples let you compare the timing at normal and half speed.

Sliding selection

<div id="status" data-pair-motion-selection="vertical" role="group" aria-label="Order status">
  <label data-pair-motion-item><input name="status" type="radio" checked> Open</label>
  <label data-pair-motion-item><input name="status" type="radio"> In progress</label>
  <label data-pair-motion-item><input name="status" type="radio"> Complete</label>
</div>
const status = document.getElementById('status');
PairMotion.selection.mount(status);

Use direct item children. A native radio can be a direct child of its item. For an existing selection control, reflect selection on the item using its established aria-current, aria-pressed or aria-selected value. The library follows radio changes automatically and measures the active item after resizing. Call selection.sync(root) after a programmatic selection change or after reconciling the item's children. Use one selected item per group.

The indicator moves as one surface in 360 ms at normal speed. The leading edge advances first, the tail follows, and a smaller cross-axis wave softens the landing. Fast changes continue from the currently painted geometry and outline. Text, native controls and focus retain their own geometry throughout.

The layout and selection semantics are the same in vertical and inline groups. Set --pair-motion-selection-fill, --pair-motion-selection-radius and --pair-motion-focus-color to use the application's theme tokens. Call selection.unmount(root) before removing a mounted group during partial navigation. When the outline cannot be animated or forced colors are active, the indicator uses the 180 ms ease-in-out slide. Reduced motion aligns the selected background immediately.

Progress

<div id="production" data-pair-motion-progress>
  <progress value="35" max="100" aria-label="Orders processed">35%</progress>
</div>
PairMotion.progress.set(document.getElementById('production'), 80, 100);

The native progress value is updated immediately. A decorative fill moves from the current proportion to the new one in 180 ms. Pass a finite number for the value and, if supplied, a positive finite maximum. Pass null for an indeterminate state. Update any visible text around the bar with the exact source amount, especially when it exceeds the maximum and the native fill is full.

Use --pair-motion-progress-fill, --pair-motion-progress-track, --pair-motion-progress-height and --pair-motion-progress-radius to adapt the visuals to the application. Progress starts at the markup value and forced colors uses the native presentation.

Keyed list updates

<ol id="rank">
  <li data-pair-motion-key="north">North</li>
  <li data-pair-motion-key="central">Central</li>
</ol>
const rank = document.getElementById('rank');
PairMotion.layout.update(rank, () => {
  rank.append(rank.firstElementChild);
});

Use stable, unique keys on direct children. Match by entity identity, such as a persistent agent identifier. The helper measures positions before and after the synchronous callback and animates the displacement for 180 ms. New visible items fade in. Removed items leave immediately. Ambiguous duplicate keys are skipped when measuring each state.

Fetch and validate data before calling update. The library calls the callback once and returns its result. The application retains responsibility for stale responses, focus when replacing nodes and releasing any mounted widgets. For the best interruption behavior reuse the keyed nodes and reserve space for UI whose size can vary.

Fragment replacement and feedback

Read the old element before the app replaces it. Use the resulting snapshot on the new element after the app has attached it:

  • const from = PairMotion.counter.capture(oldCounter) and PairMotion.counter.set(newCounter, formattedValue, from) carry the visual reel positions across replacement. The new markup already contains the authoritative value.
  • const from = PairMotion.progress.capture(oldProgress) and PairMotion.progress.set(newProgress, value, max, from) use the previous visual ratio. Apply this only when both bars have a comparable scale and meaning.
  • const from = PairMotion.layout.capture(oldList) and PairMotion.layout.play(newList, from) carry keyed child positions across replacement. Positions are relative to the list, so movement of the enclosing page does not animate all items.
  • PairMotion.effect.fade(element) reveals newly rendered contents in 180 ms. Use it for new chart data or a changed scale. PairMotion.effect.highlight(element) fades a soft background highlight in 480 ms. Set --pair-motion-highlight on the element to use a theme color.

Anchored disclosure

<details id="delivery" data-pair-motion-disclosure>
  <summary><span data-pair-motion-chevron aria-hidden="true">▸</span>Delivery details</summary>
  <div data-pair-motion-disclosure-body>
    <p>Two parcels are ready to ship.</p>
  </div>
</details>
const delivery = document.getElementById('delivery');
PairMotion.disclosure.mount(delivery);

Mount enhances the existing summary action for pointer and keyboard input. The direct body wrapper grows or collapses below the summary over 180 ms. The optional chevron rotates in the same interval. Activating the summary again reverses from the visible height. Put padding or borders inside the body wrapper so it can collapse fully.

Use PairMotion.disclosure.set(details, true) or false for programmatic changes while mounted. Closing returns focus to the summary when focus was inside the body. The body becomes inert during the close, and the native open property clears at the end of the animation. In a native named group, opening one disclosure can close another immediately. Call disclosure.unmount(details) before replacing a mounted group or its markup. Initial and no-JavaScript behavior comes from the native element.

Stable region replacement

<div id="report" data-pair-motion-region aria-live="polite">
  <div data-pair-motion-content>Loading report…</div>
</div>
const report = document.getElementById('report');
PairMotion.region.replace(report, () => {
  report.firstElementChild.textContent = '12 orders processed.';
});

Keep the region wrapper in the document and give it one direct content wrapper. PairMotion runs the render callback synchronously and returns its result. The incoming content fades in while the region moves from its visible height to its natural height over 180 ms. A second update starts from the height already on screen. Use --pair-motion-region-min-block-size to reserve a common amount of space across states and keep adjacent controls fixed when both states fit. Give an empty initial region a minimum size if it should animate on the first update.

Fetch, validate and resolve competing responses before calling this helper. The callback owns the DOM change and any focus or busy state associated with it. When motion ends, the region uses its normal layout again.

Directional steps

PairMotion.region.replace(wizard, () => renderStep(nextStep), {
  direction: nextStep > currentStep ? 'forward' : 'backward'
});

The incoming content starts 12 px away along the reading direction and moves into place while fading. The sign reverses for backward navigation and for right-to-left layouts. Use this for sequential steps and move focus to the new heading or relevant control in the application. Omit the direction to use only the fade and height transition.

Page entrance

Mark a container with data-pair-motion-page and mark the blocks that should enter with data-pair-motion-enter. Leave controls that should be visible in their resting position immediately outside the sequence.

<main id="dashboard" data-pair-motion-page>
  <section data-pair-motion-enter="0">Summary</section>
  <div class="overview-grid">
    <section data-pair-motion-enter="1">Production</section>
    <section data-pair-motion-enter="1">Open tasks</section>
  </div>
  <section data-pair-motion-enter="2">Goals</section>
</main>
PairMotion.page.enter(document.getElementById('dashboard'), {
  duration: 220,
  stagger: 40,
  distance: 8,
  origin: 'bottom'
});

Call enter(root, options) after the rendered page is attached. Empty or omitted marker values use the block's zero-based DOM index among marked blocks in the same container. Give blocks the same non-negative step number to start together, or change the numbers to control entrance order without reordering the DOM. A nested marked container owns its own blocks. Mark non-overlapping wrappers for a single entrance at each level.

Option Default Accepted values
effect slide slide, lift for a rise and a slight scale change, or flip for marked two-sided cards.
duration 220 (310 for lift, 360 for flip) Duration per block, 0–800 ms. Zero disables the entrance.
stagger 40 Interval between steps, 0–200 ms. Zero starts all blocks together.
maxDelay 160 Cap on the start delay, 0–400 ms.
distance 8 Offset, 0–32 px. Zero leaves only the fade.
origin bottom bottom, top, start, end, or none. Start and end follow text direction.
opacity 0.7 Starting fraction of the resting opacity, 0–1.
easing ease-out (ease-in-out for flip) ease-out, ease-in-out, or linear.

Slide and lift animate opacity and visual offset. Lift also starts at 98.5% of the original size, with a default offset of 14 px and starting opacity of 0.52. All entrances preserve layout and DOM order. Hidden blocks and blocks that already hold focus are skipped. A block settles immediately if it receives focus during entrance. PairMotion leaves existing individual CSS translations in place. The normal markup is shown with reduced motion or without JavaScript.

Calling enter again replaces the current sequence. Use page.cancel(root) to settle it before replacing the container. Call enter once for a page opening. On a filter or data refresh, use the relevant local effects instead.

enter() returns a promise that resolves to true after the requested blocks have finished or motion has been skipped. It resolves to false if the entrance is cancelled or superseded before finishing. To run another effect after the entrance, await the promise and check its result.

Use PairMotion.page.ready(root, element) to start an effect inside a card once its entrance and the card entrances already playing have finished. It takes the marked card or a descendant. With viewport entrances, each card waits for its own group without waiting for cards still offscreen. The promise resolves to false if the page entrance is cancelled while waiting.

PairMotion.page.enter(dashboard, { effect: 'lift', trigger: 'viewport' });
PairMotion.counter.enter(counter, { after: PairMotion.page.ready(dashboard, counter) });

Prepare the first paint

Load the optional PairMotionBoot.js in the head before the body, without async or defer, and add data-pair-motion-prepaint to the opening data-pair-motion-page root. PairMotion starts the initially visible cards in the same frame that releases the guard. Reserve space for controls and media that become interactive after initialization. The guard applies only to opted-in pages and expires after 650 ms. With JavaScript unavailable, reduced motion enabled, or initialization arriving after the guard expires, the server-rendered layout stays visible. Explicit replays still use the normal entrance.

Compose cards, then contents

Pass contents: true to page.enter() and mark non-overlapping sections inside each card with data-pair-motion-content-enter. Each card starts revealing its sections as soon as its entrance begins, with a short stagger between sections. Pass contentsOverlap as a fraction from 0 to 1 to adjust the timing. A value of 0 waits until the card finishes, and the default 1 starts the first section with the card. The normal layout, controls and server data remain in place. Focus restores the card contents immediately. In viewport mode, a new group waits if the preceding cards have settled and their contents are still moving.

<section data-pair-motion-enter="0">
  <h2 data-pair-motion-content-enter>Orders fulfilled</h2>
  <div data-pair-motion-content-enter>
    <span id="orders" data-pair-motion-counter>
      <span data-pair-motion-value>51</span>
    </span>
  </div>
</section>
PairMotion.page.enter(dashboard, {
  effect: 'lift', trigger: 'viewport', contents: true, contentsOverlap: 1
});
PairMotion.counter.enter(orders, {
  after: PairMotion.page.ready(dashboard, orders, { phase: 'reveal' })
});

By default page.enter() and page.ready() include the contents phase in their completion promises. page.ready(root, element, { phase: 'reveal' }) resolves as the card contents become visible and follows the card's stagger, overlap and tempo. Use this earlier signal for rolling counters while keeping bars and plotted series after the completed entrance. Pass the same promise to chart.reveal({ after }) to trace the series as the last phase. The page duration multiplier applies to all three phases.

Card flip

Mark each card's wrapper with data-pair-motion-flip and its visible face with data-pair-motion-flip-front. Leave the wrapper free of transforms and clipping so its faces can rotate. The front stays in the server markup and defines the card size. PairMotion adds an empty decorative back during the turn.

<div data-pair-motion-enter="1" data-pair-motion-flip>
  <section class="card" data-pair-motion-flip-front>
    <h2>Daily deliveries</h2>
  </section>
</div>
const cards = PairMotion.page.enter(dashboard, { effect: 'flip' });
const reveal = PairMotion.chart.reveal({ after: cards });

The card turns 180° around its vertical axis. Unmarked blocks still slide in. With reduced motion or keyboard focus inside the card, the front is shown at once. Set --pair-motion-flip-back-background, --pair-motion-flip-back-border-color and --pair-motion-flip-back-radius on a page or card to match its theme. The dashboard demo compares the two entrances at adjustable speeds.

Play on scroll

Set trigger: 'viewport' to reveal each block once when it first intersects the viewport. Blocks that enter in the same batch share the same stagger rules. The earliest step in each batch starts immediately. Sections hold their normal layout before and during the effect.

PairMotion.page.enter(document.getElementById('dashboard'), {
  trigger: 'viewport',
  stagger: 35
});

By default the viewport is the browser window. Pass a scroll container as viewport to watch intersections inside a pane. With reduced motion or without Intersection Observer, the content keeps its normal appearance. Call page.cancel(root) before removing a page or replacing its marked children. This also disconnects the observer.

In viewport mode the promise normally waits for all marked blocks, including those below the fold. Pass a marked block as waitFor to resolve when that block and all card entrances already playing have settled. Other blocks can still enter later on scroll.

Chart.js series reveal

Add an instance of the optional plugin to a Chart.js 4 line or bar chart. Set animation: false on the chart when using the reveal on its own.

const reveal = PairMotion.chart.reveal({ duration: 400, origin: 'start' });
const chart = new Chart(canvas, {
  type: 'line',
  data,
  options: { animation: false },
  plugins: reveal ? [reveal] : []
});

The plugin clips the drawing of the datasets while keeping chart axes, grid, legend, and data coordinates available. It defaults to 400 ms and accepts durations from 0 to 1000 ms, with 0 disabling the effect. Choose start, end, top or bottom as the origin. Start and end follow the chart's text direction.

Pass the entrance promise as after to keep axes, grid and legend visible during composition and begin drawing the series once the cards settle.

const cards = PairMotion.page.enter(dashboard, {
  trigger: 'viewport',
  waitFor: canvas.closest('[data-pair-motion-enter]')
});
const reveal = PairMotion.chart.reveal({ after: cards, duration: 400 });

The after option also accepts a promise from another effect. A result of false, a rejection or reduced motion while waiting displays the final series immediately. Try the checkbox and replay button in the operations dashboard demo.

Create one plugin instance per chart. Keep it local to that chart and dispose of the chart through its normal destroy() method before replacing the canvas. The factory returns null when the effect is disabled, reduced motion is requested or animation frames are unavailable. PairMotion can be used without loading Chart.js on other pages.

Rows entering and leaving

Pass { exit: true } to layout.update(root, apply, options) to animate a keyed list's removals and incoming items. With progressive fragments, pass the same option to layout.capture(oldRoot, options) and layout.play(newRoot, snapshot, options).

PairMotion.layout.update(table.tBodies[0], () => replaceRows(), {
  exit: true, duration: 180, distance: 5
});

Rows leave the semantic list immediately. A bounded number of visible rows fade in a decorative layer which is removed after at most 160 ms, on scroll, or on another update. Use stable keys and pass a synchronous render callback. The layer has no focusable content and the remaining rows keep their real layout. As with other fragment effects, the application owns focus recovery if it removes a focused row.

Related elements across a change

Capture the position of a heading or badge before rendering, then animate the corresponding element after the destination is attached.

const from = PairMotion.element.capture(selectedTitle);
renderDetail();
detailHeading.focus();
PairMotion.element.enter(detailTitle, from, { duration: 200, distance: 96 });

Use a dedicated inner wrapper for the moving part so the semantic heading and its focus remain in their normal position. The translation is bounded and settles immediately if the moving element receives focus. Choose a smaller distance or pass zero for a fade.

Action confirmation

Keep the native button label and form lifecycle. Add two decorative icons inside data-pair-motion-feedback-icon, marking the normal icon data-pair-motion-idle and the initially hidden check data-pair-motion-confirmed. Provide a persistent role="status" for the text.

PairMotion.effect.confirm(saveButton, {
  status: saveStatus, message: 'Changes saved.', duration: 180, hold: 950
});

Call after the successful response. The text is set synchronously, the check replaces the idle icon in its existing slot, and only the icon resets after the hold. Repeated confirmations restart the effect. Use effect.clearConfirmation(button) to clear the timer when disposing of the control.

Chart.js data updates

Capture before replacing the old chart, then wrap the new Chart.js 4 config.

const previous = PairMotion.chart.capture(chart);
chart.destroy();
const config = PairMotion.chart.transition(nextConfig, previous, {
  morph: samePeriod, duration: 250, fadeDuration: 180
});
chart = new Chart(canvas, config);

Use a positioned chart container and disable the chart's own entrance animation in nextConfig. Matching line series must have the same labels, unique series keys and a comparable linear Y scale. The series key is dataset.pairMotionKey, with the dataset label as fallback. The effect interpolates plotted coordinates from the last visible frame while parsed data and tooltip values are already current. When the data or scale cannot be compared, or morph: false describes a different period, the chart crossfades. The former plot is decorative and removed when its animation finishes or the chart is destroyed.

For list, related-element and confirmation effects, easing accepts ease-out, ease-in-out and linear. The chart update uses equivalent Chart.js curves. All four effects respect reduced-motion preferences.

Page tempo

Set the inherited CSS custom property --pair-motion-duration-factor on a page or component to tune its pace. A value of 1.3 makes durations and entrance intervals 30% longer, including Chart.js effects and CSS transitions for selection, progress and disclosure. The default is 1. Use a numeric value from 0.25 to 3. Reduced-motion support remains active.

.dashboard {
  --pair-motion-duration-factor: 2;
}

A factor of 2 doubles the duration and plays at half speed. The speed slider in the operations dashboard demo replays the sequence and shows the CSS declaration for the chosen speed.

Accessibility and fallback

With prefers-reduced-motion: reduce, the result is shown immediately. Active effects settle if the preference switches while they run. The indicator, progress fill and chevron use CSS transitions that respect this preference. Absent animation support, the helpers still apply their semantic updates. Initial values come from the HTML. Screen readers can read the true value and controls retain their native operation.

Clone this wiki locally