Extending EditRail

A plugin or a theme can add tools to the EditRail toolbar. The contract has two parts. A PHP filter declares your plugin as a provider. Your JavaScript then registers the tools.

The contract is stable from version 1.0.0. A change that breaks it will be a new major version.

A minimal example

This plugin adds a Note tool. When the author arms it and clicks the canvas, it inserts a paragraph that starts with “Note: “. Put both files in one plugin folder.

my-rail-tool.php:

<?php
/**
 * Plugin Name: My Rail Tool
 */

defined( 'ABSPATH' ) || exit;

add_action( 'enqueue_block_editor_assets', function () {
	wp_register_script(
		'my-rail-tool',
		plugins_url( 'my-rail-tool.js', __FILE__ ),
		array( 'toolrail-editor-rail', 'wp-blocks' ),
		'1.0.0',
		true
	);
} );

add_filter( 'toolrail_tool_providers', function ( $providers ) {
	$providers[] = array(
		'slug'          => 'my-rail-tool',
		'script_handle' => 'my-rail-tool',
	);
	return $providers;
} );

my-rail-tool.js:

( function () {
	if ( ! window.toolrail ) {
		return;
	}

	window.toolrail.registerTool( {
		id: 'my-rail-tool/note',
		label: 'Note',
		icon: '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" focusable="false"><rect x="4" y="4" width="16" height="16" rx="2" fill="currentColor"/></svg>',
		createBlock: function () {
			return wp.blocks.createBlock( 'core/paragraph', { content: 'Note: ' } );
		}
	} );
} )();

If EditRail is not active, the toolrail-editor-rail handle does not exist. WordPress then does not load your script, because a dependency is missing. You do not need a check in PHP.

Declare a provider in PHP

Add an entry to the toolrail_tool_providers filter. Each entry is an array with these keys:

  • slug (required): a string that is unchanged by sanitize_key(). Use lowercase letters, digits, dashes and underscores.
  • script_handle (required): the handle of a script that you register.
  • style_handle (optional): the handle of a stylesheet that you register.

EditRail drops an entry with a missing or changed slug, or with no script handle. It does not repair it. If two entries have the same slug, EditRail keeps the first. If the filter returns something that is not an array, EditRail uses no providers.

Register your script on enqueue_block_editor_assets at the default priority, with toolrail-editor-rail as a dependency. EditRail registers its own handle at priority 1. At priority 20 it enqueues the toolbar and each provider’s script and stylesheet. It enqueues a handle only if that handle is registered. All of this happens on the post editor screen only.

EditRail passes the slugs of the valid providers to the page in toolrailData.providers. toolrailData.version holds the EditRail version.

Register tools in JavaScript

Call window.toolrail.registerTool( descriptor ) when your script runs. It returns true when it registers the tool, and false when it refuses it. A refusal also writes a warning to the browser console. Each registration fires the toolrail:tools-updated event on window.

The descriptor has these properties:

  • id (required): a unique string. Use only A-Z, a-z, 0-9, _, :, ., / and -. EditRail refuses a duplicate id.
  • label: the accessible name of the tool. If it is empty, EditRail uses the id.
  • icon: inline SVG markup, as a string. Optional.
  • parent: put the tool in the flyout of an existing tool. Optional. See below.
  • insertBlock: a block name. The tool arms, and the next canvas click inserts this block.
  • createBlock: a function that returns a block or an array of blocks. The tool arms, and the next canvas click inserts what the function returns.
  • onActivate: a function that runs at once, with no canvas click.
  • isActive: a function that returns true when the tool shows as pressed. Optional.
  • supports: an object. supports.canvas is true when the tool needs a canvas click. Optional.

A tool must have one of insertBlock, createBlock or onActivate. A tool with insertBlock or createBlock uses supports.canvas: true by default. A tool with onActivate uses false by default. While a mode takes the canvas, such as the Section overview, EditRail dims each tool that needs the canvas. The tool stays in the keyboard order.

An armed tool inserts its block on a canvas click and on Ctrl+Enter. An author can also drag a top-level tool into the canvas.

Nest a tool in a flyout

parent accepts one of these values:

  • A slot id, such as pin:core/paragraph.
  • A block name, such as core/paragraph. This matches the pinned tool for that block.
  • One of the aliases text (core/paragraph), heading (core/heading), image (core/image) or section (core/group).

If the author has not pinned the parent, the tool shows at the top level of the toolbar. In a flyout, a tool that has isActive is a menu item with a checkbox for screen readers.

Read the state of the toolbar

  • window.toolrail.getMode() returns 'edit', or 'overview' while the Section overview is open.
  • The toolrail:mode-changed event fires on window when the mode changes. event.detail.mode holds the new mode.
  • window.toolrail.getDock() returns 'left', 'right', 'top', 'bottom' or 'float'. window.toolrail.setDock( dock ) moves the toolbar.
  • The toolrail:position-changed event fires on window when the toolbar docks or floats. event.detail holds dock, x and y.
  • The toolrail:tools-updated event fires on window when the registered tools or the pins change.
  • window.toolrail.getActiveTool() returns the id of the armed tool, or 'select'. window.toolrail.setActiveTool( id ) arms a tool.
  • window.toolrail.getCanvasGeometry() returns { frameRect, scale, pan, scrollX, scrollY, mode }. Use it to draw an overlay in the parent document that lines up with the canvas. A canvas point x is at frameRect.left + ( x - scrollX ) * scale in the parent viewport. The same rule applies to y.
  • window.toolrail.refresh() repaints the pressed state of each tool. Call it when your isActive() result changes for a reason that the editor’s data stores do not see. The toolbar repaints on each store change, so you do not need it for state in a store.

Store per-user state

window.toolrail.prefs stores strings in the same per-user account store that EditRail uses. Your state follows the author to other browsers and devices on the site.

window.toolrail.prefs.ready.then( function () {
	var snap = window.toolrail.prefs.get( 'toolrail-ext:my-rail-tool:snap' ); // A string, or null.
	window.toolrail.prefs.set( 'toolrail-ext:my-rail-tool:snap', '1' );
} );
  • Keys must start with toolrail-ext:. Put your own prefix after it.
  • Values must be strings. JSON-encode structured data. set() returns false for a key or value it refuses.
  • get() returns null for a key that was never written.
  • Before prefs.ready resolves, get() can return null for a key the author has. Read again after it resolves, or listen for the toolrail:prefs-ready event on window. prefs.isReady() tells you if it has resolved.

When EditRail is deleted, it removes these keys with its own preferences.

Pins and saved sets

  • Pins: pinBlock( name ), unpinBlock( name ), isPinned( name ), moveSlot( name, delta ).
  • The author’s name, description and icon for a pin: getPinMeta( slot ) and setPinMeta( slot, { title, description, icon } ). Text only. The icon is a Dashicon name, such as dashicons-star-filled, or up to 3 characters. The limits are 80 characters for the title and 240 for the description.
  • Saved sets: saveConfig( name ), loadConfig( name ), deleteConfig( name ), getConfigs(), exportConfig( name ), importConfig( parsed ).

Your own data on a pin

setPinData( slot, namespace, value ) stores your data on a pinned tool. getPinData( slot, namespace ) reads it.

  • The namespace starts with a lowercase letter or a digit, then has lowercase letters, digits and hyphens. It is 40 characters or fewer.
  • The value is plain JSON, up to 2,048 characters when serialized. null removes it.
  • setPinData() returns false if the slot is not pinned or the namespace is not valid.
  • EditRail removes the data when the author unpins the tool. Saved sets and set files carry it. Loading a set applies it one namespace at a time.
  • Each change to a pin’s entry fires toolrail:pin-meta-changed on window, with { slot } in event.detail.

EditRail stores the data and does nothing else with it. To use it, register a tool under the pin with parent: 'pin:<slot>', and read the data in its createBlock.

Set file format

{
  "format": "toolrail-set",
  "version": 1,
  "name": "kit",
  "blocks": [ "core/paragraph", "core/quote", "pattern:user:123" ],
  "meta": {
    "core/quote": { "title": "Testimonial", "icon": "dashicons-format-quote" }
  }
}
  • blocks lists slot ids. A block type is its block name. A pattern is pattern:<name>, or pattern:user:<post id> for one of the author’s own patterns.
  • meta is optional. It holds the author’s name, description and icon for blocks in the set, keyed by slot id. The import ignores entries for blocks that the set does not list.
  • The import refuses a file that has no blocks array.