Merge Announcement: Interactivity API

View the kickoff post, the status update post, and the Trac ticket for the Interactivity APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways..

Purpose & Goals

Currently, pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party authors implement their chosen JavaScriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. frameworks (or vanilla JSJS JavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors.) to enhance user experiences on WordPress sites. There is no consistency or standardized pattern for developing frontend JavaScript in WordPress.

The Interactivity API provides a standard way for developers to add interactions into the frontend of their blocks.

The API has been designed and created with these requirements:

  • BlockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience.-first and PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher-first. Prioritizing blocks for building sites and server side rendering for better SEO and performance. Combining the best for user and developer experience.
  • Backward compatible. Ensuring compatibility with both classic and block themes and optionally with other JavaScript frameworks, though it’s advised to use the API as the primary method. It also works with hooksHooks In WordPress theme and development, hooks are functions that can be applied to an action or a Filter in WordPress. Actions are functions performed when a certain event occurs in WordPress. Filters allow you to modify certain functions. Arguments used to hook both filters and actions look the same. and internationalization.
  • Declarative and reactive. Utilizing declarative code to define interactions, listening for changes in data, and updating only relevant parts of the DOM accordingly.
  • Performant: Optimizing runtime performance to deliver a fast and lightweight user experience.
  • Send less JavaScript. Reduce the overall amount of JS being sent on the page by providing a common framework that blocks can reuse.  So the more that blocks leverage the Interactivity API, the less JS will be sent overall.

A live demo of what can be achieved was announced in the State of the WordState of the Word This is the annual report given by Matt Mullenweg, founder of WordPress at WordCamp US. It looks at what we’ve done, what we’re doing, and the future of WordPress. https://wordpress.tv/tag/state-of-the-word/..

Live site demo

In case you want to read more about the goals, you can refer to the initial proposal.

Project Background

The project started as an experimental plugin in early 2022. Then, the first API version debuted in Gutenberg 16.2 and has been continually refined until Gutenberg 17.7.

In WordPress 6.4,the Image, Search, File, Navigation, and Query coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. blocks were refactored using the private version of the Interactivity API, addressing accessibilityAccessibility Accessibility (commonly shortened to a11y) refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e. unassisted) and “indirect access” meaning compatibility with a person’s assistive technology (for example, computer screen readers). (https://en.wikipedia.org/wiki/Accessibility) issues and adding the long-time expected lightbox (or “expand on click”) feature for images.

The development has been done in GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/, using a Tracking Issue to monitor progress and a Discussions category to solicit feedback and offer guidance to developers who assisted in testing.

Implementation Details

The Interactivity API is a standard system of directives, based on declarative code, for adding frontend interactivity to blocks.

Directives are special HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. attributes that tell the Interactivity API to attach a specified interaction to a DOM element or to transform it, similar to HTMX or AlpineJS. Using HTML as the templating language enables the API to understand the directives both in the server (PHP) and in the client (JS).

As part of this project, and all the interactivity scripts are now implemented leveraging the new script modules which are also shipping in WordPress 6.5. All of them will only be loaded on the frontend if at least one interactive block is present, to avoid sending unnecessary JavaScript to the frontend.

Here is an example of an interactive block, with a JavaScript file in charge of increasing or decreasing a counter, and a PHP file in charge of counter initialization and rendering.

// JS File - viewScriptModule.js

import { store } from "@wordpress/interactivity";

const { state } = store("my-counter-block", {
 actions: {
   increaseCounter: () => {
     state.counter = state.counter + 1;
   },
   decreaseCounter: () => {
     state.counter = state.counter - 1;
   },
 },
});
// PHP File - render.php
wp_interactivity_state('my-counter-block', array(
   'counter' => 0,
))
?>

<div
   <?php echo get_block_wrapper_attributes(); ?>
   data-wp-interactive="create-block"
>
   <button data-wp-on--click="actions.increaseCounter">
       <?php esc_html_e( 'Increase', 'my-first-interactive-block' ); ?>
   </button>
   <p data-wp-text="state.counter"></p>
   <button data-wp-on--click="actions.decreaseCounter">
       <?php esc_html_e( 'Decrease', 'my-first-interactive-block' ); ?>
   </button>
</div>

This would result in a block like this one:

For developers looking to get started, there is a Getting Started guide available, with plans to transition it to a handbook in the near future.

Additionally, a detailed dev notedev note Each important change in WordPress Core is documented in a developers note, (usually called dev note). Good dev notes generally include a description of the change, the decision that led to this change, and a description of how developers are supposed to work with that change. Dev notes are published on Make/Core blog during the beta phase of WordPress release cycle. Publishing dev notes is particularly important when plugin/theme authors and WordPress developers need to be aware of those changes.In general, all dev notes are compiled into a Field Guide at the beginning of the release candidate phase. will be released, providing further insights into utilizing the API and understanding its internal workings.

Modules and Import maps.

The Interactivity API brings along the support of Modules and Import Maps.

JavaScript modules have transformed the way developers write and organize JavaScript code. They provide a cleaner and more modular architecture, making code easier to maintain, test and reuse across projects.

With the addition of native support for registering and enqueueing JavaScript modules, WordPress can keep pace with web development by using efficient, effective and battle-tested methods to handle JavaScript libraries and their dependencies.

There will be another dev note about JavaScript Modules and a guide to use them.

Guide to Javascript Modules.

Contributions and Feedback.

The Interactivity API is intended to be a long-term project with future enhancements; feedback is highly welcome. The best way to reach out is via GitHub Discussions.

Code and documentation contributions are also welcomed, and the Gutenberg repository is the place to go.

Some examples of contributing could be:

  • Test the Interactivity API, create your own interactions, and share feedback about what you like and you don’t.
  • Suggest new features to include in the API.
  • Help creating tutorials or share demos that can inspire other people.

Spread the word

The more developers who use Interactivity API in their projects, the more consistency there will be in the WordPress ecosystem, and the less JavaScript will be sent to the world!

Feel free to spread the word about the Interactivity API in social media and events with your colleagues, friends, and everyone!

Props to @cbringmann, @gziolo, @swissspidy, @westonruter, @santosguillamot, @luisherranz, and @rmartinezduque for peer review.

#6-5, #feature-plugins, #feature-projects, #interactivity-api, #merge-proposals