Proposal: Changes to JavaScript Coding Standards for Full Prettier Compatibility

I propose switching to the original version of the Prettier code formatting tool in the 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/ project and updating it to the most recent 2.5 version. Consequently, we should apply the necessary changes to the existing WordPress JavaScript Coding Standards around spacing to respect Prettier’s capabilities.

Code formatting challenges

It’s worth reminding that this topic was discussed several times, beginning in 2017 when the initial exploration of using Prettier started with WordPress/gutenberg#2819. Throughout all that time, the Prettier maintainers didn’t change their mind about adding support for spaces between parens (()) and brackets ([]) despite many requests shared in prettier/prettier#1303 from users (including the WordPress community). That’s why we decided to apply the first batch of JavaScript Coding Standards revisions two years later to use the forked version of Prettier developed by developers at Automattic. It allowed us to remain aligned with the coding style conventions used for PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher in the WordPress codebase. In particular, to follow these rules:

Use spaces liberally throughout your code. “When in doubt, space it out.”

The WordPress 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/. standards prefer slightly broader whitespace rules than the jQuery style guide. These deviations are for consistency between the PHP and JavaScript files in the WordPress codebase.

The issue is that we ended up with an outdated fork of Prettier in the Gutenberg project that didn’t get any updates for more than a year. The only motivation behind using a custom version of Prettier remains its additional functionality overriding formatting behavior for spaces around parens and brackets. In the meantime, there were three minor releases of Prettier with a long list of new features in the last year:

The Gutenberg project no longer uses only JavaScript for development. Some parts of the codebase use TypeScript, which we agreed upon a few months back. It means we can’t use improvements added for newer versions of the TypeScript language and potentially for future additions to the JavaScript language. A deprecation was also added to one of the config options we use in the shared Prettier config that the community uses. It turns out that it prevents using the @wordpress/prettier-config package with the most recent version of Prettier in 3rd party projects, as explained in WordPress/gutenberg#37516. Finally, we had multiple reports in WordPress/Gutenberg#21872 from the community members using @wordpress/scripts or @wordpress/eslint-plugin packages that the forked version of Prettier doesn’t install correctly in their projects. The good news is that switching to the original Prettier will resolve all of the above!

It quickly became noticeable that the automatic code formatting saves you so much time and energy when trying to keep a consistent coding style in the project. This is why we also started using Prettier to format other types of files it supports in the Gutenberg project, like JSONJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML., YAML, Markdown. We also consider doing the same for CSSCSS Cascading Style Sheets. and SCSS next.

RevisionsRevisions The WordPress revisions system stores a record of each saved draft or published update. The revision system allows you to see what changes were made in each revision by dragging a slider (or using the Next/Previous buttons). The display indicates what has changed in each revision. to JavaScript Coding Standards

I propose we apply all the necessary changes to the WordPress JavaScript Coding Standards to switch to the latest available version of Prettier (2.5 as of writing). The excerptExcerpt An excerpt is the description of the blog post or page that will by default show on the blog archive page, in search results (SERPs), and on social media. With an SEO plugin, the excerpt may also be in that plugin’s metabox. of the most significant revisions is included below.

-Some whitespace rules differ, for consistency with the WordPress PHP coding standards.
+Some whitespace rules differ, for consistency with the [Prettier](https://prettier.io) formatting tool.
-All new or updated JavaScript code will be reviewed to ensure it conforms to the standards, and passes JSHint.
+All new or updated JavaScript code will be reviewed to ensure it conforms to the standards, and passes [ESLint](https://eslint.org).
-Use spaces liberally throughout your code. “When in doubt, space it out.”
-Any ! negation operator should have a following space.*
+Any ! negation operator should not have a following space.
-Always include extra spaces around elements and arguments:
-array = [ a, b ]; 
-foo( arg );
-foo( 'string', object );
-foo( options, object[ property ] );
-foo( node, 'property', 2 );
-prop = object[ 'default' ];
-firstArrayElement = arr[ 0 ];
+Never include extra spaces around elements and arguments: 
+arg = [a, b]; 
+foo(arg);
+foo('string', object);
+foo(options, object[property]);
+foo(node, 'property', 2);
+prop = object['default'];
+firstArrayElement = arr[0];
-var i;
-
-if ( condition ) {
-   doSomething( 'with a string' );
-} else if ( otherCondition ) {
-    otherThing( {
-        key: value,
-        otherKey: otherValue
-    } );
-} else {
-    somethingElse( true );
-}
- 
-// Unlike jQuery, WordPress prefers a space after the ! negation operator.
-// This is also done to conform to our PHP standards.
-while ( ! condition ) {
-    iterating++;
-}
- 
-for ( i = 0; i < 100; i++ ) {
-    object[ array[ i ] ] = someFn( i );
-    $( '.container' ).val( array[ i ] );
-}
- 
-try {
-    // Expressions
-} catch ( e ) {
-    // Expressions
-}
+var i;
+
+if (condition) {
+	doSomething('with a string');
+} else if (otherCondition) {
+	otherThing({
+		key: value,
+		otherKey: otherValue,
+	});
+} else {
+	somethingElse(true);
+}
+ 
+while (!condition) {
+	iterating++;
+}
+
+for (i = 0; i < 100; i++) {
+	object[array[i]] = someFn(i);
+	$('.container').val(array[i]);
+}
+
+try {
+	// Expressions
+} catch (e) {
+	// Expressions
+}

You can preview the impact on the Gutenberg codebase on GitHubGitHub GitHub is a website that offers online implementation of git repositories that can easily be shared, copied and modified by other developers. Public repositories are free to host, private repositories require a paid subscription. GitHub introduced the concept of the ‘pull request’ where code changes done in branches by contributors can be reviewed and discussed before being merged be the repository owner. https://github.com/ in the exploratory Pull Request. The same changes would impact the tooling recommended for 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. development like @wordpress/create-block and @wordpress/scripts.

When will a decision be made?

Let’s plan for making a decision three five (updated on Jan 25th) weeks from the date of publication of this post. That should give enough time for discussion and questions.

#coding-style, #codingstandards, #javascript

WordPress JavaScript Standards Change Proposal

This post was authored by @opr18 (Thomas Roberts).

During a recent WordPress #core-js meeting there was a discussion about updating the 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/. coding standard. The specific update that is being proposed is to change the rules relating to comments.

Currently, the standard reads:

Comments come before the code to which they refer, and should always be preceded by a blank line. Capitalize the first letter of the comment, and include a period at the end when writing full sentences. There must be a single space between the comment token (//) and the comment text.

The proposal is that the new wording should be:

Comments come before the code to which they refer, and should always be preceded by a blank line. Unless writing a linter override, or a `@see` type comment, capitalize the first letter of the comment, and include a period at the end. There must be a single space between the comment token (//) and the comment text.

The problem with the current guideline is that it is not enforceable by automated tools. It is hard for linting tools to easily distinguish between what is and isn’t a full sentence in the context of code comments.

Code reviews can quickly fill up with noisy comments and suggestions to capitalise or add periods to code comments. If this were fixable with a linting rule then these comments wouldn’t be necessary.

There are instances where it may not make sense to write in sentence case, for example: adding linter overrides or writing `see` comments where the comment may just be the name of a method or file, etc. so we would not enforce the rule on these types of comments.

If this guideline were to be amended, there would be several instances of code in the 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/ repository alone that do not follow it. It would be necessary to create a PR that fixes all of these issues. Because the change only relates to comments, a single PR can be made addressing all instances of comments that don’t follow the guideline, because the rule relates to comments only, this would have no impact on functionality so minimal testing would be required.

WordPress coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. currently uses JSHint for linting JavaScript files, and it does not appear that even the existing style guideline is enforced. Even so, if efforts were made to move to ESLint in WordPress core, implementing a fix for any comments that do not follow the standard should be straightforward.

Initially the rule could be enforced as a “warning” while the PR to fix the issues is completed and after it has been merged the rule could graduate to an “error”.

Here is a draft PR demonstrating the punctuation aspect of the proposed change: https://github.com/WordPress/gutenberg/pull/34964

As a part of next steps, this post is looking for feedback on:

  • How do you feel about the proposed changes to the wording of the standard?
  • Are there any concerns about the plan for implementing this change?

This proposal is open for feedback until October 5th, 2021 at which point a final decision will be made during #core-js office hours that day.

#coding-style, #codingstandards, #proposal

Proposed coding standards change (always require braces)

Our current PHP coding standards specify that for if statements, “single line blocks can omit braces for brevity.” All other constructs “should always contain braces as this enhances readability, and allows for fewer line edits for debugging or additional functionality later.” I’d like to propose we always require braces for all blocks.

One could argue about coding standards all day (not in this comments thread), but allowing braces to be omitted is probably the only thing in our standards that can cause legitimate problems, like making it easier to introduce errors. It also makes code more annoying to patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing. and less maintainable, and requires larger diffs. And, it’s more work to debug code, as you have to add braces to add debugging lines, then remove them when done. It’s easy to attempt to add a new line inside the conditional and screw it up, which has occurred even a few times in the last few weeks. For example:

if ( some_conditional() )
    some_new_line();
    return some_function();

Another catalyst here is our new JavaScript standards. Due to multi-line chaining and other situations, it is basically insane to omit curly braces in 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/.. It would be nice if our standards matched, making this the right time to raise the issue for PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher. Our coding standards have a general emphasis on whitespace and readability, and the lack of braces do generally make code feel lighter and easier to scan, but I think we’ve reached a breaking point. I’ve surveyed the other lead developers and the consensus was that while omitting braces is elegant, it doesn’t best serve the needs of the project (with many people editing many things often).

I’d like to discuss this during today’s meeting, and ideally make a decision.

I will mention that adopting this will mean all new code will receive braces. We can discuss what to do with existing code. Please don’t waste any time on a patch to add braces manually; we’d script it and do it in one commit if that’s the route we decide to take. (There’s more than 8,000 structures lacking braces.) Also worth reading in preparation for a discussion is a section in Linux’s contributor documentation on coding style pitfalls, something I’ve linked to before.

P.S. This wouldn’t change bracing placement. It’s still like this:

function func_name() {
    if ( some_conditional() ) {
        echo "Braces shall be 'cuddled,' not pushed to the next line."
    } else {
        echo "For all control structures.";
    }
}

Update: This proposal was accepted during the Wednesday meeting. I’ve updated the coding standards handbook page. We’ve yet to discuss what we’ll do for old code, but all new and changed code should receive braces.

#coding-style

JavaScript Coding Standards

The PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher files in WordPress coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. become cleaner and easier to read with every release, thanks in part to our standards for PHP code style. Our 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/., on the other hand, hasn’t gotten nearly enough love. This post is intended to open up the recent discussion around JavaScript style to the greater community so we can make up for lost time.

Don’t we already have a style guide for JavaScript?

Back in March, @tommcfarlin added a set of coding standards for JavaScript to the developer handbook. These WordPress JS coding standards are a great work-in-progress, but weren’t fully comprehensive (leading to some comment threads clarifying various areas). More importantly, without any clear implementation plan the style guide failed to gain traction.

At WordCampWordCamp WordCamps are casual, locally-organized conferences covering everything related to WordPress. They're one of the places where the WordPress community comes together to teach one another what they’ve learned throughout the year and share the joy. Learn more. Boston’s core contributor dayContributor Day Contributor Days are standalone days, frequently held before or after WordCamps but they can also happen at any time. They are events where people get together to work on various areas of https://make.wordpress.org/ There are many teams that people can participate in, each with a different focus. https://2017.us.wordcamp.org/contributor-day/ https://make.wordpress.org/support/handbook/getting-started/getting-started-at-a-contributor-day/. I revisited this style guide with @mattwiebe and Corey Frang (@gnarf37). It is important to identify *and implement* conventions for JSJS JavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors. style ASAP because syntax issues in the JS within WordPress may hide latent bugs, and inconsistent code discourages contribution. Focusing on implementation lead us to look for an existing, proven JS style guide with a .jshintrc file (a set of configuration options for the JSHint code quality tool) which we could adopt largely as-is: Getting JSHint in place lets us see the biggest issues in our JS, so we can begin tackling them incrementally (perhaps in the same manner as the inline docs effort).

After looking at Idiomatic.js and several other widely-adopted JS style guides, we feel the jQuery Foundation’s jQuery Core JavaScript Style Guide guide is the closest match for what we need in WordPress.

Adopting the jQuery Core JavaScript Style Guide

jQuery’s guide shared WordPress core’s love of white space—the same “when in doubt, space it out” mantra from the existing JS style page. Moreover, jQuery’s code conventions have been referenced in tracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. tickets as an example of how we should be writing our code. Adopting their guide wholesale capitalizes on our stylistic similarities, and will let us adopt their .jshintrc and any future code quality tools they write with minimal changes.
Continue reading

#coding-style, #javascript

I added a little to the file naming sect…

I added a little to the file naming section of the WordPress Coding Standards to clarify the way in which we name our class files.

In summary class files will be named using hypen separation and based on the class name they contain.

I won’t be changing the name of old files but have updated the files we added in 3.1 before it’s too late.

#coding-style

clearing up after rboren

clearing up after rboren

#bug-hunt, #coding-style