Building a Drag and Drop Kanban Board for Mouse, Touch, and Keyboard

Want more of these in your Google results?
A task board needs a way to move a card without dragging it.
Some people point with a head pointer or with their eyes, which makes dragging slow and easy to get wrong. You also can’t drag with a keyboard. And on a phone with a screen reader turned on, a drag usually doesn’t even reach the page, because the screen reader uses that gesture to move its own focus.
That’s why version 2.2 of WCAG (the Web Content Accessibility Guidelines) requires a way to move things without dragging them.
Plenty of drag and drop libraries only give you the drag, though. SortableJS, for example, gets millions of downloads a week on npm and doesn’t let you move an item without dragging it. When a user asked for keyboard and screen reader support in 2017, its maintainer said no and added that it would make the whole library more complex “by about a third”.
So you would usually end up adding a menu to each card yourself, with options like and . And if you write the menu and the drag separately, you have two pieces of code that have to put every card in the same place.
I built a two-column board like the ones in Google Tasks or Trello, where the drag, the Move menu, and the Undo button all call the same function to move a card. That function also puts focus back on the card and writes a message for screen readers. And you can drag cards with a mouse, a finger, or a pen.
Hover a card on the finished board below and click at its top right to move it with the menu, or drag it by that button. To put it back, click under the columns.
// index.ts
import type {
AutoscrollEdge,
AutoscrollOptions,
BoardMessages,
CardId,
CardMoveDetail,
ColumnBox,
ColumnId,
Columns,
DragBoard,
DragPress,
DropTarget,
MenuState,
MenuTarget,
Move,
MoveItem,
MoveMenuOptions,
MoveResult,
MoveSource,
TaskBoardOptions,
Titles,
} from './types';
/**
* The English strings, which `TaskBoardOptions.messages` can replace one by one.
*/
export const DEFAULT_MESSAGES: BoardMessages = {
moveToTop: 'Move to top',
moveUp: 'Move up',
moveDown: 'Move down',
moveToBottom: 'Move to bottom',
moveToColumn: ( column ) => `Move to ${column}`,
moved: ( card, position, count, column ) => `${card} moved to position ${position} of ${count} in ${column}.`,
};
/**
* The autoscroll settings, slow enough that a person can press Escape while a column still scrolls.
*/
export const DEFAULT_AUTOSCROLL: AutoscrollOptions = {
zone: 48,
maxSpeed: 300,
};
/**
* How far the pointer has to move from where it went down before a press becomes a drag, in pixels.
* A press that moves less is a click, which opens the Move menu.
*/
const DRAG_THRESHOLD = 5;
/**
* How far below a list the column still counts as the drop target, in pixels, which is also the bottom autoscroll zone outside the list.
*/
const BELOW_LIST = 60;
/**
* How long autoscroll takes to reach its full speed after the pointer enters a zone, in milliseconds.
*/
const AUTOSCROLL_RAMP = 400;
/**
* The longest frame autoscroll accounts for, in milliseconds.
* It keeps a frame after a stall from jumping the column.
*/
const MAX_FRAME = 50;
/**
* The menu items in the order the menu shows them, with the separator before the other column.
*/
const MENU_ITEMS: readonly MoveItem[] = [ 'top', 'up', 'down', 'bottom', 'other' ];
/**
* The keys that open the Move menu from a focused Move button.
* Enter and Space click the button.
* Down and Up open the menu on its first or last item.
* During a drag, none of the four reaches the menu.
*/
const MENU_KEYS: ReadonlySet<string> = new Set( [ 'Enter', ' ', 'ArrowDown', 'ArrowUp' ] );
/**
* Finds the column that holds a card.
*
* @param columns - The board's order.
* @param cardId - The card.
* @returns The column's id.
* @throws RangeError when no column holds the card, which is a bug in the caller.
*/
function columnOf( columns: Columns, cardId: CardId ): ColumnId {
const column = Object.keys( columns ).find( ( id ) => columns[ id ].includes( cardId ) );
if ( column === undefined ) {
throw new RangeError( `No column holds the card ${cardId}.` );
}
return column;
}
/**
* Finds the column a card's Move to item sends it to.
*
* @param columns - The board's order.
* @param column - The card's column.
* @returns The other column's id.
* @throws RangeError when the board has a single column.
*/
function otherColumn( columns: Columns, column: ColumnId ): ColumnId {
const other = Object.keys( columns ).find( ( id ) => id !== column );
if ( other === undefined ) {
throw new RangeError( 'The board has no other column.' );
}
return other;
}
/**
* Works out the new order for a card moved to a column and an index, the data step `TaskBoard.move()` runs first.
*
* The index is the card's position in the destination after it left its old spot.
* In other words, it's the number of cards that end up above it.
* That holds in the same column and in another one.
* A move down is always the old index plus one, and a drag passes the number of other cards above its line.
* Below 0 becomes 0, and past the end becomes the end, which is also where a card goes with no index.
* A fractional index is truncated toward zero (2.7 means 2).
* A framework's state code can call it as it is, because the function never changes `columns` or its arrays.
*
* @param columns - The board's order.
* @param cardId - The card to move.
* @param toColumn - The column it goes to.
* @param toIndex - The number of cards above it after the move, or the end of the column when it's left out.
* @returns The new order and the move's record, or null when the card would end up where it is.
* @throws RangeError for an unknown card or column, or an index that isn't a number, all of them bugs in the caller.
*/
export function moveCard( columns: Columns, cardId: CardId, toColumn: ColumnId, toIndex = Infinity ): MoveResult | null {
const fromColumn = columnOf( columns, cardId );
if ( ! Object.hasOwn( columns, toColumn ) ) {
throw new RangeError( `The board has no column ${toColumn}.` );
}
if ( typeof toIndex !== 'number' || Number.isNaN( toIndex ) ) {
throw new RangeError( 'The index is not a number.' );
}
const fromIndex = columns[ fromColumn ].indexOf( cardId );
const others = columns[ toColumn ].filter( ( id ) => id !== cardId );
const index = Math.min( Math.max( Math.trunc( toIndex ), 0 ), others.length );
if ( fromColumn === toColumn && fromIndex === index ) {
return null;
}
const next: Record<ColumnId, readonly CardId[]> = { ...columns };
next[ fromColumn ] = columns[ fromColumn ].filter( ( id ) => id !== cardId );
next[ toColumn ] = others.toSpliced( index, 0, cardId );
const move: Move = {
cardId,
from: { column: fromColumn, index: fromIndex },
to: { column: toColumn, index },
};
return { columns: next, move };
}
/**
* Works out where a Move menu item sends a card, without moving anything.
*
* Move to bottom and Move to the other column leave the index out.
* `moveCard()` then puts the card at the end, the same place a drop under the last card does.
*
* @param item - The picked item's `data-move` value.
* @param columns - The board's order.
* @param cardId - The card whose Move button opened the menu.
* @returns The column, and the index when the item has one.
*/
export function targetFor( item: MoveItem, columns: Columns, cardId: CardId ): MenuTarget {
const column = columnOf( columns, cardId );
const index = columns[ column ].indexOf( cardId );
switch ( item ) {
case 'top':
return [ column, 0 ];
case 'up':
return [ column, index - 1 ];
case 'down':
return [ column, index + 1 ];
case 'bottom':
return [ column ];
case 'other':
return [ otherColumn( columns, column ) ];
}
}
/**
* Counts the cards whose vertical middle is above a point.
*
* A drag calls it with the middles of the column's other cards, without the one being dragged.
* The count is then the index `moveCard()` takes, with no correction.
*
* @param middles - The cards' vertical middles, in viewport pixels.
* @param y - The pointer's vertical position.
* @returns How many middles are above it. A pointer exactly on a middle doesn't count that card.
*/
export function slotIndex( middles: readonly number[], y: number ): number {
return middles.filter( ( middle ) => middle < y ).length;
}
/**
* Autoscroll's speed for a pointer inside an edge zone, growing in a straight line from 0 at the zone's inner edge to the maximum at the list's edge.
*
* @param depth - How far past the zone's inner edge the pointer is, in pixels.
* @param zone - How deep the zone is, in pixels.
* @param max - The speed at the list's edge and beyond.
* @returns The speed, in the same unit as `max`.
*/
export function edgeSpeed( depth: number, zone: number, max: number ): number {
if ( depth <= 0 ) {
return 0;
}
if ( zone <= 0 || depth >= zone ) {
return max;
}
return max * ( depth / zone );
}
/**
* Writes the sentence that says where a card went, the same for every input, Undo included.
*
* Positions start at 1, and the old position stays out, since the person who moved the card knows where it came from.
*
* @param titles - Card and column titles by id.
* @param columns - The order after the move.
* @param move - The move.
* @param moved - The sentence, for a translated board.
* @returns The message.
*/
export function moveMessage( titles: Titles, columns: Columns, move: Move, moved = DEFAULT_MESSAGES.moved ): string {
const card = titles[ move.cardId ] ?? move.cardId;
const column = titles[ move.to.column ] ?? move.to.column;
return moved( card, move.to.index + 1, columns[ move.to.column ].length, column );
}
/**
* Moves a card's element so the page shows the order the data has.
*
* The reference node is the list's child at `index`, counting every child except the card, like the index in `moveCard()`.
* `moveBefore()` keeps focus and pointer capture where the browser has it, and it needs both nodes in the page.
* Where it's missing, `insertBefore()` takes the card out and puts it back.
* That drops focus to the page body until `focusCard()` puts it back after the move.
*
* @param $card - The card's `<li>`.
* @param $list - The destination `<ol>`, which holds nothing but cards.
* @param index - The card's index after the move.
*/
export function placeCard( $card: HTMLElement, $list: HTMLElement, index: number ): void {
const $others = [ ...$list.children ].filter( ( $child ) => $child !== $card );
const $next = $others[ index ] ?? null;
if ( $card.isConnected && $list.isConnected && 'moveBefore' in $list ) {
$list.moveBefore( $card, $next );
} else {
$list.insertBefore( $card, $next );
}
}
/**
* Shows a card inside its column and focuses its Move button.
*
* It changes only the column's `scrollTop`, by just enough to show the whole card, then focuses with `preventScroll`.
* A plain `focus()` on a button outside the visible part of a column scrolls it to the column's middle, and `scrollIntoView()` can scroll the page around the board too.
*
* @param $card - The card's `<li>`, inside its list.
*/
export function focusCard( $card: HTMLElement ): void {
const $list = $card.parentElement;
if ( $list ) {
const card = $card.getBoundingClientRect();
const list = $list.getBoundingClientRect();
const top = list.top + $list.clientTop;
const bottom = top + $list.clientHeight;
if ( card.top < top ) {
$list.scrollTop -= Math.ceil( top - card.top );
} else if ( card.bottom > bottom ) {
$list.scrollTop += Math.ceil( card.bottom - bottom );
}
}
const $button = $card.querySelector( 'button[data-card-move]' );
if ( $button instanceof HTMLButtonElement ) {
$button.focus( { preventScroll: true } );
}
}
/**
* Checks whether `showPopover()` takes a `source` option, which makes the Move button the popover's anchor.
*
* Some browser versions support `position-area` but not this option, and in those the menu would end up in a corner of the viewport.
* The browser converts the options object before it checks the element, so the getter runs even though the call then throws on a `<div>` that isn't a popover.
*
* @returns Whether the getter ran.
*/
function showPopoverTakesSource(): boolean {
let read = false;
try {
document.createElement( 'div' ).showPopover( {
get source() {
read = true;
return undefined;
},
} );
} catch {
// The call always throws on a div without the popover attribute, and only the getter matters here.
}
return read;
}
/**
* The Move menu every card's Move button opens, one per board, following the APG's menu button pattern.
*
* Moving a card never touches it, because it lives outside the columns.
* Before it opens, it focuses the Move button, the element `hidePopover()` gives focus back to.
* Each time it opens, it takes the button's `aria-labelledby`, which names the menu "Move Fix login" instead of "Move".
* Items stay in place and focusable at a column's ends, with `aria-disabled="true"`, and picking one does nothing and keeps the menu open.
*
* Enter, Space, or Down on a Move button opens the menu on its first item, and Up on its last.
* In the menu, Down and Up move between items and wrap, Home and End jump, Enter and Space pick, Escape closes it and focuses the Move button, and Tab closes it and moves on from the Move button.
* A second click on the same Move button closes it.
*
* Where the browser can't anchor a popover, the code takes the menu's `popover` attribute off, places the menu at fixed coordinates under the button, and closes it on presses outside it.
*/
export class MoveMenu {
/**
* The board's root, where the Move buttons are.
*/
private readonly $root: HTMLElement;
/**
* The `[role="menu"]` element.
*/
private readonly $menu: HTMLElement;
/**
* The item buttons, by their `data-move` value.
*/
private readonly $items = new Map<MoveItem, HTMLButtonElement>();
/**
* What the menu shows for each card, and what it does with a pick.
*/
private readonly options: MoveMenuOptions;
/**
* Whether the menu is a popover anchored to the button, which takes both `position-area` in CSS and the `source` option of `showPopover()`.
*/
private readonly anchored: boolean;
/**
* The Move button that opened the menu, or null while the menu is closed.
*/
private $button: HTMLButtonElement | null = null;
/**
* The Move button whose menu was open when the last press started, so the click that follows closes it instead of opening it again, whatever light dismiss did in between.
*/
private $openAtPress: HTMLButtonElement | null = null;
/**
* Removes every listener in `destroy()`.
*/
private readonly listeners = new AbortController();
/**
* Builds the menu's items and wires the board's Move buttons to it.
*
* @param $root - The board's root, which holds the Move buttons.
* @param $menu - The empty `[role="menu"][popover]` element, with an id the buttons' `aria-controls` points at.
* @param options - The item texts, the state per card, and the pick callback.
*/
constructor( $root: HTMLElement, $menu: HTMLElement, options: MoveMenuOptions ) {
this.$root = $root;
this.$menu = $menu;
this.options = options;
const texts: Record<MoveItem, string> = {
top: options.messages.moveToTop,
up: options.messages.moveUp,
down: options.messages.moveDown,
bottom: options.messages.moveToBottom,
other: '',
};
for ( const item of MENU_ITEMS ) {
if ( item === 'other' ) {
const $separator = document.createElement( 'div' );
$separator.setAttribute( 'role', 'separator' );
$menu.append( $separator );
}
const $item = document.createElement( 'button' );
$item.setAttribute( 'role', 'menuitem' );
$item.tabIndex = -1;
$item.dataset.move = item;
$item.textContent = texts[ item ];
$menu.append( $item );
this.$items.set( item, $item );
}
this.anchored = CSS.supports( 'position-area', 'block-end' ) && showPopoverTakesSource();
if ( ! this.anchored ) {
$menu.removeAttribute( 'popover' );
$menu.hidden = true;
}
const { signal } = this.listeners;
$root.addEventListener( 'click', this.onButtonClick, { signal } );
$root.addEventListener( 'keydown', this.onButtonKeyDown, { signal } );
$menu.addEventListener( 'keydown', this.onMenuKeyDown, { signal } );
$menu.addEventListener( 'click', this.onMenuClick, { signal } );
$menu.addEventListener( 'toggle', this.onToggle, { signal } );
$root.ownerDocument.addEventListener( 'pointerdown', this.onPress, { capture: true, signal } );
}
/**
* Whether the menu is open.
*
* @returns Whether it's showing for a Move button.
*/
private isOpen(): boolean {
if ( this.$button === null ) {
return false;
}
return this.anchored ? this.$menu.matches( ':popover-open' ) : ! this.$menu.hidden;
}
/**
* Opens the menu for a card's Move button, and focuses its first or last item.
*
* @param $button - The Move button.
* @param enabledItems - The items that do something for this card.
* @param otherColumnTitle - The other column's title, for the last item.
* @param focus - Which item gets focus, the last one after Up on the button.
*/
open( $button: HTMLButtonElement, enabledItems: readonly MoveItem[], otherColumnTitle: string, focus: 'first' | 'last' = 'first' ): void {
this.close();
for ( const [ item, $item ] of this.$items ) {
if ( item === 'other' ) {
$item.textContent = this.options.messages.moveToColumn( otherColumnTitle );
}
if ( enabledItems.includes( item ) ) {
$item.removeAttribute( 'aria-disabled' );
} else {
$item.setAttribute( 'aria-disabled', 'true' );
}
}
if ( $button.ownerDocument.activeElement !== $button ) {
$button.focus( { preventScroll: true } );
}
this.$menu.setAttribute( 'aria-labelledby', $button.getAttribute( 'aria-labelledby' ) ?? $button.id );
this.$button = $button;
$button.setAttribute( 'aria-expanded', 'true' );
if ( this.anchored ) {
this.$menu.showPopover( { source: $button } );
} else {
this.$menu.hidden = false;
this.placeUnder( $button );
}
const $items = [ ...this.$items.values() ];
$items[ focus === 'first' ? 0 : $items.length - 1 ].focus( { preventScroll: true } );
}
/**
* Closes the menu, and puts focus back on its Move button when focus was in the menu.
*
* Focus that already left the menu stays where it went, like on another card's Move button that a drag just pressed.
* It also resets the button of a menu that light dismiss closed a moment ago, before its `toggle` event arrives.
*/
close(): void {
const $button = this.$button;
if ( $button === null ) {
return;
}
const hadFocus = this.$menu.contains( this.$menu.ownerDocument.activeElement );
this.$button = null;
$button.setAttribute( 'aria-expanded', 'false' );
if ( this.anchored ) {
if ( this.$menu.matches( ':popover-open' ) ) {
this.$menu.hidePopover();
}
} else {
this.$menu.hidden = true;
}
if ( hadFocus && $button.ownerDocument.activeElement !== $button ) {
$button.focus( { preventScroll: true } );
}
}
/**
* Closes the menu and removes every listener.
*/
destroy(): void {
this.close();
this.listeners.abort();
}
/**
* Places the menu under the button with fixed coordinates, where the browser can't anchor it, lined up with the button's right edge, and flips it up or to the right when it wouldn't fit.
*
* @param $button - The Move button.
*/
private placeUnder( $button: HTMLButtonElement ): void {
const view = $button.ownerDocument.documentElement;
const box = $button.getBoundingClientRect();
const width = this.$menu.offsetWidth;
const height = this.$menu.offsetHeight;
let top = box.bottom + 4;
if ( top + height > view.clientHeight - 4 && box.top - 4 - height >= 4 ) {
top = box.top - 4 - height;
}
let left = box.right - width;
if ( left < 4 ) {
left = Math.max( 4, Math.min( box.left, view.clientWidth - 4 - width ) );
}
this.$menu.style.top = `${top}px`;
this.$menu.style.left = `${left}px`;
}
/**
* Finds the Move button an event came from.
*
* @param event - An event inside the board.
* @returns The button, or null.
*/
private buttonOf( event: Event ): HTMLButtonElement | null {
if ( ! ( event.target instanceof Element ) ) {
return null;
}
const $button = event.target.closest( 'button[data-card-move]' );
return $button instanceof HTMLButtonElement && this.$root.contains( $button ) ? $button : null;
}
/**
* Opens the menu for a Move button.
*
* @param $button - The Move button.
* @param focus - Which item gets focus.
*/
private openFor( $button: HTMLButtonElement, focus: 'first' | 'last' ): void {
const { enabled, otherColumn } = this.options.describe( $button );
this.open( $button, enabled, otherColumn, focus );
}
/**
* Remembers whether the menu was open when a press started, and closes it on a press outside it where it isn't a popover.
*
* It listens in the capture phase on the document, before light dismiss and before the board's own `pointerdown` handlers.
*
* @param event - Any `pointerdown` in the document.
*/
private onPress = ( event: PointerEvent ): void => {
this.$openAtPress = this.isOpen() ? this.$button : null;
if ( ! this.anchored && this.isOpen() && event.target instanceof Node ) {
if ( ! this.$menu.contains( event.target ) && ! this.$button?.contains( event.target ) ) {
this.close();
}
}
};
/**
* Opens the menu on its first item when a Move button is clicked, tapped, or pressed with Enter or Space, and closes it on a second activation.
*
* For a pointer's click, with `detail` above 0, the handler checks whether the menu was open when the press started.
* A keyboard click has no press.
* A click that something already prevented, like a drag's guard, does nothing.
*
* @param event - A `click` inside the board.
*/
private onButtonClick = ( event: MouseEvent ): void => {
const $button = this.buttonOf( event );
if ( $button === null || event.defaultPrevented ) {
return;
}
const wasOpen = ( event.detail > 0 && this.$openAtPress === $button ) || ( this.isOpen() && this.$button === $button );
this.$openAtPress = null;
if ( wasOpen ) {
this.close();
} else {
this.openFor( $button, 'first' );
}
};
/**
* Opens the menu on its first item with Down, and on its last item with Up, while a Move button has focus.
*
* A key that something already prevented does nothing.
* During a drag, `BoardDrag` prevents Down and Up to keep the menu closed.
*
* @param event - A `keydown` inside the board.
*/
private onButtonKeyDown = ( event: KeyboardEvent ): void => {
const $button = this.buttonOf( event );
if ( $button === null || event.defaultPrevented || ( event.key !== 'ArrowDown' && event.key !== 'ArrowUp' ) ) {
return;
}
event.preventDefault();
this.openFor( $button, event.key === 'ArrowDown' ? 'first' : 'last' );
};
/**
* Handles the menu's keys.
*
* Enter and Space pick in `keydown`, where preventing the event also stops the click they'd make.
* That way a pick never runs twice.
* Tab isn't prevented, because the menu closes and focuses the Move button first.
* The browser then moves focus on from there.
*
* @param event - A `keydown` inside the menu.
*/
private onMenuKeyDown = ( event: KeyboardEvent ): void => {
const $items = [ ...this.$items.values() ];
const current = $items.findIndex( ( $item ) => $item === this.$menu.ownerDocument.activeElement );
const focusAt = ( index: number ): void => {
event.preventDefault();
$items[ ( index + $items.length ) % $items.length ].focus( { preventScroll: true } );
};
switch ( event.key ) {
case 'ArrowDown':
focusAt( current + 1 );
break;
case 'ArrowUp':
focusAt( current === -1 ? $items.length - 1 : current - 1 );
break;
case 'Home':
focusAt( 0 );
break;
case 'End':
focusAt( $items.length - 1 );
break;
case 'Enter':
case ' ':
event.preventDefault();
if ( current !== -1 ) {
this.pick( $items[ current ] );
}
break;
case 'Escape':
event.preventDefault();
this.close();
break;
case 'Tab':
this.close();
break;
}
};
/**
* Picks the item a pointer or an assistive technology clicked.
*
* @param event - A `click` inside the menu.
*/
private onMenuClick = ( event: MouseEvent ): void => {
const $item = event.target instanceof Element ? event.target.closest( '[role="menuitem"]' ) : null;
if ( $item instanceof HTMLButtonElement ) {
this.pick( $item );
}
};
/**
* Closes the menu and reports the item, unless the item is disabled, which keeps the menu open and does nothing.
*
* @param $item - The item.
*/
private pick( $item: HTMLButtonElement ): void {
const $button = this.$button;
const item = MENU_ITEMS.find( ( name ) => name === $item.dataset.move );
if ( $button === null || item === undefined || $item.getAttribute( 'aria-disabled' ) === 'true' ) {
return;
}
this.close();
this.options.onPick( item, $button );
}
/**
* Keeps `aria-expanded` in sync when the browser closes the popover itself, with light dismiss or Escape.
*
* The event arrives after the close, so a menu that opened again for another button in the meantime is left alone.
*
* @param event - The popover's `toggle` event.
*/
private onToggle = ( event: ToggleEvent ): void => {
if ( event.newState === 'closed' && this.$button !== null && ! this.$menu.matches( ':popover-open' ) ) {
this.$button.setAttribute( 'aria-expanded', 'false' );
this.$button = null;
}
};
}
/**
* Finds an element inside the board, or throws when the markup is missing it.
*
* @param $root - The board's root.
* @param selector - The element's selector.
* @returns The element.
*/
function part( $root: HTMLElement, selector: string ): HTMLElement {
const $found = $root.querySelector( selector );
if ( ! ( $found instanceof HTMLElement ) ) {
throw new Error( `The task board needs ${selector} inside its root element.` );
}
return $found;
}
/**
* A task board that moves cards with a Move menu on every card, and with a drag once a `BoardDrag` is attached.
*
* It enhances markup the page already has.
* That markup has `ol[data-column]` lists named by their headings through `aria-labelledby`, `li[data-card]` cards with a `[data-card-title]` title and a `button[data-card-move]` Move button, an empty `[data-move-menu]` popover, a `[data-board-status]` paragraph with `role="status"`, and an optional `[data-undo]` row with a `span` and a `button`.
* Every Move button and title has a document-unique id, and the Move button's `aria-labelledby` lists its own id and then the title's id, which names it "Move Fix login".
*
* Every move goes through `move()`, whatever made it.
* In `move()`, the order changes in the data, the card's element moves once, focus goes to its Move button, the status paragraph gets the message a second later, the Undo row gets the move, and a `card-move` event fires.
* The board writes nothing to the URL and saves nothing.
* An app saves the order from the `card-move` event.
*
* The Move buttons need `touch-action: none`, `user-select: none`, and `-webkit-user-select: none` in CSS.
* Without them, a touch drag doesn't work and a long press selects text.
*
* @fires card-move - After every move, with the move and what made it.
*/
export class TaskBoard implements DragBoard {
/**
* The board's root element, the only element of the board a `BoardDrag` uses.
*/
readonly $root: HTMLElement;
/**
* The autoscroll settings a `BoardDrag` uses.
*/
readonly autoscroll: AutoscrollOptions;
/**
* The board's order, the source of truth the page follows.
*/
private data: Columns;
/**
* Card and column titles by id.
*/
private readonly titles: Titles;
/**
* The cards' elements by id.
*/
private readonly $cards = new Map<CardId, HTMLElement>();
/**
* The lists by column id.
*/
private readonly $lists = new Map<ColumnId, HTMLElement>();
/**
* The visually hidden status paragraph.
*/
private readonly $status: HTMLElement;
/**
* The Undo row's message, when the board has an Undo row.
*/
private readonly $undoMessage: HTMLElement | null = null;
/**
* The Undo row's button, when the board has an Undo row.
*/
private readonly $undoButton: HTMLButtonElement | null = null;
/**
* The strings the board writes.
*/
private readonly messages: BoardMessages;
/**
* The delay between a move and its message, in milliseconds.
*/
private readonly announceDelay: number;
/**
* The board's one Move menu.
*/
private readonly menu: MoveMenu;
/**
* The last move, which Undo sends back, or null when there's nothing to undo.
*/
private lastMove: Move | null = null;
/**
* The pending message's timer, which a newer move cancels.
*/
private announceTimer: number | undefined;
/**
* Removes every listener in `destroy()`.
*/
private readonly listeners = new AbortController();
/**
* Gets the columns and cards from the markup and wires the Move buttons to the Move menu.
*
* @param $root - The board's root element.
* @param options - Product options, like translated strings, the message delay, and autoscroll.
*/
constructor( $root: HTMLElement, options: TaskBoardOptions = {} ) {
this.$root = $root;
this.messages = { ...DEFAULT_MESSAGES, ...options.messages };
this.announceDelay = options.announceDelay ?? 1000;
this.autoscroll = { ...DEFAULT_AUTOSCROLL, ...options.autoscroll };
const $menu = part( $root, '[data-move-menu]' );
if ( $menu.id === '' ) {
throw new Error( 'The Move menu needs an id, which the Move buttons point at with aria-controls.' );
}
this.$status = part( $root, '[data-board-status]' );
const columns: Record<ColumnId, readonly CardId[]> = {};
const titles: Record<string, string> = {};
for ( const $list of $root.querySelectorAll( 'ol[data-column]' ) ) {
const column = $list instanceof HTMLElement ? $list.dataset.column : undefined;
if ( ! ( $list instanceof HTMLElement ) || column === undefined ) {
continue;
}
this.$lists.set( column, $list );
const $heading = $root.ownerDocument.getElementById( $list.getAttribute( 'aria-labelledby' ) ?? '' );
titles[ column ] = $heading?.textContent?.trim() ?? column;
const ids: CardId[] = [];
for ( const $card of $list.querySelectorAll( 'li[data-card]' ) ) {
const id = $card instanceof HTMLElement ? $card.dataset.card : undefined;
if ( ! ( $card instanceof HTMLElement ) || id === undefined ) {
continue;
}
ids.push( id );
this.$cards.set( id, $card );
titles[ id ] = $card.querySelector( '[data-card-title]' )?.textContent?.trim() ?? id;
const $button = $card.querySelector( 'button[data-card-move]' );
if ( $button instanceof HTMLButtonElement ) {
$button.setAttribute( 'aria-haspopup', 'menu' );
$button.setAttribute( 'aria-expanded', 'false' );
$button.setAttribute( 'aria-controls', $menu.id );
}
}
columns[ column ] = ids;
}
this.data = columns;
this.titles = titles;
const $undo = $root.querySelector( '[data-undo]' );
if ( $undo ) {
const $message = $undo.querySelector( ':scope > span' );
const $button = $undo.querySelector( ':scope > button' );
if ( $message instanceof HTMLElement && $button instanceof HTMLButtonElement ) {
this.$undoMessage = $message;
this.$undoButton = $button;
$button.hidden = true;
$button.addEventListener( 'click', () => this.undo(), { signal: this.listeners.signal } );
}
}
this.menu = new MoveMenu( $root, $menu, {
messages: this.messages,
describe: ( $button ) => this.menuState( $button ),
onPick: ( item, $button ) => this.onPick( item, $button ),
} );
}
/**
* The board's order, read-only.
* `move()` is the only way to change it.
*
* @returns One array of card ids per column, top to bottom.
*/
get columns(): Columns {
return this.data;
}
/**
* Moves a card, the one call the Move menu, a drop, and Undo all make.
*
* After the data changes, the card's element moves once with `placeCard()`, `focusCard()` shows the card in its column and focuses its Move button, and the message goes out.
* When the card would end up where it is, nothing happens at all.
*
* @param cardId - The card to move.
* @param toColumn - The column it goes to.
* @param toIndex - The number of cards above it after the move, or the end of the column when it's left out.
* @param source - What made the move, passed on in the `card-move` event.
* @returns The new order and the move, or null when nothing moved.
*/
move( cardId: CardId, toColumn: ColumnId, toIndex?: number, source: MoveSource = 'api' ): MoveResult | null {
const result = moveCard( this.data, cardId, toColumn, toIndex );
if ( result === null ) {
return null;
}
this.data = result.columns;
const $card = this.$cards.get( cardId );
const $list = this.$lists.get( toColumn );
if ( $card && $list ) {
placeCard( $card, $list, result.move.to.index );
focusCard( $card );
}
const message = moveMessage( this.titles, this.data, result.move, this.messages.moved );
this.announce( message );
this.lastMove = source === 'undo' ? null : result.move;
this.showUndo( message );
const detail: CardMoveDetail = { move: result.move, source };
this.$root.dispatchEvent( new CustomEvent( 'card-move', { bubbles: true, detail } ) );
return result;
}
/**
* Sends the last moved card back to its old place, through `move()` like any other move.
*
* The old index is already the right index, because an index is the position after the card left its spot.
* With one level of Undo, a second call does nothing.
*
* @returns The move back, or null when there was nothing to undo.
*/
undo(): MoveResult | null {
const last = this.lastMove;
if ( last === null ) {
return null;
}
this.lastMove = null;
return this.move( last.cardId, last.from.column, last.from.index, 'undo' );
}
/**
* Closes the Move menu, which a drag does when it starts.
*/
closeMenu(): void {
this.menu.close();
}
/**
* Removes every listener and cancels a pending message.
*/
destroy(): void {
clearTimeout( this.announceTimer );
this.menu.destroy();
this.listeners.abort();
}
/**
* Empties the status paragraph now and writes the message a second later, replacing a message that's still waiting.
*
* Atlassian's live region package delays its messages by the same second.
* A comment in its code says the announcing function "is often called right before focus changes", like every menu move here.
*
* @param message - The message.
*/
private announce( message: string ): void {
this.$status.textContent = '';
clearTimeout( this.announceTimer );
this.announceTimer = window.setTimeout( () => {
this.$status.textContent = message;
}, this.announceDelay );
}
/**
* Shows the last move's message in the Undo row, and its Undo button only while there's a move to undo.
*
* Hiding the button never drops focus, because `move()` has already focused the card after an Undo.
*
* @param message - The message.
*/
private showUndo( message: string ): void {
if ( this.$undoMessage === null || this.$undoButton === null ) {
return;
}
this.$undoMessage.textContent = message;
this.$undoButton.hidden = this.lastMove === null;
}
/**
* Finds the card a Move button is in.
*
* @param $button - A Move button.
* @returns The card's id, or undefined.
*/
private cardIdOf( $button: HTMLButtonElement ): CardId | undefined {
const $card = $button.closest( 'li[data-card]' );
return $card instanceof HTMLElement ? $card.dataset.card : undefined;
}
/**
* Works out which menu items do something for a card.
* Nothing goes up from the top of a column or down from its bottom.
*
* @param $button - The card's Move button.
* @returns The enabled items and the other column's title.
*/
private menuState( $button: HTMLButtonElement ): MenuState {
const cardId = this.cardIdOf( $button );
const column = Object.keys( this.data ).find( ( id ) => cardId !== undefined && this.data[ id ].includes( cardId ) );
if ( cardId === undefined || column === undefined ) {
return { enabled: [], otherColumn: '' };
}
const index = this.data[ column ].indexOf( cardId );
const last = this.data[ column ].length - 1;
const other = Object.keys( this.data ).find( ( id ) => id !== column );
const enabled: MoveItem[] = [];
if ( index > 0 ) {
enabled.push( 'top', 'up' );
}
if ( index < last ) {
enabled.push( 'down', 'bottom' );
}
if ( other !== undefined ) {
enabled.push( 'other' );
}
return { enabled, otherColumn: other === undefined ? '' : this.titles[ other ] };
}
/**
* Moves the card a menu item names, after the menu closed and focus went back to the Move button.
*
* @param item - The picked item.
* @param $button - The card's Move button.
*/
private onPick( item: MoveItem, $button: HTMLButtonElement ): void {
const cardId = this.cardIdOf( $button );
if ( cardId !== undefined ) {
const [ column, index ] = targetFor( item, this.data, cardId );
this.move( cardId, column, index, 'menu' );
}
}
}
/**
* The pointer drag for a `TaskBoard`, or for any board with the members of `DragBoard`.
* It's one more way to say where a card should end up.
*
* A press on a Move button becomes a drag once the pointer moves 5 pixels.
* A press that moves less is a click, which opens the Move menu.
* During a drag, the card stays in its place at a lower opacity, a line shows where it will go, and a small preview follows the pointer.
* The target comes from geometry, from the column whose box has the pointer in it and the number of that column's other cards whose middle is above the pointer.
* `moveCard()` takes that same number as its index.
* On release, the drag passes it to `board.move()`, the same call the menu makes.
* Escape, `pointercancel`, a lost pointer capture, the page going hidden, and a release outside the columns all cancel the drag.
* After a cancel, nothing moves, the columns' scroll goes back, and focus stays on the Move button.
* Swallowing the next click after any press that became a drag keeps a drop from opening the menu.
*
* It uses only the board's root element, calls only `board.move()` and `board.closeMenu()`, and listens to the board's `card-move` event.
* It needs the Move buttons' `touch-action: none` in CSS, set before any touch starts.
* The line is drawn with the `data-drop-line` attribute (`before` or `after` on a card, `empty` on a list), the dragged card and the root get `data-dragging`, and the preview is a `.board-drag-preview` element in the root.
*/
export class BoardDrag {
/**
* The board this drag moves cards on.
*/
private readonly board: DragBoard;
/**
* The board's root element.
*/
private readonly $root: HTMLElement;
/**
* The press in progress, or null.
*/
private press: DragPress | null = null;
/**
* Where a drop would put the card now, which the line shows and the release uses.
*/
private target: DropTarget | null = null;
/**
* The element the line is drawn on.
*/
private $line: HTMLElement | null = null;
/**
* Whether the next click with a pointer comes from a press that became a drag.
*/
private swallowClick = false;
/**
* The autoscroll loop's animation frame.
*/
private frame = 0;
/**
* When the last autoscroll frame ran.
*/
private lastFrame = 0;
/**
* The list and direction autoscroll is running for, so the ramp starts over at a new edge.
*/
private edge: AutoscrollEdge | null = null;
/**
* When the pointer entered the current edge zone.
*/
private edgeSince = 0;
/**
* The fraction of a pixel autoscroll owes, since `scrollTop` rounds.
*/
private carry = 0;
/**
* Removes the listeners that live as long as the drag in `destroy()`.
*/
private readonly listeners = new AbortController();
/**
* Removes the listeners for one press when it ends.
*/
private pressListeners: AbortController | null = null;
/**
* Attaches the drag to a board.
*
* @param board - The board, a `TaskBoard` or any board with the members of `DragBoard`.
*/
constructor( board: DragBoard ) {
this.board = board;
this.$root = board.$root;
const { signal } = this.listeners;
const doc = this.$root.ownerDocument;
this.$root.addEventListener( 'pointerdown', this.onPointerDown, { signal } );
this.$root.addEventListener( 'dragstart', this.onDragStart, { signal } );
this.$root.addEventListener( 'card-move', this.onCardMove, { signal } );
doc.addEventListener( 'pointerdown', this.onAnyPress, { capture: true, signal } );
doc.addEventListener( 'click', this.onClick, { capture: true, signal } );
}
/**
* Ends a drag in progress without moving anything, and removes every listener.
*/
destroy(): void {
this.cancelDrag();
this.listeners.abort();
}
/**
* Starts a press on a Move button.
*
* For a mouse or a pen, `preventDefault()` stops text selection, which in Firefox turned the next press into the browser's own drag, and stops the browser from scrolling a column under a pressed mouse.
* It doesn't stop a mouse click, so a press that never moves still opens the menu.
* A touch press isn't prevented.
* WebKit drops a tap's click after a prevented `pointerdown`, which would leave a tap unable to open the menu.
* With `touch-action: none` on the button, the browser doesn't scroll from it anyway.
* The board focuses the button itself, since Safari doesn't focus a button on a click.
* Then it captures the pointer, which sends every move to the button.
* The board listens for the rest of the press on the document, which catches every case even if capture ends early.
*
* @param event - A `pointerdown` inside the board.
*/
private onPointerDown = ( event: PointerEvent ): void => {
if ( this.press !== null || ! event.isPrimary || event.button !== 0 || ! ( event.target instanceof Element ) ) {
return;
}
const $button = event.target.closest( 'button[data-card-move]' );
const $card = $button?.closest( 'li[data-card]' );
if ( ! ( $button instanceof HTMLButtonElement ) || ! ( $card instanceof HTMLElement ) || ! this.$root.contains( $card ) ) {
return;
}
const cardId = $card.dataset.card;
if ( cardId === undefined ) {
return;
}
if ( event.pointerType !== 'touch' ) {
event.preventDefault();
}
$button.focus( { preventScroll: true } );
try {
$button.setPointerCapture( event.pointerId );
} catch {
// The pointer is already gone, and pointercancel or pointerup ends the press.
}
this.press = {
pointerId: event.pointerId,
$button,
$card,
cardId,
startX: event.clientX,
startY: event.clientY,
x: event.clientX,
y: event.clientY,
dragging: false,
scroll: new Map(),
$preview: null,
};
this.pressListeners = new AbortController();
const { signal } = this.pressListeners;
const doc = this.$root.ownerDocument;
doc.addEventListener( 'pointermove', this.onPointerMove, { signal } );
doc.addEventListener( 'pointerup', this.onPointerUp, { signal } );
doc.addEventListener( 'pointercancel', this.onPointerEnd, { signal } );
doc.addEventListener( 'lostpointercapture', this.onPointerEnd, { signal } );
doc.addEventListener( 'keydown', this.onKeyDown, { capture: true, signal } );
doc.addEventListener( 'scroll', this.onScroll, { capture: true, passive: true, signal } );
doc.addEventListener( 'visibilitychange', this.onVisibilityChange, { signal } );
doc.addEventListener( 'contextmenu', this.onContextMenu, { signal } );
};
/**
* Keeps the pointer's last position, turns the press into a drag past the threshold, and redraws the line.
*
* @param event - A `pointermove` in the document.
*/
private onPointerMove = ( event: PointerEvent ): void => {
const press = this.press;
if ( press === null || event.pointerId !== press.pointerId ) {
return;
}
press.x = event.clientX;
press.y = event.clientY;
if ( ! press.dragging ) {
if ( Math.hypot( press.x - press.startX, press.y - press.startY ) < DRAG_THRESHOLD ) {
return;
}
this.startDrag( press );
}
this.showTarget( this.targetAt( press ) );
this.movePreview( press );
};
/**
* Drops the card where the line is, with the same `move()` call the menu makes, or cancels when there's no line.
*
* The press ends before the move.
* A `lostpointercapture` from an `insertBefore()` move then finds no press and never counts as a cancel.
* A press that never became a drag only ends, and the click after it opens the menu.
*
* @param event - A `pointerup` in the document.
*/
private onPointerUp = ( event: PointerEvent ): void => {
const press = this.press;
if ( press === null || event.pointerId !== press.pointerId ) {
return;
}
const target = press.dragging ? this.target : null;
if ( target === null ) {
this.cancelDrag();
return;
}
this.endDrag();
this.board.move( press.cardId, target.column, target.index, 'drag' );
};
/**
* Cancels the drag when the browser takes the pointer back, or when capture ends before the release.
*
* @param event - A `pointercancel` or `lostpointercapture` in the document.
*/
private onPointerEnd = ( event: PointerEvent ): void => {
if ( this.press !== null && event.pointerId === this.press.pointerId ) {
this.cancelDrag();
}
};
/**
* Cancels the drag on Escape, and keeps Enter, Space, Down, and Up on a Move button from opening the menu under a drag.
*
* The browser does nothing to a pointer drag on Escape, so the board listens for it.
* The listener is on the document in the capture phase.
* It runs before the Move menu's own `keydown` handler on the board, which skips any key that's already prevented.
* A button makes its Space click on `keyup`, out of this listener's reach.
* The click guard drops that click instead.
*
* @param event - A `keydown` in the document, in the capture phase.
*/
private onKeyDown = ( event: KeyboardEvent ): void => {
if ( this.press === null || ! this.press.dragging ) {
return;
}
if ( event.key === 'Escape' ) {
event.preventDefault();
this.cancelDrag();
} else if ( MENU_KEYS.has( event.key ) && event.target instanceof Element && event.target.closest( 'button[data-card-move]' ) ) {
event.preventDefault();
}
};
/**
* Works the line out again from the last pointer position on every scroll in the page.
*
* When a column scrolls under a pointer that holds still, the browser sends no `pointermove`, whether autoscroll, a wheel, or a trackpad scrolled it.
* Scroll events don't bubble, so the listener is on the document in the capture phase.
*/
private onScroll = (): void => {
if ( this.press?.dragging ) {
this.showTarget( this.targetAt( this.press ) );
this.movePreview( this.press );
}
};
/**
* Cancels the drag when the page goes hidden.
*/
private onVisibilityChange = (): void => {
if ( this.$root.ownerDocument.visibilityState === 'hidden' ) {
this.cancelDrag();
}
};
/**
* Keeps a long press from opening the context menu while a drag runs.
*
* @param event - A `contextmenu` in the document.
*/
private onContextMenu = ( event: MouseEvent ): void => {
if ( this.press?.dragging ) {
event.preventDefault();
}
};
/**
* Stops the browser's own drag of anything inside the board, like a link or an image, which WebKit starts without a `pointercancel`.
*
* @param event - A `dragstart` inside the board.
*/
private onDragStart = ( event: DragEvent ): void => {
event.preventDefault();
};
/**
* Ends a drag without a move of its own when another move happens during it, like a keyboard Undo or app code calling `move()`.
* The scroll stays where that move left it, and focus stays where it put it.
*/
private onCardMove = (): void => {
this.endDrag();
};
/**
* Forgets a swallow that no click used, at the start of the next press.
*/
private onAnyPress = (): void => {
this.swallowClick = false;
};
/**
* Swallows the click that follows a press that became a drag, dropped or cancelled, and any click on a Move button while a drag runs.
*
* A keyboard Enter or Space after a drag makes a click with `detail` 0.
* That click never matches and always opens the menu.
* During a drag, this handler drops the Space click a button makes on `keyup`, after the `keydown` guard has already run.
* A click on anything else during a drag, like a keyboard Undo, still goes through.
*
* @param event - Any `click` in the document, in the capture phase.
*/
private onClick = ( event: MouseEvent ): void => {
if ( this.press?.dragging && event.target instanceof Element && event.target.closest( 'button[data-card-move]' ) ) {
event.preventDefault();
event.stopPropagation();
return;
}
if ( this.swallowClick && event.detail > 0 ) {
event.preventDefault();
event.stopPropagation();
this.swallowClick = false;
}
};
/**
* Turns a press into a drag.
* It closes the menu, records each list's scroll for a cancel, dims the card, adds the preview, and starts autoscroll.
*
* @param press - The press.
*/
private startDrag( press: DragPress ): void {
press.dragging = true;
this.board.closeMenu();
for ( const $list of this.lists() ) {
press.scroll.set( $list, $list.scrollTop );
}
press.$card.dataset.dragging = '';
this.$root.dataset.dragging = '';
const $preview = this.$root.ownerDocument.createElement( 'div' );
$preview.className = 'board-drag-preview';
$preview.setAttribute( 'aria-hidden', 'true' );
$preview.textContent = press.$card.querySelector( '[data-card-title]' )?.textContent?.trim() ?? '';
this.$root.append( $preview );
press.$preview = $preview;
this.lastFrame = performance.now();
this.frame = requestAnimationFrame( this.tick );
}
/**
* Puts the preview to the right of the pointer and just below it, inside the window.
*
* When the line is below the pointer, the preview goes below the line too.
* It never covers the line or the card right above it, the two things people watch to see where the card will go.
*
* @param press - The press.
*/
private movePreview( press: DragPress ): void {
const $preview = press.$preview;
if ( $preview === null ) {
return;
}
const view = this.$root.ownerDocument.documentElement;
const below = Math.max( press.y + 12, this.lineBottom() + 6 );
const left = Math.max( Math.min( press.x + 16, view.clientWidth - $preview.offsetWidth - 4 ), 4 );
const top = Math.max( Math.min( below, view.clientHeight - $preview.offsetHeight - 4 ), 4 );
$preview.style.left = `${left}px`;
$preview.style.top = `${top}px`;
}
/**
* Finds the lowest point of the gap the line is drawn in.
* That's the top of the card under the line, one list gap below the last card, or the top of an empty list's content.
*
* @returns The y coordinate in viewport pixels, or minus infinity when no line is drawn.
*/
private lineBottom(): number {
const $line = this.$line;
if ( $line === null ) {
return -Infinity;
}
const box = $line.getBoundingClientRect();
if ( $line.dataset.dropLine === 'before' ) {
return box.top;
}
if ( $line.dataset.dropLine === 'after' ) {
const $list = $line.parentElement;
return box.bottom + ( $list ? Number.parseFloat( getComputedStyle( $list ).rowGap ) || 0 : 0 );
}
return box.top + ( Number.parseFloat( getComputedStyle( $line ).paddingTop ) || 0 );
}
/**
* The board's lists.
*
* @returns Every `ol[data-column]` in the board.
*/
private lists(): HTMLElement[] {
return [ ...this.$root.querySelectorAll( 'ol[data-column]' ) ].filter( ( $list ) => $list instanceof HTMLElement );
}
/**
* Works out the box a list's column covers for the drop.
* The box takes in the list, its heading above it, and the zone below it.
*
* @param $list - A list.
* @returns The left, right, top, and bottom edges, in viewport pixels.
*/
private columnBox( $list: HTMLElement ): ColumnBox {
const box = $list.getBoundingClientRect();
const $heading = this.$root.ownerDocument.getElementById( $list.getAttribute( 'aria-labelledby' ) ?? '' );
const top = $heading ? Math.min( $heading.getBoundingClientRect().top, box.top ) : box.top;
return { left: box.left, right: box.right, top, bottom: box.bottom + BELOW_LIST };
}
/**
* Works out where a drop would put the card, from positions only, since a captured pointer sends every event to the button.
*
* @param press - The press, with the pointer's last position.
* @returns The column and the index, or null when the pointer is over neither column.
*/
private targetAt( press: DragPress ): DropTarget | null {
for ( const $list of this.lists() ) {
const box = this.columnBox( $list );
const column = $list.dataset.column;
if ( column === undefined || press.x < box.left || press.x > box.right || press.y < box.top || press.y > box.bottom ) {
continue;
}
const $others = [ ...$list.children ].filter( ( $child ) => $child !== press.$card );
const middles = $others.map( ( $other ) => {
const card = $other.getBoundingClientRect();
return card.top + card.height / 2;
} );
const index = slotIndex( middles, press.y );
const same = $list === press.$card.parentElement && index === [ ...$list.children ].indexOf( press.$card );
return { column, index, same };
}
return null;
}
/**
* Draws the line in the gap where the card would go, on the card below that gap, on the last card for the end, or on an empty list.
*
* The line hides over the card's own place, where a drop changes nothing.
*
* @param target - Where a drop would put the card, or null.
*/
private showTarget( target: DropTarget | null ): void {
this.target = target;
this.$line?.removeAttribute( 'data-drop-line' );
this.$line = null;
const press = this.press;
if ( press === null || target === null || target.same ) {
return;
}
const $list = this.lists().find( ( $candidate ) => $candidate.dataset.column === target.column );
if ( $list === undefined ) {
return;
}
const $others = [ ...$list.children ].filter( ( $child ) => $child !== press.$card && $child instanceof HTMLElement );
const $before = $others[ target.index ];
const $last = $others.at( -1 );
if ( $before instanceof HTMLElement ) {
$before.dataset.dropLine = 'before';
this.$line = $before;
} else if ( $last instanceof HTMLElement ) {
$last.dataset.dropLine = 'after';
this.$line = $last;
} else {
$list.dataset.dropLine = 'empty';
this.$line = $list;
}
}
/**
* Finds the list edge the pointer is close to, if any, and how fast to scroll it there.
*
* The zone is the 48 pixels inside a list's top and bottom edges, or a quarter of its height when that's smaller, plus the heading above it and the 60 pixels below it.
*
* @param press - The press.
* @returns The edge, or null outside every zone or at the list's scroll limit.
*/
private edgeAt( press: DragPress ): AutoscrollEdge | null {
for ( const $list of this.lists() ) {
const column = this.columnBox( $list );
if ( press.x < column.left || press.x > column.right || press.y < column.top || press.y > column.bottom ) {
continue;
}
const box = $list.getBoundingClientRect();
const zone = Math.min( this.board.autoscroll.zone, box.height / 4 );
const { maxSpeed } = this.board.autoscroll;
if ( press.y > box.bottom - zone && $list.scrollTop < $list.scrollHeight - $list.clientHeight - 0.5 ) {
return { $list, direction: 1, speed: edgeSpeed( press.y - ( box.bottom - zone ), zone, maxSpeed ) };
}
if ( press.y < box.top + zone && $list.scrollTop > 0 ) {
return { $list, direction: -1, speed: edgeSpeed( box.top + zone - press.y, zone, maxSpeed ) };
}
return null;
}
return null;
}
/**
* One autoscroll frame.
*
* The speed is per second and gets multiplied by the time since the last frame, which keeps it the same at any refresh rate.
* It grows over the first 400 milliseconds in a zone.
* The loop only scrolls.
* The scroll listener redraws the line on the `scroll` that each step fires.
*
* @param now - The frame's timestamp.
*/
private tick = ( now: number ): void => {
const press = this.press;
if ( press === null || ! press.dragging ) {
return;
}
const elapsed = Math.min( Math.max( now - this.lastFrame, 0 ), MAX_FRAME );
this.lastFrame = now;
const edge = this.edgeAt( press );
const previous = this.edge;
if ( edge === null || previous === null || edge.$list !== previous.$list || edge.direction !== previous.direction ) {
this.edgeSince = now;
this.carry = 0;
}
this.edge = edge;
if ( edge !== null ) {
const ramp = Math.min( ( now - this.edgeSince ) / AUTOSCROLL_RAMP, 1 );
this.carry += edge.speed * ramp * elapsed / 1000;
const step = Math.trunc( this.carry );
if ( step > 0 ) {
this.carry -= step;
edge.$list.scrollTop += step * edge.direction;
}
}
this.frame = requestAnimationFrame( this.tick );
};
/**
* Ends the press without a move.
* When the press had become a drag, it first puts each list's scroll back.
*/
private cancelDrag(): void {
const press = this.press;
if ( press?.dragging ) {
for ( const [ $list, top ] of press.scroll ) {
$list.scrollTop = top;
}
}
this.endDrag();
}
/**
* Removes the line and the preview, undims the card, stops autoscroll, clears the press, and turns the click swallow on when the press had become a drag.
*/
private endDrag(): void {
const press = this.press;
if ( press === null ) {
return;
}
this.press = null;
this.pressListeners?.abort();
this.pressListeners = null;
cancelAnimationFrame( this.frame );
this.edge = null;
this.carry = 0;
this.showTarget( null );
press.$preview?.remove();
delete press.$card.dataset.dragging;
delete this.$root.dataset.dragging;
if ( press.dragging ) {
this.swallowClick = true;
}
}
}Markup and data
A column is an <ol> with a heading, because the order of the cards means something.
HTML defines an ordered list as a list where changing the order changes the meaning.
MDN notes that Safari doesn’t tell screen readers that a list with hidden markers is a list, unless it has role="list".
We add that role to the columns’ lists.
Firefox makes a scrollable list a Tab stop of its own, so the list needs a name.
We give it one by pointing its aria-labelledby at the column’s heading.
Cards are <li> elements with a title and a button that shows a grip icon and the word Move.
I’d keep the word, since Nielsen Norman Group found that grip icons are “not nearly as universal as designers may think”.
The button on “Fix login” gets the name “Move Fix login” from an aria-labelledby that points at the button itself first and at the title second.
board.html
<!-- board.html -->
<!-- The To do column: a heading and the list it names -->
<h2 id="todo-title">To do</h2>
<ol id="todo" role="list" aria-labelledby="todo-title">
<!-- One card, with its title and its Move button -->
<li id="fix-login">
<p id="fix-login-title">Fix login</p>
<button
id="fix-login-move"
type="button"
class="move"
aria-labelledby="fix-login-move fix-login-title"
>Move</button>
</li>
</ol>I don’t like the idea of a visible button on a board full of cards.
On screens with hover, it only shows up at the top right of the card you’re pointing at or working with.
We hide it with opacity, because display: none and visibility: hidden would take it out of the Tab order too.
On touch screens, which don’t have hover, the button is always visible.
board.css
/* board.css */
@media ( hover: hover ) {
/* Hide the Move button unless you point at its card, Tab to it,
or open its menu. */
li:not( :hover, :focus-within ) .move:not( [aria-expanded='true'] ) {
opacity: 0;
}
}We keep the order in a columns object, with one array of card ids per column, like { todo: [ 'pricing-page', 'fix-login' ], doing: [ 'mobile-menu' ] }.
The card and column titles go in a separate titles object.
One function for every move
Every move on this board goes through one function, move().
First, it gets the new order from moveCard(), a function that changes nothing but the data.
moveCard() takes the columns object and a cardId, plus the column and an optional index where the card should go.
It’s easy to get that index off by one. While you drag a card down, it stays in its old place, above the line that shows where it’ll go. If you count the cards above the line, you count the card you’re dragging too, which puts it one place past the line.
Flutter (Google’s framework for building apps) fixes this in its reorderable list by lowering the new index by one on a move down.
Flutter runs its drop through the function that makes that correction, along with the Move up and Move down actions it gives screen readers, like the drag and the menu on this board.
The older onReorder callback didn’t make that correction and is deprecated now.
I count the index with the card already taken out of its old spot. Counted like that, a move down is always the old index plus one. And for a drag, you just count the cards above the line, without the one you’re dragging.
Some moves don’t have a position, like . Without an index, the card goes to the end, like a drop below a column’s last card.
I put that default in the shared code, instead of writing it once for the drag and again for the menu.
Atlassian’s example board for its Pragmatic drag and drop library does that for moves to another column. In that board, a card with no index goes to the top, whether you pick a Move to item or drop it on the other column’s empty space. But if you drop it on the empty space of its own column, the code works out the index itself and puts the card at the bottom.
That said, I don’t mind the top, as long as the menu and the drop both send cards there.
board.js
// board.js
function moveCard( columns, cardId, toColumn, toIndex = Infinity ) {
// Find where the card is now.
const fromColumn = Object.keys( columns ).find( ( id ) => {
return columns[ id ].includes( cardId );
} );
const fromIndex = columns[ fromColumn ].indexOf( cardId );
// Count positions in the destination without the card,
// and keep the index between the top and the bottom.
const others = columns[ toColumn ].filter( ( id ) => {
return id !== cardId;
} );
const index = Math.min( Math.max( toIndex, 0 ), others.length );
// A card that would stay where it is doesn't move.
if ( fromColumn === toColumn && fromIndex === index ) {
return null;
}
// Build new arrays and leave the columns we got alone.
const next = { ...columns };
next[ fromColumn ] = columns[ fromColumn ].filter( ( id ) => {
return id !== cardId;
} );
next[ toColumn ] = others.toSpliced( index, 0, cardId );
// Keep the card's old place and its new one, for the message and Undo.
const move = {
cardId,
from: { column: fromColumn, index: fromIndex },
to: { column: toColumn, index },
};
return { columns: next, move };
}Our moveCard() keeps the index between the top and the bottom of the column.
Because it builds new arrays and leaves the columns you pass in alone, you can call it on a framework’s state directly, like an Angular signal’s value or React state.
If the card would stay where it is, we get null back from moveCard() and skip the rest.
That’s because even putting a card’s element right back where it was can take focus away from it.
We’ll keep the move that moveCard() returns, with the card’s old place and its new one, for the message and for Undo.
And since moveCard() doesn’t touch the page, you can test it with a plain unit test.
A Move menu on every card
The second way to move a card has to work with clicks or taps, without dragging. Keyboard support alone isn’t enough. W3C’s explanation of the rule points out that “people using a touchscreen device may not use a physical keyboard”.
The example on that page is even a task board, with a pop-up menu for moving a card to another column. W3C’s G219 technique and Atlassian’s guidelines for its library describe a menu like that too.
Google Tasks has a menu next to a task for moving it to another list.
GitHub Projects lets you pick up a card with Enter and move it with the arrow keys. I didn’t add that. The menu already works with the keyboard.
Atlassian also advises against arrow-key controls, partly because people using the JAWS screen reader have to switch its mode first.
On this board, one button per card opens the menu and starts the drag.
W3C has a collection of patterns for accessible widgets, called the ARIA Authoring Practices Guide (APG).
It doesn’t have a drag and drop pattern, even though a request for one has been open since 2019.
ARIA used to have aria-grabbed and aria-dropeffect for drag and drop, but both are deprecated without a replacement.
I followed the APG’s menu button pattern for the button.
It gets three attributes from that pattern:
aria-haspopup="menu"to tell screen readers it opens a menu.aria-expanded, set to true while the menu is open.aria-controlsto point it to the menu.
All the cards share one menu. It’s outside the columns and doesn’t move with them.
The menu is a popover, an element the browser shows above the rest of the page. We place it under the button with CSS anchor positioning, like the list in my picker article.
If it doesn’t fit near an edge of the window, position-try-fallbacks lets the browser flip it above the button or to its other side, like the hovercard in my tooltip article.
To open it, we focus the button and pass it to showPopover() in the source option.
On Escape, hidePopover() closes the menu and puts focus back on the button.
In browsers without anchor positioning or the source option, we take the popover attribute off, place the menu under the button with fixed positioning, and close it ourselves on a press outside it.
board.html
<!-- board.html -->
<!-- The Move button, which opens the shared menu -->
<button
id="fix-login-move"
type="button"
class="move"
aria-labelledby="fix-login-move fix-login-title"
aria-haspopup="menu"
aria-expanded="false"
aria-controls="move-menu"
>Move</button>
<!-- One menu for every card, outside the columns -->
<div id="move-menu" role="menu" popover>
<button role="menuitem" tabindex="-1" data-move="top">Move to top</button>
</div>The other four items follow , with a separator above .
Every time the menu opens, we copy the button’s aria-labelledby onto it to name it “Move Fix login”.
Like in the APG, Enter or Space opens it on the first item, and Up opens it on the last.
Atlassian’s guidelines suggest item names that include the card, like “Move task ‘clean dishes’ to top of backlog”. But under WCAG’s Label in Name rule, an item’s name has to contain the text it shows, ideally at the start. Atlassian’s example puts the card’s name between Move and to top. So I put the card’s name in the button, after the word Move, and named the items by their text alone.
targetFor() turns an item’s data-move value into a column and an index.
move-menu.js
// move-menu.js
function targetFor( item, columns, cardId ) {
// Where the card is now, and which column is the other one.
const column = Object.keys( columns ).find( ( id ) => {
return columns[ id ].includes( cardId );
} );
const index = columns[ column ].indexOf( cardId );
const other = Object.keys( columns ).find( ( id ) => {
return id !== column;
} );
// Each item's column and index.
// Without an index, the card goes to the end of the column.
const targets = {
top: [ column, 0 ],
up: [ column, index - 1 ],
down: [ column, index + 1 ],
bottom: [ column ],
other: [ other ],
};
return targets[ item ];
}When you pick an item, we close the menu with hidePopover() and call move( cardId, ...targetFor( item, columns, cardId ) ) to run moveCard() and update the page to match.
and don’t do anything on a column’s first card, just like and on its last one.
We keep them in place and focusable with aria-disabled="true", as the APG’s menu pattern describes for disabled items.
Menu items here are 36 pixels tall, more than the 24 pixels WCAG’s target size rule requires for a menu that opens over the page.
Keeping focus on the card
If you move a card with the keyboard, you expect to stay on it, ready to move it again.
But insertBefore() moves an element by taking it out of the page and putting it back, which sends focus to the body.
I showed the same thing for appendChild() in my article on memory leaks.
And in Chrome and Firefox, the next Tab takes you to whatever came after the card’s old spot.
moveBefore() moves the card without taking it out of the page.
Focus stays on its button, so Tab takes you to its new neighbor.
We fall back to insertBefore() in Safari, since it doesn’t have moveBefore().
placeCard() moves the card’s <li>, and like moveCard(), it counts the list’s children without the card.
board.js
// board.js
function placeCard( $card, $list, index ) {
// Find the card it goes in front of, counting without it.
const $others = [ ...$list.children ].filter( ( $child ) => {
return $child !== $card;
} );
const $next = $others[ index ] ?? null;
// moveBefore() keeps focus on the card.
// Where it's missing, like in Safari, use insertBefore().
if ( 'moveBefore' in $list ) {
$list.moveBefore( $card, $next );
} else {
$list.insertBefore( $card, $next );
}
}MDN says that “Most browsers do give focus to a button being clicked, but Safari does not, by design.” So in Safari, a clicked button doesn’t have focus for the board to put back. That’s why the board always focuses the moved card’s button itself, whether it had focus or not.
focusCard() scrolls the column just enough to show the card and focuses the button without letting the browser scroll.
A plain focus() would scroll a button that’s out of view to the middle of the column.
Like in the picker article, I skipped scrollIntoView().
It can scroll the article page around the demo.
board.js
// board.js
function focusCard( $card ) {
// The card's box and its column's box on screen.
const $list = $card.parentElement;
const card = $card.getBoundingClientRect();
const list = $list.getBoundingClientRect();
// Scroll the column just enough to show the card.
if ( card.top < list.top ) {
$list.scrollTop -= list.top - card.top;
} else if ( card.bottom > list.bottom ) {
$list.scrollTop += card.bottom - list.bottom;
}
// Focus its Move button without letting the browser scroll again.
const $button = $card.querySelector( '.move' );
$button.focus( { preventScroll: true } );
}Our move() calls moveCard(), placeCard(), and focusCard(), in that order.
board.js
// board.js
function move( cardId, toColumn, toIndex ) {
// Work out the new order, or stop if the card stays where it is.
const result = moveCard( columns, cardId, toColumn, toIndex );
if ( ! result ) {
return;
}
columns = result.columns;
// Move the card's element and put focus back on it.
const $card = document.getElementById( cardId );
const $list = document.getElementById( toColumn );
placeCard( $card, $list, result.move.to.index );
focusCard( $card );
}The buttons at the top of the next board let you pick how it moves the card’s element. (In Safari, Tab reaches buttons if you turn on Press Tab to highlight each item on a webpage in its Advanced settings.)
- Press Tab until the Focus line shows “Move Fix login”, and press Enter.
- Press Down twice and Enter to pick , then press Tab.
- Pick at the top and do both steps again, and once more with .
With a mouse, you can drag “Fix login” one card down or pick from its menu, and press Tab once it moves.
The Focus line showed Page body with .
The board’s fallback for Safari, , keeps focus on “Move Fix login”, like .
Messages for screen readers
Sighted people see the card move. Screen reader users need to hear where it went, because the button’s name doesn’t say the column. It’s just “Move Fix login”.
WCAG calls this kind of message a status message. You have to mark it up for screen readers and other assistive technology to announce it without moving focus.
Like in my picker article, I write the message to a visually hidden paragraph with role="status".
Screen readers announce changes to the text of a live region, an element like this one.
We put the paragraph in the page from the start and empty it before every message.
It also has aria-live="polite" next to the role.
TetraLogical’s tests in 2024 found a browser and screen reader pair that announced aria-live="polite" but not role="status".
Messages are one sentence, like “Fix login moved to position 3 of 14 in To do.” Positions start at 1. I left the old position out. I mean, whoever moved the card knows where it came from.
Like Atlassian’s live region package, we write the message a second later. A comment in that package explains that its announcing function “is often called right before focus changes”, and that the focus change would often get the message skipped or interrupted. And a menu move changes focus right away.
Drops and Undo get a message too, since they go through move(), but a cancelled drag doesn’t.
Browsers also have ariaNotify(), a method that queues a string for screen readers to announce without a live region.
Chrome shipped it first, followed by Firefox and Safari.
W3C documents the status region for the result of an action, and ariaNotify() for progress updates next to a live region.
MDN adds that live region announcements take priority over ariaNotify() ones, and that usually only the latest announcement gets spoken.
I’d send a move’s message through the status paragraph alone.
We call announce() from move() next to focusCard() and pass it the move from moveCard().
It writes the message to $status, the status paragraph.
A newer move cancels any message that hasn’t been written yet.
board.js
// board.js
const $status = document.querySelector( '#board-status' );
let announceTimer;
function announce( { cardId, to } ) {
// Empty the paragraph now, and cancel a message that's still waiting.
$status.textContent = '';
clearTimeout( announceTimer );
// Write the message a second later, once focus has moved.
const count = columns[ to.column ].length;
const position = `position ${to.index + 1} of ${count}`;
const card = titles[ cardId ];
const column = titles[ to.column ];
announceTimer = setTimeout( () => {
$status.textContent = `${card} moved to ${position} in ${column}.`;
}, 1000 );
}Dragging a card
The drag is just one more way to say where a card goes.
It turns where the pointer is into a column and a position, and passes them to move() when you let go.
I’d build it with pointer events (the events browsers send for a mouse, a finger, or a pen) instead of HTML’s drag and drop. HTML’s drag and drop doesn’t work with a keyboard, and it drags a picture of the card that the browser takes. And whether a column scrolls during a native drag depends on the browser. Pragmatic drag and drop and Adobe’s React Aria still build on it, and add a menu or a keyboard path on top.
You’d need it to drag files in from the desktop or between windows, but a board would still need the Move menu.
While you drag, the card stays dimmed in its place, as Atlassian’s design guidelines suggest. Nothing else moves, except a small preview of the card’s title that follows the pointer.
We capture the pointer with setPointerCapture() on the press.
From then on, the browser sends the pointer’s events to the button, wherever the pointer goes.
If we moved the card with insertBefore() in the middle of the drag, its button would lose both the capture and focus.
That happens in Playwright’s builds of Chromium, Firefox, and WebKit (Safari’s engine).
moveBefore() keeps the capture, but Safari doesn’t have it.
The downside of leaving the card in place is that you don’t see where the cards end up until you let go. If you’d rather show that during the drag, Nielsen Norman Group describes moving the other cards aside with an animation of about 100 milliseconds.
For touch, you have to tell the browser ahead of time, in CSS, that a swipe on the button shouldn’t scroll the page.
You do that with touch-action, the CSS property for the gestures the browser handles itself.
The browser checks it at the start of a touch, and it ignores any change you make in a pointerdown listener for the rest of the touch.
Only the button gets touch-action: none.
Swipes and pinch zoom work normally on the rest of the card.
Next to touch-action, we use user-select: none, plus its -webkit- version for Safari, to keep a long press from selecting the button’s text.
board.css
/* board.css */
.move {
/* A swipe on the button drags the card instead of scrolling the page. */
touch-action: none;
/* A long press doesn't select the button's text. */
user-select: none;
-webkit-user-select: none;
cursor: grab;
}In Chromium’s touch emulation, a touch drag on a button with auto or pan-y got a pointer move or two, followed by a pointercancel.
Browsers send one if they take the pointer for themselves.
Then the browser scrolled the column, if it had room to.
With none, the drag kept going.
The drag and drop library dnd-kit delays a touch drag by 250 milliseconds.
A swipe during that time scrolls the page instead.
Our button has none, which makes a delay unnecessary.
On a phone, I kept the two columns side by side, about 145 pixels wide inside this article. That way, a drag into the other column stays inside the demo. The UK government’s GOV.UK publishing components turn dragging off on small screens instead, and keep their up and down buttons.
Anyway, our drag starts with a pointerdown on a button.
For a mouse or a pen, we call preventDefault() on it.
Without it, Firefox could leave text selected after one drag and turn the next press into a native drag.
Firefox and WebKit would also scroll the column by themselves while you hold the mouse button down below it.
Touch presses aren’t prevented.
In WebKit, a tap whose pointerdown was prevented didn’t get the click that opens the menu.
A prevented press doesn’t focus the button in any of the three engines. We focus it ourselves.
drag.js
// drag.js
const $board = document.querySelector( '#board' );
let press = null;
$board.addEventListener( 'pointerdown', ( event ) => {
// Only the main button or the first finger, on a Move button.
const $button = event.target.closest( '.move' );
if ( ! $button || ! event.isPrimary || event.button !== 0 ) {
return;
}
// Stop text selection and native drags, but let a tap make its click.
if ( event.pointerType !== 'touch' ) {
event.preventDefault();
}
// Focus the button, and send it every move until the release.
$button.focus( { preventScroll: true } );
$button.setPointerCapture( event.pointerId );
// Remember the card and where the press started.
press = {
$card: $button.closest( 'li' ),
x: event.clientX,
y: event.clientY,
dragging: false,
};
} );The press turns into a drag once the pointer moves 5 pixels. Before that, it’s still a click and opens the menu. dnd-kit uses 5 pixels in one of its rules for starting a drag too.
Our pointermove listener keeps the pointer’s last position in pointer.
Once it’s past the 5 pixels, it gets the column and the position from targetAt() and keeps them in target.
Then it draws the line there with showTarget().
drag.js
// drag.js
let pointer = null;
let target = null;
document.addEventListener( 'pointermove', ( event ) => {
if ( ! press ) {
return;
}
// Keep the pointer's last position.
pointer = { x: event.clientX, y: event.clientY };
// Under 5 pixels, the press is still a click.
const distance = Math.hypot( pointer.x - press.x, pointer.y - press.y );
if ( ! press.dragging && distance < 5 ) {
return;
}
// Past that, it's a drag. Keep the target and draw the line there.
press.dragging = true;
target = targetAt( pointer );
showTarget( target );
} );At the start of the drag, we close the menu and dim the card.
targetAt() finds the column by comparing the pointer to the columns’ boxes on screen.
For the position, it calls indexAt() on that column’s list to count the other cards whose middle is above the pointer.
drag.js
// drag.js
function indexAt( $list, y ) {
// The column's other cards, without the one being dragged.
const $others = [ ...$list.children ].filter( ( $card ) => {
return $card !== press.$card;
} );
// Count the ones whose middle is above the pointer.
return $others.filter( ( $card ) => {
const box = $card.getBoundingClientRect();
return box.top + box.height / 2 < y;
} ).length;
}Ending a drag
You end a drag by letting go, but it can also end without a move, on Escape or if the browser takes the pointer back.
However it ends, the browser may fire a click on the button right after you let go.
That click would open the menu.
While a swallowClick flag is on, we swallow the next click with a detail above 0, and we turn the flag off at the next press.
A click from Enter on the keyboard has a detail of 0 and still goes through.
dnd-kit swallows a drop’s click, like this board does.
drag.js
// drag.js
let swallowClick = false;
// A new press starts with clicks allowed again.
document.addEventListener( 'pointerdown', () => {
swallowClick = false;
}, true );
// Drop the click that follows a drag before it opens the menu.
// A keyboard Enter has a detail of 0 and still goes through.
document.addEventListener( 'click', ( event ) => {
if ( swallowClick && event.detail > 0 ) {
event.preventDefault();
event.stopPropagation();
swallowClick = false;
}
}, true );endDrag() removes the line and the preview, clears press and target, and turns swallowClick on if the press had become a drag.
A cancel doesn’t have to put anything back. The card never left its place. Under WCAG’s Pointer Cancellation rule, a drag that completes on the release needs an abort or an undo. On this board, letting go outside the columns aborts it.
Escape needs its own listener, because the browser itself does nothing to a pointer drag on that key.
A pointercancel or a lost capture before you let go (lostpointercapture) ends a drag too.
Neither one is a drop.
Back in 2017, a SortableJS user reported that drag and drop broke in a new version of Chrome, because the library treated pointercancel as a drop.
Escape, pointercancel, and a lost capture all go through cancelDrag(), like letting go outside the columns.
Because the columns might have scrolled during the drag and left the card out of view, cancelDrag() puts them back where they were with restoreScroll().
drag.js
// drag.js
function cancelDrag() {
// Put the columns' scroll back if the drag scrolled them.
if ( press?.dragging ) {
restoreScroll();
}
endDrag();
}
// The browser took the pointer back, or the capture ended early.
document.addEventListener( 'pointercancel', cancelDrag );
document.addEventListener( 'lostpointercapture', cancelDrag );
// Escape cancels the drag.
document.addEventListener( 'keydown', ( event ) => {
if ( event.key === 'Escape' ) {
cancelDrag();
}
} );On pointerup, we pass the target we saved with the line to move(), the same way the menu does, or call cancelDrag() if there’s no target.
Because we use the saved target instead of where the pointer ended up, the card goes exactly where the line was.
drag.js
// drag.js
document.addEventListener( 'pointerup', () => {
// With no line, the release cancels the drag.
const drop = press?.dragging ? target : null;
if ( ! drop ) {
cancelDrag();
return;
}
// Drop the card where the line was, with the same call the menu makes.
const cardId = press.$card.id;
endDrag();
move( cardId, drop.column, drop.index );
} );In the next board, you can try the drag and the ways to cancel it:
- Drag “Fix login” down and let go with the line under “Search bar”.
- Drag “Dark mode” into Doing and let go anywhere in it.
- Start a drag and press Escape, then drag a card up over the bar at the top and let go over it.
- Pick in the touch-action buttons and drag “Fix login” up by its button with your finger, and again with .
When the column scrolls
Sometimes a column scrolls while your pointer stays still.
One example is autoscroll, where the column scrolls by itself while you hold a card near its edge.
The Pointer Events spec says a pointer that hasn’t moved “never fires a pointermove event”.
So a line that only updates on pointermove stays on the same card and slides away from the pointer with it.
I’d work out the target and the line again from the pointer’s last position whenever something scrolls. Since scroll events don’t bubble, the listener goes on the document, in the capture phase.
drag.js
// drag.js
// When anything scrolls during a drag, put the line under the pointer again.
document.addEventListener( 'scroll', () => {
if ( press?.dragging ) {
target = targetAt( pointer );
showTarget( target );
}
}, { capture: true, passive: true } );dnd-kit works out its drop target again on any scroll. SortableJS does it while its autoscroll runs.
On this board, the column starts scrolling once the pointer is within 48 pixels of a list’s top or bottom edge, or a quarter of the list’s height if that’s smaller. The bottom zone goes on up to 60 pixels below the list. The closer the pointer gets to the edge, the faster the column scrolls, from 0 up to 300 pixels a second at the edge and past it.
Whenever the pointer enters a zone, the speed builds up over 400 milliseconds. Because of the ramp, a drag that starts near an edge doesn’t scroll at full speed right away. At the edge, To do takes about two and a quarter seconds to scroll to the end, enough time to press Escape while it moves.
I picked those numbers for this board. Library defaults vary a lot. SortableJS, for example, scrolls about 417 pixels a second, while Pragmatic drag and drop’s standard setting goes up to 900.
Our autoscroll code just scrolls the column, one frame at a time, and leaves the line to the scroll listener above. On this board, only the columns scroll. Boards taller than the window would need autoscroll near the window’s top and bottom too.
With Scroll listener off, scroll events never reach the board’s listener.
- Drag “Fix login” to the bottom edge of To do and press Escape while the column scrolls, without moving the pointer.
- Turn Scroll listener off, drag “Fix login” back to the edge, hold it still for a second or two, and let go.
Without the listener, the line rode up with the cards. And the drop put “Fix login” where the line was, well above the pointer.
Undo
Undo is just one more call to move(), with the card’s old column and index.
Even inside one column, the old index doesn’t need a correction, since we count positions without the card in its old spot.
We add two more lines to move(), one for the message from earlier and one that saves the move in lastMove for Undo.
board.js
// board.js
let lastMove = null;
function move( cardId, toColumn, toIndex ) {
// Work out the new order, or stop if the card stays where it is.
const result = moveCard( columns, cardId, toColumn, toIndex );
if ( ! result ) {
return;
}
columns = result.columns;
// Move the card's element and put focus back on it.
const $card = document.getElementById( cardId );
const $list = document.getElementById( toColumn );
placeCard( $card, $list, result.move.to.index );
focusCard( $card );
// Write the message, and keep the move for Undo.
announce( result.move );
lastMove = result.move;
}board.js
// board.js
function undo() {
if ( ! lastMove ) {
return;
}
// Send the card back to its old column and index.
const { cardId, from } = lastMove;
move( cardId, from.column, from.index );
// There's one level of Undo, and a second click does nothing.
lastMove = null;
}The row under the columns shows the move’s message next to an button.
Focus never moves to that row by itself. Google’s Material Design 3 says the same about snackbars, its short messages that can carry an action.
The row doesn’t have a timer, and it keeps its message until the next move or an Undo. Material Design 3 says snackbars with actions “shouldn’t auto-dismiss”. WCAG’s Timing Adjustable rule would allow a timer, though, as long as people can put the card back without the row, like with the Move menu.
Nielsen Norman Group recommends more than one level of undo for people who make many moves in a row.
You’d get that by keeping a list of moves instead of just lastMove.
What separates a senior from a junior here
- Before reading a board’s code, an experienced reviewer drags a card one place down inside a column, then makes that move from the Move menu. The question is “If I make this move with the menu instead of dragging, does the card end up in the same place, and where’s my focus?” Either a different order or focus on the page body is enough for them to block the merge.
- Next, they search the diff for every place that changes the order, like a
splice()or aninsertBefore()that doesn’t run throughmove(). Each extra one is a second rule for where a card goes. - They watch the status paragraph’s text in the Elements panel of DevTools for every kind of move, because a sighted reviewer never sees it otherwise.
They check that
move()callsannounce()for each successful move. - They leave the autoscroll speed and the line’s look for a later pull request, along with a second level of Undo. But they don’t merge a Move menu that doesn’t open with a tap.
Want more of these in your Google results?