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-dxand--swipe-opacityon it and the CSS translates and fades it, with no transition whiledata-draggingis set and a transition on release. ItscanStartkeeps a press on the button from starting a drag. - createVelocityTracker takes the pointer's
xandtimeStampon the press, every move and the release, and gives the speed just before the release. - resolveSwipeDirection decides on release from the drag's
dxanddyand 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.
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();
}
}<swipe-card-element>
<div data-swipe-card>
<span>Your report is ready</span>
<button type="button" data-dismiss>Dismiss</button>
</div>
<button type="button" data-restore hidden>Restore the card</button>
<p data-status aria-live="polite">The card is shown</p>
</swipe-card-element>.primitive-example:has(
> swipe-card-element,
> [data-controller='swipe-card'],
> swipe-card-app,
> [data-example='swipe-card']
) {
flex-direction: column;
align-items: stretch;
overflow-x: clip;
min-height: 8rem;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card] {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
padding: var(--space-3) var(--space-4);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
cursor: grab;
touch-action: none;
user-select: none;
transform: translateX(var(--swipe-dx, 0));
opacity: var(--swipe-opacity, 1);
transition:
transform var(--duration-normal) var(--ease-out-strong),
opacity var(--duration-normal) var(--ease-out-strong);
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card][data-dragging] {
transition: none;
cursor: grabbing;
box-shadow: var(--shadow-overlay);
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card][hidden] {
display: none;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card']) [data-restore] {
align-self: flex-start;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-restore][hidden] {
display: none;
}
@media (prefers-reduced-motion: reduce) {
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card] {
transition: none;
}
}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.
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.
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();
}
}<swipe-card-element>
<div data-swipe-card>
<span>Your report is ready</span>
<button type="button" data-dismiss>Dismiss</button>
</div>
<button type="button" data-restore hidden>Restore the card</button>
<p data-status aria-live="polite">The card is shown</p>
</swipe-card-element>.primitive-example:has(
> swipe-card-element,
> [data-controller='swipe-card'],
> swipe-card-app,
> [data-example='swipe-card']
) {
flex-direction: column;
align-items: stretch;
overflow-x: clip;
min-height: 8rem;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card] {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
padding: var(--space-3) var(--space-4);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
cursor: grab;
touch-action: none;
user-select: none;
transform: translateX(var(--swipe-dx, 0));
opacity: var(--swipe-opacity, 1);
transition:
transform var(--duration-normal) var(--ease-out-strong),
opacity var(--duration-normal) var(--ease-out-strong);
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card][data-dragging] {
transition: none;
cursor: grabbing;
box-shadow: var(--shadow-overlay);
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card][hidden] {
display: none;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card']) [data-restore] {
align-self: flex-start;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-restore][hidden] {
display: none;
}
@media (prefers-reduced-motion: reduce) {
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card] {
transition: none;
}
}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.
The same card as one self-contained tag. The element owns its markup: it keeps whether the card is shown and the status line as state and draws them with render(), so there is no markup to author or copy and the page holds only the tag.
import { RadiantElement, customElement, onEvent, state } from '@ecopages/radiant';
import { createPointerDragController } from '@ecopages/radiant-ui/controllers';
import { createVelocityTracker, resolveSwipeDirection } from '@ecopages/radiant-ui/helpers';
@customElement('swipe-card-app')
export class SwipeCardApp extends RadiantElement<{ status: string }> {
@state shown = true;
@state status = 'The card is shown';
private focusAfterRender: 'dismiss' | 'restore' | null = null;
private readonly speed = createVelocityTracker();
private readonly drag = 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 get card(): HTMLElement {
return this.querySelector<HTMLElement>('[data-swipe-card]')!;
}
/**
* Attaches the drag to the drawn card and moves focus once the render has shown or hidden the buttons.
*
* @remarks
* The drag controller attaches when the element connects, before the first render has made the card, so it
* attaches again here, where its target exists. A button that the render is about to hide cannot take focus, so a
* focus move is recorded when the state changes and made here, after the commit.
*/
protected override updated(): void {
this.drag.attach();
if (this.focusAfterRender) {
this.querySelector<HTMLElement>(`[data-${this.focusAfterRender}]`)?.focus();
this.focusAfterRender = null;
}
}
/**
* The drag writes `--swipe-dx` and `--swipe-opacity` straight onto the card, and `data-dragging` too, so a drag
* never re-renders; the render only owns `hidden`.
*/
private setShown(shown: boolean, message: string): void {
if (!shown && this.card.contains(document.activeElement)) {
this.focusAfterRender = 'restore';
}
this.card.style.setProperty('--swipe-dx', '0px');
this.card.style.setProperty('--swipe-opacity', '1');
this.shown = shown;
this.status = message;
}
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.focusAfterRender = 'restore';
}
@onEvent({ selector: '[data-restore]', type: 'click' })
restore(): void {
this.setShown(true, 'The card is shown');
this.focusAfterRender = 'dismiss';
}
override render() {
return (
<>
<div data-swipe-card hidden={!this.shown}>
<span>Your report is ready</span>
<button type="button" data-dismiss>
Dismiss
</button>
</div>
<button type="button" data-restore hidden={this.shown}>
Restore the card
</button>
<p data-status aria-live="polite">
{this.$.status}
</p>
</>
);
}
}.primitive-example:has(
> swipe-card-element,
> [data-controller='swipe-card'],
> swipe-card-app,
> [data-example='swipe-card']
) {
flex-direction: column;
align-items: stretch;
overflow-x: clip;
min-height: 8rem;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card] {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
padding: var(--space-3) var(--space-4);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
cursor: grab;
touch-action: none;
user-select: none;
transform: translateX(var(--swipe-dx, 0));
opacity: var(--swipe-opacity, 1);
transition:
transform var(--duration-normal) var(--ease-out-strong),
opacity var(--duration-normal) var(--ease-out-strong);
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card][data-dragging] {
transition: none;
cursor: grabbing;
box-shadow: var(--shadow-overlay);
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card][hidden] {
display: none;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card']) [data-restore] {
align-self: flex-start;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-restore][hidden] {
display: none;
}
@media (prefers-reduced-motion: reduce) {
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card] {
transition: none;
}
}shown and status are @state, so dismissing and restoring write state and render() sets hidden on the card and the restore button. The drag does not go through state: it writes --swipe-dx, --swipe-opacity and data-dragging straight onto the card, which the render never sets, so a drag does not re-render sixty times a second. Focus moves in updated(), after the commit, because the restore button is still hidden when the state changes; the element records where focus should go and updated() moves it. The status line is bound with this.$.status, so announcing patches one text node.
Compared with the Radiant element above, the markup lives inside the element, so there is nothing to keep in step with the page, but restyling the structure means editing the class. It also needs the render path on the server to have content before the script runs: this docs build prerenders the tag empty and the client draws it, so the page shows nothing until the script loads, which a page of authored children does not.
The same behavior as a RadiantController: a class attached to markup that already exists, found through data-controller, with no custom element tag.
The card is shown
import { RadiantController, controller, onEvent, query } from '@ecopages/radiant';
import { createPointerDragController } from '@ecopages/radiant-ui/controllers';
import { createVelocityTracker, resolveSwipeDirection } from '@ecopages/radiant-ui/helpers';
@controller('swipe-card')
export class SwipeCardController extends RadiantController {
@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(host: Element) {
super(host);
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();
}
}<div data-controller="swipe-card">
<div data-swipe-card>
<span>Your report is ready</span>
<button type="button" data-dismiss>Dismiss</button>
</div>
<button type="button" data-restore hidden>Restore the card</button>
<p data-status aria-live="polite">The card is shown</p>
</div>.primitive-example:has(
> swipe-card-element,
> [data-controller='swipe-card'],
> swipe-card-app,
> [data-example='swipe-card']
) {
flex-direction: column;
align-items: stretch;
overflow-x: clip;
min-height: 8rem;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card] {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
padding: var(--space-3) var(--space-4);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
cursor: grab;
touch-action: none;
user-select: none;
transform: translateX(var(--swipe-dx, 0));
opacity: var(--swipe-opacity, 1);
transition:
transform var(--duration-normal) var(--ease-out-strong),
opacity var(--duration-normal) var(--ease-out-strong);
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card][data-dragging] {
transition: none;
cursor: grabbing;
box-shadow: var(--shadow-overlay);
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card][hidden] {
display: none;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card']) [data-restore] {
align-self: flex-start;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-restore][hidden] {
display: none;
}
@media (prefers-reduced-motion: reduce) {
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card] {
transition: none;
}
}The class body is the element's: @query finds the parts, @onEvent handles the buttons and createPointerDragController(this, ...) attaches the drag on connect and destroys it on cleanup, because a RadiantController offers the same two registration methods as a RadiantElement. The constructor receives the host element, so it passes it to super(host).
What differs from the Radiant element: there is no tag to define, so the markup can come from a server or a CMS and only needs data-controller="swipe-card" on its root. One registry, which this docs site starts over the document, attaches the class to that element, also when it is inserted later, and cleans up when the element is removed.
A mount function wires the controllers to one element and returns the cleanup that undoes it.
The card is shown
import { PointerDragController } from '@ecopages/radiant-ui/controllers';
import { createVelocityTracker, resolveSwipeDirection } from '@ecopages/radiant-ui/helpers';
export function mount(root: HTMLElement): () => void {
const card = root.querySelector<HTMLElement>('[data-swipe-card]')!;
const dismissButton = root.querySelector<HTMLElement>('[data-dismiss]')!;
const restoreButton = root.querySelector<HTMLElement>('[data-restore]')!;
const status = root.querySelector('[data-status]')!;
function setShown(shown: boolean, message: string): void {
const hadFocus = !shown && card.contains(document.activeElement);
card.hidden = !shown;
restoreButton.hidden = shown;
if (hadFocus) {
restoreButton.focus();
}
status.textContent = message;
card.style.setProperty('--swipe-dx', '0px');
card.style.setProperty('--swipe-opacity', '1');
}
function follow(dx: number): void {
const distance = Math.min(Math.abs(dx) / card.offsetWidth, 1);
card.style.setProperty('--swipe-dx', `${dx}px`);
card.style.setProperty('--swipe-opacity', `${1 - distance / 2}`);
}
const speed = createVelocityTracker();
const drag = new PointerDragController({
getTarget: () => card,
capture: false,
canStart: (event) => !(event.target instanceof Element && event.target.closest('button')),
onStart: ({ event, x }) => {
speed.reset();
speed.add(event.timeStamp, x);
card.dataset.dragging = '';
},
onMove: ({ dx, event, x }) => {
speed.add(event.timeStamp, x);
follow(dx);
},
onEnd: ({ reason, dx, dy, event, x }) => {
delete card.dataset.dragging;
speed.add(event.timeStamp, x);
const direction =
reason === 'release'
? resolveSwipeDirection(dx, dy, {
minVelocity: 0.5,
dominance: 2,
velocity: { x: speed.velocity(event.timeStamp), y: 0 },
})
: null;
if (!direction) {
follow(0);
return;
}
follow(direction === 'left' ? -card.offsetWidth : card.offsetWidth);
Promise.allSettled(card.getAnimations().map((animation) => animation.finished)).then(() =>
setShown(false, `Card dismissed, swiped ${direction}`),
);
},
});
drag.attach();
dismissButton.addEventListener('click', () => {
setShown(false, 'Card dismissed');
restoreButton.focus();
});
restoreButton.addEventListener('click', () => {
setShown(true, 'The card is shown');
dismissButton.focus();
});
return () => drag.destroy();
}<div data-example="swipe-card">
<div data-swipe-card>
<span>Your report is ready</span>
<button type="button" data-dismiss>Dismiss</button>
</div>
<button type="button" data-restore hidden>Restore the card</button>
<p data-status aria-live="polite">The card is shown</p>
</div>.primitive-example:has(
> swipe-card-element,
> [data-controller='swipe-card'],
> swipe-card-app,
> [data-example='swipe-card']
) {
flex-direction: column;
align-items: stretch;
overflow-x: clip;
min-height: 8rem;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card] {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
padding: var(--space-3) var(--space-4);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
cursor: grab;
touch-action: none;
user-select: none;
transform: translateX(var(--swipe-dx, 0));
opacity: var(--swipe-opacity, 1);
transition:
transform var(--duration-normal) var(--ease-out-strong),
opacity var(--duration-normal) var(--ease-out-strong);
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card][data-dragging] {
transition: none;
cursor: grabbing;
box-shadow: var(--shadow-overlay);
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card][hidden] {
display: none;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card']) [data-restore] {
align-self: flex-start;
}
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-restore][hidden] {
display: none;
}
@media (prefers-reduced-motion: reduce) {
:is([data-example='swipe-card'], swipe-card-element, swipe-card-app, div[data-controller='swipe-card'])
[data-swipe-card] {
transition: none;
}
}mount runs once for each example element on the page, and the function it returns undoes it; see how the examples run.
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.