Getting started

Actions

Forms

Layout

Navigation

Overlays

Feedback

Data display

Controllers

Helpers

Recipes

Swipe to dismiss

A card that follows the pointer, dismissed by a horizontal swipe, and with a button that does the same.

Goal

A notification, a suggestion or a message in a feed that the user clears with a gesture. A gesture is never the only way: the button is the keyboard and assistive technology path, and both paths end in the same function.

Primitives

  • PointerDragController reports the drag, so the card follows the pointer: the recipe writes --swipe-dx and --swipe-opacity on it and the CSS translates and fades it, with no transition while data-dragging is set and a transition on release. Its canStart keeps a press on the button from starting a drag.
  • createVelocityTracker takes the pointer's x and timeStamp on the press, every move and the release, and gives the speed just before the release.
  • resolveSwipeDirection decides on release from the drag's dx and dy and that release velocity: a long drag counts, and so does a short quick flick (minVelocity) as long as it is clearly sideways (dominance). Past the decision the card flies out and is dismissed; otherwise it springs back.

The recipe uses one PointerDragController and the pure decision rather than a second SwipeController on the same card: SwipeController is built on a PointerDragController, so two would listen for the same press twice and finish in an order the recipe does not control. The speed comes from the tracker, so a flick after a pause still counts.

Left to the recipe: what dismissing does (here it waits for the fly-out animation, hides the card and says so in a live region) and, where the card is hidden while it holds focus, moving focus on to the restore button. A card that only needs the decision and no feedback uses SwipeController.

Example

Drag the card sideways at least 48 px, or flick it faster than 0.5 px per ms over at least 16 px, then release. A shorter or slower drag springs back, and so does one that is not at least twice as far sideways as vertically. Or press the Dismiss button. Pick an authoring pattern below; they all behave the same, and the one you pick is remembered on the other recipes.

The same behavior as a RadiantElement. The markup is authored inside the element and the element finds its parts with @query; there is nothing to mount, clean up or run again.

Your report is ready

The card is shown

import { RadiantElement, customElement, onEvent, query } from '@ecopages/radiant';
import { createPointerDragController } from '@ecopages/radiant-ui/controllers';
import { createVelocityTracker, resolveSwipeDirection } from '@ecopages/radiant-ui/helpers';

@customElement('swipe-card-element')
export class SwipeCardElement extends RadiantElement {
	@query('[data-swipe-card]') private card!: HTMLElement;
	@query('[data-dismiss]') private dismissButton!: HTMLElement;
	@query('[data-restore]') private restoreButton!: HTMLElement;
	@query('[data-status]') private status!: HTMLElement;
	private readonly speed = createVelocityTracker();

	constructor() {
		super();
		createPointerDragController(this, {
			getTarget: () => this.card,
			capture: false,
			canStart: (event) => !(event.target instanceof Element && event.target.closest('button')),
			onStart: ({ event, x }) => {
				this.speed.reset();
				this.speed.add(event.timeStamp, x);
				this.card.dataset.dragging = '';
			},
			onMove: ({ dx, event, x }) => {
				this.speed.add(event.timeStamp, x);
				this.follow(dx);
			},
			onEnd: ({ reason, dx, dy, event, x }) => {
				delete this.card.dataset.dragging;
				this.speed.add(event.timeStamp, x);
				const direction =
					reason === 'release'
						? resolveSwipeDirection(dx, dy, {
								minVelocity: 0.5,
								dominance: 2,
								velocity: { x: this.speed.velocity(event.timeStamp), y: 0 },
							})
						: null;
				if (!direction) {
					this.follow(0);
					return;
				}
				this.follow(direction === 'left' ? -this.card.offsetWidth : this.card.offsetWidth);
				Promise.allSettled(this.card.getAnimations().map((animation) => animation.finished)).then(() =>
					this.setShown(false, `Card dismissed, swiped ${direction}`),
				);
			},
		});
	}

	private setShown(shown: boolean, message: string): void {
		const hadFocus = !shown && this.card.contains(document.activeElement);
		this.card.hidden = !shown;
		this.restoreButton.hidden = shown;
		if (hadFocus) {
			this.restoreButton.focus();
		}
		this.status.textContent = message;
		this.card.style.setProperty('--swipe-dx', '0px');
		this.card.style.setProperty('--swipe-opacity', '1');
	}

	private follow(dx: number): void {
		const distance = Math.min(Math.abs(dx) / this.card.offsetWidth, 1);
		this.card.style.setProperty('--swipe-dx', `${dx}px`);
		this.card.style.setProperty('--swipe-opacity', `${1 - distance / 2}`);
	}

	@onEvent({ selector: '[data-dismiss]', type: 'click' })
	dismiss(): void {
		this.setShown(false, 'Card dismissed');
		this.restoreButton.focus();
	}

	@onEvent({ selector: '[data-restore]', type: 'click' })
	restore(): void {
		this.setShown(true, 'The card is shown');
		this.dismissButton.focus();
	}
}

createPointerDragController(this, ...) in the constructor attaches the drag when the element connects and destroys it when the element disconnects, and the @onEvent listeners for the two buttons follow the same lifecycle. The card, the buttons and the live region are found with @query, so the element owns all of them; the pure resolveSwipeDirection decision is unchanged.

What the Radiant form removes: the mount function and its registration, the cleanup to return and call, and the re-run after a client-side navigation.

Styles

The card follows the drag only through these rules: the recipe writes --swipe-dx and --swipe-opacity and the stylesheet turns them into a translation and a fade, with no transition while data-dragging is set. The stylesheet is the swipe-card.css tab in the files above.