Block Editor Keyboard Shortcuts in WordPress 5.4

WordPress 5.4 introduces a new package called @wordpress/keyboard-shortcuts to centralize the registration/removal and documentation of the available keyboard shortcuts in the block editor screen.

Registering shortcuts

You should register keyboard shortcuts when you load the screen/plugin for the first time, by calling the registerShortcut action.

wp.data.dispatch( 'core/keyboard-shortcuts' ).registerShortcut( {
	// Shortcut name (identifier)
	name: 'plugin/shortcut-name',

 	// Catergory (global, block or selection)
	category: 'block',

	// Description 
	description: 'Short description of your shortcut.',

	// The key combination used to trigger the shortcut
	// Could be just a single character or a character with
	// a modifier.
	keyCombination: {
		modifier: 'primaryAlt',
		character: 't',
	},

	// Some shortcuts can be triggered using several 
	// key combination, the aliases array is used to define
	// the alternative combinations
	aliases: [
		{
			modifier: 'primary',
			character: 'i',
		},
	],
} );

Registering a shortcut automatically adds it to the keyboard shortcuts help modal, where users can find it.

Implementing the keyboard shortcut behavior

The @wordpress/keyboard-shortcuts package also provides the useShortcut React hook to define the behavior triggered by the keyboard shortcuts.

import { useShortcut } from '@wordpress/keyboard-shortcuts';
import { useCallback } from '@wordpress/element';

const MyComponent = () => {
	useShortcut(
		// Shortcut name
		'plugin/shortcut-name',

		// Shortcut callback
		useCallback(
			( event ) => {
				// Do something when the keyboard 
				// shortcut is triggered
			},
			[]
		)
	);
}

Using this React hook instead of a custom implementation comes with a few advantages:

  • If the shortcut is unregistered by a third-party plugin, the callback is just ignored.
  • The shortcut key combination can be modified at runtime and the callback will still be called properly.

Removing existing shortcuts

Registered shortcuts can also be unregistered (and potentially replaced) by third-party plugins

wp.data.dispatch( 'core/keyboard-shortcuts' ).unregisterShortcut(
	'plugin/shortcut-name'
);

Next steps

In the next releases, this package will also let you offer a centralized UI to modify the keyboard shortcuts per user.

#5-4, #accessibility, #block-editor, #dev-notes