Gutenberg Development with Examples: Google Maps (part 3)

Published in WordPress.

Welcome to the third and last post on how to create a maps plugin for Gutenberg. Our last post was quite dense and we saw a lot of different things: the attributes our block has, how to insert a map using a React component, how to use WordPress components or even create our own components to define the user interface, etc. Today we’ll be discussing something simpler.

In this post we’ll see how to render the Google Maps map in the front-end. To do this, we will take a closer look at save.js and we will make a few changes to the plugin so that everything works as expected. I will also use this last post to comment on any point that may have been unclear until now.

How to Save Our Map Block to Display It in the Front-End

To display the map in the front-end we first have to define the HTML we want to be rendered in the front-end. In a Gutenberg block, this is achieved by defining the save method of the registerBlockType function. As I already mentioned in the previous post, this method is defined in the file save.js in packages/blocks/nelio-maps/.

Again, this is an extremely simple function to understand:

  • From line 7 to 25 we extract all the attributes that are relevant to our block. That is, all the attributes that we defined in attributes.js and that tweak the appearance of our map.
  • In line 41 we open the div that will serve as a container for the block.
  • In line 47 we find a div that will wrap the map itself. Look at something very interesting: this div includes all the attributes object in its definition. This means that all the properties in attributes (for example, 'data-lat': lat of line 34) will be rendered as HTML attributes (for instance, assuming that the variable lat is 2.48171, lat will appear in the final HTML as data-lat="2.48171").
  • On line 49, a small div is added containing the coordinates of the marker.
  • On line 59, the contents of the RichText that we had defined in edit.js.

So, in essence, the method save generates an HTML that contains all the attributes that are relevant to render a map in the front-end. So, what could go wrong? Well, if you were to open the front-end now, all you’d see would be this:

Screenshot where a map should look and not seen
Screen capture where a map should be seen. Oh wait… What’s going on?

An empty block that only has some RichText content. What happened?

How to Modify the Plugin to Render a Google Map Created with our Gutenberg Block

To display a Google Map in the front-end it is necessary that we load the Google Maps library and a script that uses it to build the map itself. This is extremely simple and if you have ever developed for WordPress, you should know how to do it.

The first thing we should do is create a script that can build a Google Map using the data we have put in the HTML. This script is in assets/src/js/public/public.js. Take a closer look to understand how it works:

  • In line 9 we search all the nodes that contain a map (filtering by one of the classes that we have included in the save method) and, for each of them, we call the initGoogleMap method.
  • This method relies on two functions to do its job. On the one hand, it extracts the coordinates of a possible marker with the function extractMarkerPositionIfAny of line 55 and, on the other, it extracts all the properties of the map (center coordinates, zoom level, list of visible buttons, etc) with the function extractMapOptions from line 26. Note that both functions are simply dedicated to reading the values of the attributes data-something we had put into the save method.
  • Finally, we created a map (line 18) and added a marker (line 21) using the Map and Marker classes, respectively, provided by the Google Maps library.

Now that we have this script, we only need two additional tweaks in our project:

Once all these changes have been made, this is the final result:

Google map with the Nelio Maps plugin in the front-end
Screenshot of a Google map with the Nelio Maps plugin in the front-end.

I know what you’re thinking: why, instead of doing all this by hand, didn’t we use the React component we had used in edit.js? Wouldn’t this save some time?

Indeed, using the React component we saw in the previous post would have saved us some trouble… but there’s a catch: it relies on React, which means we would have had to load React in the front-end to use too. And that seems like too much, don’t you think?

Pending Details

Finally, let me briefly discuss one aspect that’s very important, or else your plugin won’t work: the Google Maps API Key.

The Google Maps API Key

In order to use Google Maps you need to have an API key. How to get it is something Antonio explained to us a few days ago. Now, how do we use it?

One option would be to hardcode our API key in the plugin. If you’re the only one who’ll be using the plugin, that would do the trick. But if you plan on distributing your plugin to real users, it’s a very bad idea, because not all Google services are free—some are paid, and the costs can be quite expensive if everybody uses your key.

What to do in these cases? The idea is very simple: just add a configuration option in the plugin for people to enter their own API key.

In our case, if you add a map without API key, you will see the following warning message:

Warning message when there is no API key available
Warning message that is displayed to the user when there is no API key available.

urging you to add the API key.

Usually, you’d create a special page to manage your plugin’s settings. But for a plugin as easy and simple as the one we’re creating, I thought it be easier if we opted for a different solution.

In WordPress there is an options screen in /wp-admin/options.php that looks like this:

Option to enter the API key
How to add the API key from the WordPress settings.

It is a kind of “nice interface” to edit (almost) all the options that have been registered in WordPress and are in the table wp_options. So, all our plugin has to do is make sure that this option always exists in the database (even when there’s no API key set yet) and we will have a “nice interface” for the user to paste their API key without our doing anything!

To achieve this, use the init hook (see line 73 of this commit) with a function (line 134) that always sets a value to your key option. If the option does not exist yet, this function will set its value to the default value (an empty string) and save the option. If it already existed, the new value will be the same we already had, and so the update function won’t do anything. A clever and efective hack!

In Summary

In this post we have overcome the last barrier in our project: how to save the map and how to display it in the front-end. Basically, all we needed was a div with all the relevant information about the map (its center, options for displaying the buttons, the marker, etc.) and a small script to rebuild it in the front-end.

I hope that this tutorial has pleased you and serves as an example to undertake your own projects. As you can see, if you start a new project with a good foundation like the one we have created in Nelio with the boilerplate for Gutenberg development, materializing your ideas into real projects will be way easier.

If you have any questions, let us know in the comments section below. Good luck!

Featured image by Artem Bali on Unsplash.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...

Gutenberg Development with Examples: Google Maps (part 2)

Published in WordPress.

Hi there! We’re back with our tutorial to develop in Gutenberg. Last week we started a project that added a map block in WordPress. In that first post we defined what the requirements that our plugin has to meet were and we prepared the skeleton of what will end up being the final product, starting with the fantastic plugin boilerplate that we have created at Nelio.

Today comes the second part of the tutorial on how to create the map block. In this post we will see how to add a Google Maps map inside the WordPress editor and how to implement a user interface that allows us to manipulate its behavior.

A Quick Look at the Current Status of the Project…

In the current state of the project we have a simple Demoblock defined in packages/blocks/demo/. This small block is the one that comes as an example in Nelio’s plugin boilerplate and looks like this:

Demo block that our boilerplate includes by default in the block editor.
Demo block that our boilerplate includes by default in the block editor.

Obviously, this isn’t what we want. We’re not interested in a heart icon followed by some text, but in something like this:

Nelio Maps screenshot
Screenshot of the map block included in Nelio Maps.

That is, we want a Google Map block with an optional marker in it. How can we move from the original example block that our boilerplate had to this other, more powerful block? Well that’s what we’re going to answer today!

But before that, let me invest a couple of minutes explaining what we have right now and how we’re going to move forward. I think that, if you understand the current state of the project, you’ll have an easier time following what will come next.

Understanding the Demo block…

As I’ve already said, the demo block is defined in packages/blocks/demo/. In this folder you’ll find the styles of the block, its icon, and several files with the code that implements its operation. Let’s see the most important files.

On the one hand, there’s the main file: index.js. This file exports three variables: the name of the block (name), the definition of the block (settings), and the styles that the block supports (styles). These three variables are those used in packages/blocks/index.js to register the block in Gutenberg (with registerBlockType) and thus make it available to final users.

This main file, then, serves as an entry point to understand the block we are creating. In the object settings (settings), we see three important properties: attributes, edit, and save. Each of these properties has its own JavaScript file (for the sake of simplicity and ease of understanding), each named after their corresponding property. Let’s take a quick look at all of them:

  • The attributes.js file defines all those properties of our block that are dynamic and, therefore, should be tweakable by our users. In the case of our Demo block, the only attribute that exists is the text the user has written, but the map block will have many more options: the coordinates of the center of the map, the default zoom level the map should use, what buttons (if any) should be visible to interact with the map, etc.
  • The file edit.js is the one that defines how the block is displayed in the WordPress editor and what settings are offered to the user (both in the toolbar and in the sidebar of the block’s settings). In Demo, the edit simply includes the RichText component of WordPress to write the content. As we will see, the map block will be more complex and will also include additional settings.
  • Finally, save.js defines the method that will convert the block we were editing in Gutenberg into the HTML that must be rendered in the front-end. Again, in Demo we see that this function simply saves the contents of a RichText using RichText.Content, but it could be anything else (as we will see next week in the third and last part of this tutorial).

Creation of the Map Block Based on the Demo Block Included in the Plugin Boilerplate

Once we understand exactly how the Demo block works, it’s time to ask ourselves: how do we create ours? Well, very easy: as Toni told us a few days ago, we simply have to duplicate the directory packages/blocks/demo/ into packages/blocks/nelio-maps/ and start to modify everything necessary. I know, it’s easier said than done.

Let’s start with something easy: attributes.js. This file contains all the properties that should be modifiable by our final users. In the previous post we specified what requirements our plugin should meet and, therefore, we outlined what things should be tweakable. Well, taking a look at the resulting attributes.js you’ll clearly see what can be tweaked from our map block: zoom level, map center, visibility of different buttons… Super simple stuff!

The next point to modify is all that concerns the edition of the block in Gutenberg. To do this, we must dive into edit.js. If you look closely, you will see that it is not much more complicated than what we had in our original Demo block.

The most important thing is in the block’s render method (line 33), where we retrieve the attributes we just defined from an object named this.props. We’ll use this properties to render the block and its setings, of course. This is what we have:

  1. A toolbar ToolbarControls (line 66), which we defined in an external file named toolbar.js (don’t worry, we’ll see its content in a minute).
  2. The block settings that appear in the editor’s sidebar (line 68), which we find in a component called Inspector that we defined in inspector.js.
  3. The content of the block itself, which has two states:
    • If I do not have a Google Maps API key available, we show a user notice (line 122).
    • If we have this key, we show the map using MapBlock (line 83). The map might include a Marker (line 97), which is only visible when the option is activated, and might also be accompanied of a div (line 104) with additional information about it.

Google Maps as a React Component

If we want to put a Google map in our editor, we must use a component that allows us to use the Maps API of Google Maps. Considering that Gutenberg is built on top of React, the logical thing to do is to find out if there’s a React component of Google Maps. And, sure thing, there’s one!

As you can read in the project’s documentation, first we have to add the component into our project. Just install and add the dependency running the following command:

npm install react-google-maps --save-dev

which adds a new entry in our package.json and downloads the package into node_modules.

How to Create a WordPress Component that Encapsulates a React Component

If we continue looking at the documentation of this React project for Google Maps, we will see that they recommend us to wrap their GoogleMap component with our own component. Once it’s encapsulated, we will have to use our component in our plugin.

Well, let’s follow their lead and create a component called MapBlock in its own file map-block.js. And that’s it! We now have a map component ready that we can use in our Gutenberg block.

How to Add Block Settings in WordPress Editor’s Inspector

The next step is to configure how this map should look in the editor and add a few settings to tweak its appearance. To do this, we must add several settings sections in the Gutenberg sidebar. As I have already advanced, we achieve this with a component that we have called Inspector and that we have defined in the file inspector.js.

If you take a look at this file, you will see that it follows the same pattern as always: we are defining a Component with a render method. This method pulls the relevant attributes in this.props and returns the JSX with all the controls. In this particular case, it returns an instance of InspectorControls (this tells WordPress that this content goes to the sidebar) with several PanelBody sections. Let’s see each section in detail.

Basic Map Settings

The first PanelBody we found (line 47) has no title and, therefore, always appears as a section that can not be closed:

Basic adjustments of Nelio's map
Basic settings of the map block of Nelio Maps. Choose the size and zoom level with these two selectors.

The section defines a pair of RangeControls, whose result you can see in the previous screenshot. These two controls allow us to modify the height of the map and its zoom level.

Another interesting and simple section is the one found on line 121. Here we add a few options to activate or deactivate the buttons that should be shown on the map when displayed in the front-end :

Map buttons
Set which map buttons will be visible in the front-end.

To do this, we simply have to use the default WordPress component CheckboxControl.

How to Add a Custom Style Section for Our Map Block

Another interesting section of our block is the style section (line 68). You can see the final result in the following screenshot:

Google Maps Styles
You can change the appearance of the map using the Styles section in the block configuration.

It’s a special section because the component we use (MapStyles) is not something that exists in WordPress by default, but something we have created for this block in particular. As you can see in the previous link, it is a component that loads a set of predefined styles in a component of type ImagePicker (which, incidentally, does not exist by default in WordPress either—you can find it in packages/components/image-picker/).

When the user selects any of the styles included in ImagePicker, the MapStyles component invokes the onChange function it’s been given (see line 76 of inspector.js) passing two values: the name of the selected style and the associated JSON.

Finally, notice that one of the options that MapStyles includes is a Custom style:

Custom map style in Nelio Maps
In addition to the 5 default styles included in the block, there is the possibility to add your own style of the map using a JSON.

When selected, the component renders an additional text box (line 45) so that the user can enter their own style in JSON format. In case you did not know, the maps of Google Maps can be customized a lot!

How to Add a Marker into Our Map

The next section we have is the one that controls our marker (line 81). This section allows us to show or hide the marker (line 86) and, when active, gives us some additional settings:

How to add a bookmark to the map
The block allows you to add a marker to the map to indicate a specific point of the same.

As you see, a search box appears to search for locations in Google Maps (which we have implemented, again, with a custom component called AddressSearch) and the ability to show or hide the text block in which to put additional information about the marker .

By the way, notice that the AddressSearch component is based on a component called StandaloneSearchBox, which is also part of the React project . What a pleasure it is to reuse the work of others!

How to Configure the Toolbar of a Block

The last thing we have to discuss is the toolbar. If you have understood how the sidebar works, the toolbar is a piece of cake.

Nelio Maps toolbar
The toolbar offers quick access to the most important options on the Nelio Maps map.

The toolbar of our plugin is represented by the ToolbarControls component defined in toolbar.js. Here we simply add a component to define the alignment of the block (BlockAlignmentToolbar, on line 42), a pair of dropdowns to center the map (line 50) and to modify the location of the marker (line 79), and a couple of extra buttons to change the location of the text box in which we can put additional information about the marker (lines 107 and 120).

Search for locations integrated in WordPress
With integrated location search, you can search for any business or address without leaving the block editor.

In Summary

Today we have seen how to create the entire editing interface of our map block. As you can see, it’s a process that might seem complicated at first glance, but becomes pretty natural quickly. In the end, the secret is to start from an example that is well organized (as our plugin boilerplate is) and build the interface step by step, reusing the components that WordPress offers or that already exist, or even creating your own.

See you next week with the last part of this tutorial, where we’ll see how to save our map and how to view it in the front-end.

Featured image by rawpixel on Unsplash.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...

Gutenberg Development with Examples: Google Maps (part 1)

Published in WordPress.

A few days ago we published a new plugin in the WordPress.org plugins directory: Nelio Maps. As the name reveals, it’s a maps plugin that adds a new type of block in the WordPress editor. With it, we can easily add a Google map on our pages or posts. Here’s how it looks:

The Nelio Maps plugin allows you to insert and customize a Google Map to your pages and posts.

Nelio Maps is one of our first plugins entirely designed for Gutenberg. Despite being a relatively simple plugin, it is a very useful product. On the one hand, because any user who wants to add maps to their website can now do so by installing a simple and lightweight plugin. On the other hand, because any developer that wants to develop in Gutenberg now has a real example of how to create a plugin “from scratch”, simply by reading this post.

As I am aware that the development of a plugin like this is not the easiest thing in the world, I have organized this tutorial in three different parts. Today I will explain how to create the plugin “from scratch” so that we end up with the skeleton we’ll use to build the final product. In the second post I will explain how to get an interactive map in the WordPress block editor and we will see all the components that I have created to make the plugin. Finally, in the third and last post we’ll see how to save the map in the database and how we can show it in the frontend.

Defining our Project and the Plugin We Want

It may seem like a truism, but before embarking with any new project, the first thing we must do is define what we want to achieve with said project. Depending on the functionalities we want to include, we will have a different set of requirements. So let’s define what kind of map plugin we want to implement in this tutorial.

These are the requirements of the project:

  1. One should be able to add a map (or more than one) to their pages or posts.
  2. It should be possible to center the map anywhere by
    • either dragging the map with the mouse
    • or looking for the location in a search box.
  3. The size of the map should be adjustable, both in width and height
  4. The map should include different styles (black and white, custom color palettes, etc.)
  5. The user should be able to add a marker in the map.
  6. If there is a marker, the map must be accompanied by a text box with additional information about the marker.

Ambitious, right? Well, let’s get started!

How to Create a Gutenberg Plugin “From Scratch”

If you follow our blog, you’ve probably seen that a few days ago Antonio published a post explaining how to create plugins using a plugin boilerplate that we have created in Nelio. If you have not read his post yet, I recommend you read it first, because our plugin will be based on the plugin boilerplate wp-beb that Antonio explains there.

To start our project, the first thing we will do is mirror Nelio’s boilerplate plugin. First, create a new repository in your GitHub account. Then, follow the steps described in Github’s help pages to mirror our boilerplate:

git clone --bare https://github.com/avillegasn/wp-beb.git
cd wp-beb.git
git push --mirror https://github.com/your-username/your-repo.git

Once your project is ready, follow the instructions found in README.md to compile the project and thus be able to see it in your WordPress site.

How to Transform the Plugin Boilerplate into Your Plugin

As it appears in the plugin boilerplate documentation, the first thing we have to do is change the project’s name in the source code. That is, you have to change all occurrences of wp-beb (both uppercase and lowercase, with hyphens or underscores) by the name of our plugin (in my case, nelio-maps).

For this, we can use the following script:

Just keep in mind you’ll have to replace the string nelio maps int lines 5, 8, 9, and 10 to whatever your plugin’s name will be.

On the other hand, now is also a good time to change the plugin documentation. On the one hand you have to edit the files README.md and readme.txt to reflect the purpose of your new plugin (without forgetting to mention the fact that you are using our boilerplate as a base, of course). On the other, you should change the first comment in the main PHP file, as it’s the data WordPress uses to display the plugin in the Plugins screen.

You can see how I made all these changes in the first commit of the Nelio Maps project.

How to Clean the Plugin Boilerplate of Unnecessary Stuff

Nelio’s boilerplate plugin includes, by default, a couple of components: (a) a demo block and (b) a Gutenberg plugin. Since we are only interested in creating a block (the map), we are going to eliminate everything that is left over (the Gutenberg plugin).

This step is quite simple, since basically it is based on “deleting” unnecessary things from the plugin. Specifically, we should:

  1. Get rid of all the content that appears in the assets folder (which is where the Gutenberg plugin was added, its style, and its icon).
  2. Clean the file webpack.config.js, since there are a couple of rules that used the files in assets we just removed.
  3. Clean the main file of the plugin, since it enqueues a stylesheet and a JavaScript file that no longer exist.

You can see all the changes in this commit. If you compile the code again, you will see that the Demo block still exists, but the Gutenberg plugin that appeared in the upper right corner of the screen doesn’t.

Summary

In today’s post we have seen how to create a plugin for Gutenberg. First, we have defined the type of project we want to create and we have identified its requirements. Next, we have seen the steps needed to adapt the boilerplate plugin from Nelio to a new project. That is, we have seen how to clone Nelio’s boilerplate project and clean it to meet our particular needs.

See you next week with the second part of this tutorial, where we will modify the Demo block so that it performs all the functions we have described at the beginning of this post.

Featured image by Brett Zeck on Unsplash.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...

5 JavaScript Features You Must Know to Develop in Gutenberg

Published in WordPress.

In 2016 Matt Mullenweg told us:

I’m going to give you some homework: learn JavaScript deeply (…) because it’s the future of the web.

Matt Mullenweg (on YouTube)

I don’t know if you followed his advice three years ago, but if you didn’t, you can’t postpone it anymore. The official release of the block editor has forced many developers to get up to speed with JavaScript. The language is becoming more and more relevant within WordPress and, if we do not want to stay behind, we must improve our skills with it.

In the past I wrote a post about what you can achieve using vanilla JavaScript, without libraries like jQuery. Today I want to go a step further and explain some of the novelties that are in the new versions of JavaScript and that are shocking the first time you see them. I think it’s important that you know them, because they’re present in all new JavaScript projects (including Gutenberg, of course).

Let’s learn JavaScript with Gutenberg!

#1 – Destructuring Objects and Arrays

Let’s suppose we want to see how the interface of editing a paragraph in Gutenberg works. If you’ve read our previous posts on Gutenberg, you know we have to look at the edit component of the relevant block. In our case, this component is ParagraphBlock and the first thing we’ll find in its render method, line 127, is this:

What is all this? Well, let’s start with something easier. Imagine you have an object like the following:

Destructuring objects and arrays makes it possible to unpack values from arrays, or properties from objects, into distinct variables:

With a single statement, we were able to recover the id, title, and content of our post. And this is precisely what Gutenberg was doing in our first snippet: we pulled the attributes object, the setAttributes function, the isRTL attribute, etc. of this.props.

A little more confusing, but equally interesting, is the possibility of extracting attributes from nested objects. That is, starting from an object such that:

we can retrieve values in post as well as values in a nested object, such as id or name in author:

Now pay attention: every time we destructure an object, the variables we create have the same names as the attributes we’re pulling. This begs the question: what would happen if we want to recover multiple id attributes from different nested objects? For example, in our case, both the post and its nested object author have an id, so…

can we pull these two values out? The solution lies in aliases:

That is, we can specify the attribute we want to pull (for example, author.id) and the name of the variable that will hold its value (authorId) all at once.

Finally, let me tell you that destructuring also works with arrays:

as well as function parameters. That is, if one of the parameters in our function is an object, we can destructure it in the function definition itself:

Pretty handy, huh?

#2 – Arrow Functions

Another fairly common example. If you take a look at captions the Gutenberg image blocks, you’ll see the following on line 693 :

What is the value in parentheses? Why is there an arrow? What is that about setAttributes with curly braces inside? Argh!!

Well, let’s decrypt this step by step. When you see an arrow like =>, you just met an arrow function. An arrow function can be extremely similar to classic functions, but they use a slightly different syntax:

The main advantage of arrow functions is that they can be further simplified, making the code even more compact. For example, if your function has a single instruction, you can save the curly braces and the return keyword, since the function will automatically return the result of evaluating its only statement:

Another simplification that we can make are the parentheses in its argument list. If we are writing a function that has a single parameter, the parentheses become optional:

#3 – Spread and Rest Operators

Back to the paragraph block, take a look at line 64 :

What the heck?

Well, let me introduce you to the spread operator: ....

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Let’s start with the simplest example. Suppose we have an array with a certain number of elements and we want to put it inside another array. We can achieve this with:

With it, we are “expanding” (hence the operator’s name) the elements of one array (list) within the other (result).

This also works with objects:

Now look at the following example (which is a copy of the Gutenberg example with which we have opened this section):

If I am expanding two objects that have properties in common, the resulting object will contain the union of properties of both objects and, for every “repeated” property, it will contain the value of the object on the right. Thus, for example, the title attribute that is repeated in both objects, contains the value of the object newAttributes, while the other attributes (author on the one hand and words on the other) appear in the result with the only values they could contain.

#4 – Template Literals

Template literals are widely used in Gutenberg. You can see an example in the following index.js, line 133:

Or, even more complicated, inline 136:

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called “template strings” in prior editions of the ES2015 specification. Here you have another example similar to the first one we’ve just seen:

Now, what was happening in the second example? Basically, we are creating an object with properties whose “names” are dynamic (some use a variable, other use template literals). Let’s see this with a shorter example:

Easier than you expected, isn’t it?

#5 – Bye bye for and while

Finally, I would like to end this post with a couple of functions that are very useful for working with arrays and with which you should already be familiar. Both can be found, for example, in the block of Gutenberg columns. Indeed, I am talking about map (line 136) and reduce (line 119). Let’s see what each of them is for and how you can use them.

The map method creates a new array with the results of calling a provided function on every element in the calling array:

Basically, it’s a method that runs through all the elements of an array (that’s the for statement) and applies a function in each element (the “body” of the classic for).

The reduce methodis very similar to map, but instead of returning an array whose elements are the result of applying a function to the original elements, it returns a single value. That is, a method that allows you to apply a function to an accumulator and to each value of an array (from left to right) to reduce it to a single value. For example:

Wrapping Up

As you can see, new versions of JavaScript add constructions that allow writing code more efficiently and comfortably, but its syntax can be confusing at first. I hope that today’s post has helped you understand what’s new in JavaScript and how to use its new structures and functions.

I really like the way JavaScript is evolving, as I think it allows you to write better and more readable code (once you know how to read it, of course). What do you think? After reading this post, are you already keen to “learn JavaScript deeply” once and for all?

Featured image by Ross Findon on Unsplash.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...

The WordPress Block Editor Plugin Boilerplate

Published in WordPress.

The development in WordPress is being modernized by leaps and bounds. A few days ago I explained the current technologies that are already present in version 5 of our content management system. Now it’s time to teach you how to develop plugins for WordPress taking into account the possibilities of the new block editor.

Today I’ll describe the boilerplate that we are using in Nelio for our WordPress developments with a JavaScript base.

You have all the codebase of our boilerplate plugin for WordPress in GitHub, so you have no excuse to not modernize and expand your horizons as a developer.

WordPress Block Editor Boilerplate

The main reason for creating a project that serves as the basis for the creation of new WordPress plugins arises from our own need as developers to be able to unify and standardize all our projects.

The development in WordPress is no longer just PHP. Let's leave the antiques behind because it's time to modernize.
The development in WordPress is no longer just PHP. Let’s leave the old stuff behind because it’s time to modernize your skills.

Inspired by the WordPress Plugin Boilerplate, our idea is to do something similar but focused on plugins that extend the block editor with a modern stack using compilers, transpilers, bundlers and, ultimately, common development tools for JavaScript projects.

Installation And Development Process

The plugin boilerplate that we have created as a base can be downloaded directly from GitHub. After that, you can move it to the plugins folder (/wp-content/plugins/) of your WordPress installation:

git clone https://github.com/avillegasn/wp-beb.git

This will download the plugin folder with all the content. Then you need to rename both this folder and its content to use the name you want. For example, if your plugin is going to be called my-plugin:

  • rename the wp-beb files to my-plugin
  • replace wp-beb with my-plugin
  • replace wp_beb with my_plugin
  • replace WP_BEB with MY_PLUGIN

Once you have done this, to compile the plugin and generate the final code, run this:

npm install && npm run build

Keep in mind that you will need to have installed the following tools:

The npm install command downloads the dependencies of Node.js and PHP in the node_modules and vendor folders, respectively. When the process finishes you will have a dist folder with the compiled files. Now it is safe to activate the plugin in your WordPress.

In addition to the previous command, our boilerplate provides the following additional commands:

  • npm run dev Build files without minification.
  • npm run watch Build files and watch for changes.
  • npm run build Build files and minify JS and CSS.
  • npm run lint-php Run PHP_CodeSniffer on PHP files to detect errors.
  • npm run lint-php:fix Run phpcbf to try to fix PHP errors.
  • npm run lint-css Run stylelint on SCSS files to detect errors.
  • npm run lint-css:fix Try to fix errors on SCSS files.
  • npm run lint-js Run eslint on JS files to detect errors.
  • npm run lint-js:fix Try to fix errors on JS files.
  • npm run lint Run linting process on PHP, SCSS, and JS files.
  • npm run update:packages Update package dependencies in Node.js.

Usually you’ll be running npm run watch while you are developing code so that changes are compiled and bundled in real time. To generate a final, stable version, though, run npm run build.

Contents And Folder Structure

Our WordPress Block Editor Boilerplate includes the following files and folders:

  • .babelrc. Babel configuration file.
  • .editorconfig. EditorConfig file that helps maintain consistent coding styles for multiple developers working on the same project across various editors and IDEs.
  • .eslintignore. Used to exclude certain files from ESLint linting process.
  • .eslintrcESLint config file.
  • .gitattributesText file that gives attributes to path names in Git.
  • .gitignore. Used to exclude certain files from the repository.
    composer.json. Describes the PHP dependencies of the project and may contain other metadata as well.
  • composer.lock. Used to lock multiple developers working on the same project to the same versions of PHP dependencies.
    index.php. To hide the inner file structure in the server, whatever that be.
  • LICENSE.txt. Copy of the GNU GPL v2 license.
  • package-lock.json. Used to lock multiple developers working on the same project to the same versions of NPM dependencies.
  • package.jsonManifest file for the project. Central repository of configuration where you will find the names of the packages required and the CLI commands you can use to manage the project.
  • phpcs.ruleset.xmlPHP_CodeSniffer config file.
  • postcss.config.jsPostCSS config file.
  • README.md. The file that you’re currently reading.
  • readme.txt. The template for the WordPress plugin readme file.
  • webpack.config.js. Config file for webpack.
  • wp-beb.php. Main file of the WordPress plugin.
  • An assets directory that contains CSS, JS, and image resources.
  • languages directory that contains the translation files for i18n.
  • packages directory that contains block definitions to extend the WordPress block editor.

Apart from all this, once you compile the project, you will get the dist folder with the compiled files, the vendor directory with dependencies and executables for PHP, and the node_modules directory with dependencies and executables for NPM and JavaScript.

Add a New Block to The WordPress Block Editor

The interesting thing about this WordPress Block Editor Boilerplate is its default state. Once you have downloaded and compiled the plugin activate it and you’ll discover that it’s a fully functional plugin that adds a new block in your editor.

Demo block that our boilerplate includes by default in the block editor.
Demo block that our boilerplate includes by default in the block editor.

The Demo block added by our boilerplate is just a simple text block preceded by a heart dashicon, as you can see in the previous screenshot. The block also defines two additional styles, which modify the colors of the text inside the block. These should help you understand how to create blocks and styles in Gutenberg.

The JavaScript code that adds this block in the editor is in packages/blocks/demo (see here). If you want to delete this block, just delete the demo directory and delete its import and usage in the packages/blocks/index.js file.

In addition, the code for the demo block is split into different files, each of these including a different portion of the arguments used by registerBlockType.

On the other hand, if you want to add an additional block, duplicate the packages/blocks/demo and give it the name you want for your block. Modify the JavaScript files inside as you wish and remember to import the main file of the new block in packages/blocks/index.js.

Extend The Block Editor With a Plugin

In addition to the demo block that I mentioned before, our boilerplate for the block editor includes the definition of a Gutenberg plugin. Keep in mind that this “plugin” is not a regular WordPress plugin, but something that extends the block editor itself. “A plugin inside the WordPress plugin”, if you will.

Plugin for the block editor that we add by default.
Plugin for the block editor that we add by default.

You can see the plugin in the screenshot above, located on the right side. This plugin is activated by clicking on the icon on the top right, next to the publish button.

The plugin includes a color picker (so you can see how you can easily reuse the React components that Gutenberg includes) and a button to insert a demo block to the editor programmatically (another interesting scenario).

You have the plugin code in assets/src/js/admin (you can see it here). Specifically, the file plugin.js includes the call registerPlugin and the file plugin-component.js defines the component that is responsible for rendering the color picker and the button that I mentioned before.

Again, you can modify this plugin as you wish. Or you can delete it, if you want. To do so, remember to remove the plugin.js JavaScript file enqueued in the main file wp-beb.php (see here) as well as the corresponding CSS file (here).

Let’s Give it a Shot!

We hope that our WordPress Block Editor Boilerplate will help you to get rid of your JS fear and to start programming extensions for the WordPress block editor in a simple way. Try it and tell us about your experience. We will be happy to read your comments!

Featured image by Icons8 team on Unsplash.

PoorNot badGoodGreatExcellent (1 votes, average: 5.00 out of 5)
Loading...

9 Tips For Mastering The WordPress Block Editor.

Published in WordPress.

The WordPress block editor is very intuitive. But even if you’ve been using it since its first release, it’s possible that there are still tricks and little things that you haven’t noticed and that can make part of your work as a writer easier. And that’s why I think it’s worth spending a few minutes of your time to reading this post that will help you master the block editor.

If you’re still with the classic WordPress editor and don’t know how to get started with the block editor, I recommend that you read this introductory article to Gutenberg by David.

Assuming you’re already familiar with the new editor, here’s a list of new features or tricks that you may not be familiar with. I’ll start by commenting on some new blocks that make it much easier to create content and, then, some tricks you can use in the editor that can be practical for you.

#1 Add A Button

With the classic WordPress editor, if you wanted to add a button in the middle of a post or a page you basically had two options: either switch to HTML mode and write the code, or use some plugin that created a shortcode for the button in question.

The block editor already incorporates the button block that allows you to quickly create a button in the middle of a post:

Layout elements blocks of the Gutenberg editor.
Layout elements blocks of the Gutenberg editor.

The Button block allows you to create a button in which you define its appearance, the background and font colors, and you can even add a CSS class.

Creating a block with the WordPress block editor
Creating a button in this post is very easy!

It’s that easy! And the result is a button like this one, which you should click you want to subscribe to Nelio Content 😉

#2 Add a Table

As with the button, adding a simple table with the classic editor also meant doing it with HTML and CSS or with some plugin. In fact, it was often easier to create the table with any other editor and then insert it into a post as an image.

Now you have the Table block that you’ll find in the set of Formatting blocks.

Formatting blocks of the Gutenberg editor.
Formatting blocks of the Gutenberg editor.

After selecting the Table block, you must indicate the number of rows and columns that you want to create by default. But don’t worry, then you have the option to add or delete rows and columns. You can also indicate the style of the table.

Creating a Table block with the WordPress block editor.
Creating a Table block with the WordPress block editor.

In this way, you can create the following table with some features of Nelio A /B Testing very easily.

BasicProfessionalEnterprise
$29 /mo$89 /mo$259 /mo
5,000 tested page views35,000 tested page views200,000 tested page views
1 site5 sites10 sites
For IndividualsFor Small BusinessFor Large Businesses

#3 Embed An External Element Just By Copying And Pasting

Other blocks that can be very useful are embedded types, which allow you to embed external elements such as videos, Facebook posts, tweets, etc.

Some of the blocks of the Gutenberg editor to embed third party elements.
Some of the blocks of the Gutenberg editor to embed third-party elements.

But you can also, instead of creating a block of this type, directly copy and paste the URL you want to embed and automatically insert the item in question. Just paste a link such as https://youtu.be/7SzwJQ55jus and let WordPress do the magic:

#4 Use The Spacer Block To Increase The Space Between Blocks

This is one of the blocks that perhaps you didn’t know existed either: the Spacer block. Its function, as its name suggests, is to increase the spacing between blocks.

The Spacer block has by default exactly 100 pixels but you can customize the height of it as you want. Just position the cursor over the blue dot below the block and increase the size by dragging the blue dot as far as you want.

Spacer block
Customize the size of the spacer block by dragging the blue dot.

In addition, you can also use an additional CSS class to define how you want the spacer block to be. This can be very useful in the creation of pages.

#5 Information On The Number of Words and Structure

In the classic editor, you would select a post and, automatically, get number of words in that post. Now, where is this information in the block editor?

Don’t worry, in the toolbar you have this information at all times very handy by clicking on the icon of a circle with an i. And it doesn’t just count the words, it also tells you the structure of the whole post or page you’re editing.

Information about top toolbar.
In the upper toolbar you’ll find the information icon about the number of words and structure of your postor page.

#6 Move The Block Toolbar To The Top

By default, when you are editing a block you have the block toolbar floating on top of the block itself. The big advantage of this is that you have it more at hand but the problem with floating toolbars is that they can cover part of the previous block.

Floating toolbar block
Floating toolbar block in the WordPress block editor.

As you can see in the image, the toolbar is covering part of the previous headline. If this is impractical or annoying, you can easily change it. Click on the three dots of Show more tools & options and check the Top Toolbar option.

Checking Top toolbar option.
Checking Top toolbar option.

Once checked, you have the toolbar fixed at the top of your editor.

Fixed top tool bar.
Fixed top tool bar.

#7 Use The Slash (/) As A Shortcut

The block editor gives you some shortcuts so you can be more efficient editing your posts. The first one you should use is the slash, /. As easy as starting to type the name of a block with the slash and it will show you the types of blocks you can add:

Start typing with a slash
Start typing with a slash and choose the type of block you want.

#8 Learn About Other Keyboard Shortcuts

One of the features that the new editor has incorporated is that you have many other keyboard shortcuts that can help you be much faster typing. To know them all, click on the three dots of Show more tools & options:

Keyboard shortcuts.
Look at the keyboard shortcuts you have available in the editor.

Alternatively, you can also access this help with the shortcut or Ctrl H (for Mac) or Alt H (for Windows). And below I show you the shortcuts that I think you may find most useful.

Global actionsShortcut in MacShortcut in Windows
Display this helpCtrl  H  Alt H
Save your changes SCtrl S
Undo your last changes ZCtrl Z
Redo your last undo ZCtrl  Z
Show or hide the settings sidebar ,Ctrl  ,
Open the block navigation menuCtrl  O Alt O
Switch between Visual Editor and Code editor    MCtrl  Alt M
Block actionsShortcut in MacShortcut in Windows
Duplicate the selected block(s) D Ctrl D
Remove the selected block(s)Ctrl  o Alt Z
Insert a new block before the selected block(s)  TCtrl Alt T
Insert a new block after the selected block(s) YCtrl Alt Y
Change the block type after adding a new paragraph/ /
Text formattingShortcut in MacShortcut in Windows
Make the selected text bold B Ctrl B
Make the selected text italic I Ctrl I
Underline the selected text UCtrl U
Convert the selected text into a link KCtrl K
Remove a link K Ctrl K
Add a strikethrough to the selected textCtrl  D Alt D
Display the selected text in a monoespaced fontCtrl  X Alt X

#9 Convert A Block Into Header With Hashtag (#)

You might consider this as a keyboard shortcut. Gutenberg’s block editor supports three types of headers: H2, H3 and H4. When you are typing the block by default is paragraph type. But you can turn it into a header very easily: start typing the new paragraph with ## for H2, ### for H3 y #### for H4. Try it and you’ll see how easy it is.

Conclusion

The first experience you have with the new block editor after years of using the classic WordPress editor may not be what you were expecting. But it’s normal, changes are difficult.

In the beginning, you might not be able to find certain things or think the editor is slower to use… And it’s true: the block editor still needs improvement in quite a few aspects. But if you learn to master it, little by little you will see its advantages and you will see that there are things that you couldn’t easily do before that you can now do.

Our recommendation? Go ahead and give the new editor a shot—you’ll soon forget how the classic editor worked!

Featured image of Rana Sawalha on Unsplash.

PoorNot badGoodGreatExcellent (2 votes, average: 5.00 out of 5)
Loading...

Automattic Design Awards to Give More Visibility to Gutenberg

Published in Community.

As you know if you are a regular reader of this blog, we always recommend knowing the latest trends in design and development of WordPress. And that’s why we already told you all you need to know about Gutenberg (the new WordPress editor) or the 9 best block plugins with which you can create better designs for your pages and posts.

And to reward and give visibility to those who are already working with Gutenberg, Automattic, the company founded by Matt Mullenweg, creator of WordPress, held the first edition of the Automattic Design Awards in 2018.

I think you’ll like to know a little more about who the winners and finalists were, including any curiosity related to the prize. So let’s get to it.

The Prize

We wanted to show how design is thriving in the open-source web, from elegant front-end design to robust tools for creativity.

Alexis Lloyd – Automattic Design Award Blog

Prizes are offered to the winner of each of the 3 categories: Best Site, Best Solution, and Best Style. This year in particular the focus was on projects that were prepared and adapted to Gutenberg and on:

  • Deep user empathy
  • Developer led design
  • Outstanding UX
  • Attention to the details
  • Simplicity
  • Breathtaking content

As a prize, Automattic gave each winner a trophy designed by the design studio Nervous System. And it consisted of an intricate, filigree cube where the Automattic logo emerges from a cellular structure on each side. The trophies were printed in 3D using Selective Laser Sintering in white nylon. The structure was developed with Corollaria software.

Inspired by biological systems, Corollaria plays with adaptive patterns that respond to environmental conditions. You can read more about the algorithmic techniques used in this Corollaria blog post. And the following video shows you the process of generating the trophy.

Trophy generation of the Automattic Design Award.

With the prize as in the following image:

Automattic Design Award Trophy.
Automattic Design Award Trophy 2018.

The call for proposals was open until November 16, 2018 and the presentation of the winners was made public in the 2018 WordCamp US. The jury of the Automattic Design Awards was a luxury team, made up of professionals with great prestige and recognition:

Winners and Finalists

Let’s see now who were the winners and finalists in each category.

Best Site

In the category of Best Site, awards are given to websites that offer well thought-out, easy to use, and visually appealing experiences. And the winner in the Best Site category was Kit designed by Peter van Grieken.

Kit website.
kit.nl website.

The jury unanimously considered this website to be the winner: its vivid colors and general appearance are very nice. A team of 2 people made an integration of 7 websites into one without losing sight of what they wanted to get from the audience. The whole site is designed and developed in Gutenberg. I recommend you to take a look at it, as you will surely like it.

There were two finalists in this category:

  • Level Level by Taeke Reijenga
    Website of a WordPress agency with a clean and neat design.
  • Moundarren by Diane Collet
    A calm design that fits the topic of the site: poetry.

Best Solution

In the category of Best Solution, awards are given to the tools that allow others to create great sites. The winner in the Best Solution category was Rich Tabor’s Block Gallery. I told you about this plugin when I told you about the 9 best WordPress block plugins. The Block Gallery plugin gives you three new blocks exclusive to Gutenberg with which you can create three different ways to view image galleries:

Block Gallery plugin.
Blocks available in the Block Gallery plugin.

In this category, the two finalists were:

  • Atomic Blocks by Mike McAlistera
    This plugin was also one of the plugins we talked about in the previous post. It offers you 11 additional blocks to the ones you find in Gutenberg by default like buttons, testimonials, etc.
  • Create-guten-block by Ahmad Awais
    Create-guten-block is a dev-toolkit with zero configuration (#0CJS) to develop Gutenberg blocks in a matter of minutes without having to configure multiple tools and development environments.

Best Style

Finally, in the category of Best Style awards are given to sites that have a strong aesthetic form and at the same time are completely functional. Sites that are accessible, attractive, and fast are rewarded. The winner in the Best Style category was Level Level, by Taeke Reijenga. The same one that had been a finalist in the category of Best Site.

Level-level.com website.
Level-level.com website.

The Level team presented a Gutenberg site with some videos in which they explained how it works. As a company specializing in accessibility, all the tests that were carried out to evaluate this aspect had a maximum score.

In this category, the two finalists were:

  • Moundarren by Diane Collet
    As in the Best Site category, this French editor, which has been offering Chinese and Japanese poetry to an international audience for more than 30 years, was a finalist in this category due to its accessibility.
  • Emergence Magazine by Emergence Magazine and Studio Airport
    The website was created before Gutenberg was complete but its design serves as an inspiration to explore the potential of different development tools.

Congratulations!

And now all we have to do is congratulate all the prize finalists and winners. We know that all of them showed their enthusiasm with the prize received in the social networks 🤗.

Featured image by John Maeda on Twitter.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...