Be API WordPress agency | News | WordPress | Interactivity on WordPress: a new API for block editor

Interactivity on WordPress: a new API for block editor

Published on

by

During the last WordCamp Europe, we plunged into the behind the scenes of the WordPress block editor to explore a new development: the API of interactivity. This new brick aims to improve a still too little considered aspect of the blocks: their behaviour on the front side, i.e. how they show themselves visually for the end user.

Interactivity, in this context, refers to the ability of a block to respond immediately to a user action. Think of an accordion block that opens, a submenu that pops up or a change in the quantities of a basket on an e-commerce site.

These interactions were previously left to the discretion of each developer, leading to several technical challenges that we will come back to later in this article. But before that, let's start by reminding of the interest for the CMS open source WordPress to focus on creating new APIs.

The essential role of APIs in WordPress

WordPress offers a wide range of dApplication Programming Interfaces, better known under the English acronym API.

Their interest? Standardize many aspects of the code that developers of extension and WordPress themes might have to write. Instead of starting from zero each time, they benefit from a range of predefined resources, such as functions or classes.

Key benefits include:

  • Simplicity and Clarity : The required codes are not only standardized, but also well documented, making them accessible to all developers using WordPress.
  • Security and Performance : These two aspects are managed by default by APIs, which benefit in addition to the expert look of the community that participates in the development of the core of WordPress.
  • Flexibility : APIs can be adjusted and enriched over time, offering increasing possibilities, fixes and improvements, without forcing developers to constantly review their code.

WordPress APIs are not only tools to facilitate developers' lives. They embody WordPress's vision for a more efficient, secure and evolving web development.

Strengthening interactivity

WordPress block editor already offers a wide range of tools allowing a rich edition of backoffice content. But until recently, developers wishing to offer complex and/or interactive renderings on the front part had to design their own solution, often without clear guidelines or established good practices. This heterogeneity of solutions could affect page performance, accessibility and security.

Introduction of site editor, or « Full Site Editing » (FSE), highlighted this problem, with its construction from blocks. In response to this, a group of developers undertook to design a solution: their reflection gave rise to a detailed article, presenting this new API, and demonstration site. Its deployment presents challenges, since it must be functional on the server side when rendering the page and on the browser side where the user will interact with the blocks.

For this API, developers have established key criteria such as:

  • A smooth integration with the current block logic, accessible on the server side in PHP,
  • Compatibility with WordPress core and existing extensions, including all hooks to manipulate HTML rendering,
  • An optional implementation for the maintenance or creation of blocks, with progressive adoption as needed,
  • A minimal influence on web page performance.

Other conditions specifically target extension developers.

This new API presents the potential to transform the dynamics of blocks in the face of user interactions. It allows developers to focus on their business objectives, while simplifying the implementation of the technical foundations necessary for these ambitions.

For end users

Although initially designed to optimize the daily lives of developers, this new API has tangible benefits for all, with at the top of the list a significant improvement in performance and security consolidation.

As mentioned above, the benefits of APIs are wide.

Regarding the interactivity API, its main assets for end users are distinguished by:

  • Faster and smoother navigation: With less resources to load and maximum optimisation, users benefit from reduced loading time and better responsiveness, guaranteeing an optimized experience.
  • Quality of code: The programmatic platform is reviewed and approved by a community of developers concerned with its performance, security and evolving capacity. A quality code translates into fewer bugs, failures and interruptions – all contributing to a more fluid and secure navigation.
  • Interoperability: This innovation ensures a harmony between different elements of a page, allowing more intelligent and intuitive interactions. Whether it is a weather widget that adapts to your location or an e-commerce integration that suggests products based on your browsing, this interoperability greatly enriches the user experience.

For developers

This new API is not yet stabilized, examples of codes are given as an example and will most likely be modified in the future.

One of the strengths of this new development API is to be reactive. It contains the elements that make the strength of React philosophy: "interfaces" derived from a specific state. The developer describes how the interface should be displayed and how its state should be changed, and the underlying library is responsible for detecting events, updating the state and mutating the interface accordingly. This is the whole philosophy of block editors.

Conversely, to add interactivity to elements of a site, it was often a question of jQuery (or native JavaScript). With this approach, the developer is responsible for managing interface rendering, event detection, state update and interface modification. The more elements to be updated, the more this method reveals its weaknesses.

Another crucial requirement for this API was its compatibility with server-side rendering. The HTML produced by the server must form the basis of the client side, on which an interactive dimension is superimposed. This HTML should not be completely replaced. From a performance point of view and SEO, this guarantees instant display of tangible content, avoiding an effect « blank page » while downloading and running JavaScript necessary for rendering. This also ensures that any changes to the server-side HTML are retained, such as the possible addition of CSS classes.

For component « reactive », the team opted for the library Preact, which, while more compact, borrows widely from the concepts of React. It is this layer that orchestrates the updating of interfaces according to user interactions.

The real innovation lies in the method of integrating interactive elements, carried out through HTML directives. This principle is inspired by what is done by the bookshop. AlpineJs.

Through this system, one can easily enrich an HTML code to enable it to trigger actions or react to changes (of « effects »).

<div
data-wp-context='{ "isOpen": false }'
data-wp-effect="effects.logIsOpen"
>
<button
data-wp-on--click="actions.toggle"
data-wp-bind--aria-expanded="context.isOpen"
aria-controls="p-1"
>
Toggle
</button>

<p id="p-1" data-wp-show="context.isOpen">
This element is now visible!
</p>
</div>

These guidelines will link HTML elements with the reactive part in JavaScript

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

store({
actions: {
toggle: ({ context }) => {
context.isOpen = !context.isOpen;
},
},
effects: {
logIsOpen: ({ context }) => {
// Log the value of `isOpen` each time it changes.
console.log(`Is open: ${context.isOpen}`);
},
},
});

In the example above (from the presentation article of the interactivated API published on the Make Core block), we have a « block » fictitious that works like an accordion.

To summarize the operation, when the user clicks on the button element, it changes the status value isOpen. When this value changes, it will have the effect (where the name « effect » used in English) to display or hide the paragraph element.

All this operation is carried by the directives visible in HTML as data-wp-on--click, data-wp-show and who bridge with the JavaScript code.

The article on Core is very well done and presents more complete mechanism and guidelines in parallel with React.

Conclusion

Thus, the Gutenberg publisher continues to evolve and improve. This new API is a very interesting proposal to facilitate the development of interactive experiences via blocks. Developers who contributed to its creation have pushed the reflection to propose a solution integrating perfectly into the existing WordPress ecosystem, remaining as light as possible.

Developers working on the Gutenberg or WooCommerce project have already begun to evolve their blocks to take advantage of the new possibilities that this API offers. There is a strong bet that it will continue to evolve – but it is interesting to see that it is already exploited.

If you want to follow developments, a changelog is available to monitor the evolution of the API and it has its own category in the discussion section of the Gutenberg project.