Thunks in Gutenberg

Gutenberg 11.6 added support for thunks. You can think of thunks as of functions that can be dispatched:

// actions.js
export const myThunkAction = () => ( { select, dispatch } ) => {
	return "I'm a thunk! I can be dispatched, use selectors, and even dispatch other actions.";
};

Why are thunks useful?

Thunks expand the meaning of what a Redux action is. Before thunks, actions were purely functional and could only return and yield data. Common use cases such as interacting with the store or requesting 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. data from an action required using a separate control. You would often see code like:

export function* saveRecordAction( id ) {
	const record = yield controls.select( 'current-store', 'getRecord', id );
	yield { type: 'BEFORE_SAVE', id, record };
	const results = yield controls.fetch({ url: 'https://...', method: 'POST', data: record });
	yield { type: 'AFTER_SAVE', id, results };
	return results;
}

const controls = {
	select: // ...,
	fetch: // ...,
};

Side effects like store operations and fetch functions would be implemented outside of the action. Thunks provide an alternative to this approach. They allow you to use side effects inline, like this:

export const saveRecordAction = ( id ) => async ({ select, dispatch }) => {
	const record = select( 'current-store', 'getRecord', id );
	dispatch({ type: 'BEFORE_SAVE', id, record });
	const response = await fetch({ url: 'https://...', method: 'POST', data: record });
	const results = await response.json();
	dispatch({ type: 'AFTER_SAVE', id, results });
	return results;
}

This removes the need to implement separate controls.

Thunks have access to the store helpers

Let’s take a look at an example from 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/ coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.. Prior to thunks, the toggleFeature action from the @wordpress/interface package was implemented like this:

export function* toggleFeature( scope, featureName ) {
	const currentValue = yield controls.select(
		interfaceStoreName,
		'isFeatureActive',
		scope,
		featureName
	);

	yield controls.dispatch(
		interfaceStoreName,
		'setFeatureValue',
		scope,
		featureName,
		! currentValue
	);
}

Controls were the only way to dispatch actions and select data from the store.

With thunks, there is a cleaner way. This is how toggleFeature is implemented now:

export function toggleFeature( scope, featureName ) {
	return function ( { select, dispatch } ) {
		const currentValue = select.isFeatureActive( scope, featureName );
		dispatch.setFeatureValue( scope, featureName, ! currentValue );
	};
}

Thanks to the select and dispatch arguments, thunks may use the store directly without the need for generators and controls.

Thunks may be async

Imagine a simple ReactReact React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org app that allows you to set the temperature on a thermostat. It only has one input and one button. Clicking the button dispatches a saveTemperatureToAPI action with the value from the input.

If we used controls to save the temperature, the store definition would look like below:

const store = wp.data.createReduxStore( 'my-store', {
    actions: {
        saveTemperatureToAPI: function*( temperature ) {
            const result = yield { type: 'FETCH_JSON', url: 'https://...', method: 'POST', data: { temperature } };
            return result;
        }
    },
    controls: { 
        async FETCH_JSON( action ) {
            const response = await window.fetch( action.url, {
                method: action.method,
                body: JSON.stringify( action.data ),
            } );
            return response.json();
        }
    },
    // reducers, selectors, ...
} );

While the code is reasonably straightforward, there is a level of indirection. The saveTemperatureToAPI action does not talk directly to the API, but has to go through the FETCH_JSON control.

Let’s see how this indirection can be removed with thunks:

const store = wp.data.createReduxStore( 'my-store', {
    __experimentalUseThunks: true,
    actions: {
        saveTemperatureToAPI: ( temperature ) => async () => {
            const response = await window.fetch( 'https://...', {
                method: 'POST',
                body: JSON.stringify( { temperature } ),
            } );
            return await response.json();
        }
    },
    // reducers, selectors, ...
} );

That’s pretty cool! What’s even better is that resolvers are supported as well:

const store = wp.data.createReduxStore( 'my-store', {
    // ...
    selectors: {
        getTemperature: ( state ) => state.temperature
    },
    resolvers: {
        getTemperature: () => async ( { dispatch } ) => {
            const response = await window.fetch( 'https://...' );
            const result = await response.json();
            dispatch.receiveCurrentTemperature( result.temperature );
        }
    },
    // ...
} );

Support for thunks is experimental for now. You can enable it by setting __experimentalUseThunks: true when registering your store.

Thunks API

A thunk receives a single object argument with the following keys:

select

An object containing the store’s selectors pre-bound to state, which means you don’t need to provide the state, only the additional arguments. select triggers the related resolvers, if any, but does not wait for them to finish. It just returns the current value even if it’s null.

If a selector is part of the public API, it’s available as a method on the select object:

const thunk = () => ( { select } ) => {
    // select is an object of the store’s selectors, pre-bound to current state:
    const temperature = select.getTemperature();
}

Since not all selectors are exposed on the store, select doubles as a function that supports passing a selector as an argument:

const thunk = () => ( { select } ) => {
    // select supports private selectors:
    const doubleTemperature = select( ( temperature ) => temperature * 2 );
}

resolveSelect

resolveSelect is the same as select, except it returns a promise that resolves with the value provided by the related resolver.

const thunk = () => ( { resolveSelect } ) => {
    const temperature = await resolveSelect.getTemperature();
}

dispatch

An object containing the store’s actions

If an action is part of the public API, it’s available as a method on the dispatch object:

const thunk = () => ( { dispatch } ) => {
    // dispatch is an object of the store’s actions:
    const temperature = await dispatch.retrieveTemperature();
}

Since not all actions are exposed on the store, dispatch doubles as a function that supports passing a Redux action as an argument:

const thunk = () => async ( { dispatch } ) => {
	// dispatch is also a function accepting inline actions:
	dispatch({ type: 'SET_TEMPERATURE', temperature: result.value });
    
	// thunks are interchangeable with actions
	dispatch( updateTemperature( 100 ) );
	
	// Thunks may be async, too. When they are, dispatch returns a promise
	await dispatch( ( ) => window.fetch( /* ... */ ) );
}

registry

A registry provides access to other stores through its dispatchselect, and resolveSelect methods. These are very similar to the ones described above, with a slight twist. Calling registry.select( storeName ) returns a function returning an object of selectors from storeName. This comes handy when you need to interact with another store. For example:

const thunk = () => ( { registry } ) => {
  const error = registry.select( 'core' ).getLastEntitySaveError( 'root', 'menu', menuId );
  /* ... */
}

This article is now a part of the developer’s handbook.

Special thanks to @jsnajdr, @get_dave, and @mcsf for their countless reviews and ideas for improving this article.

WordPress Performance Team kick off

Two weeks ago, Google and Yoast WordPress contributors posted a proposal to create a Performance team responsible for coordinating efforts to increase the performance (speed) of WordPress. The proposal was very well received overall, and many other contributors showed interest in joining the effort (thanks everyone).

This post aims at announcing the next steps.

Initial contributors coordination

As authors of the initial proposal, long time WordPress contributors, @tweetythierry, @flixos90, @aristath, @justinahinon, @adamsilverstein (in no particular order) are committed to:

  • lead the working groups formation
  • coordinate the initial administrative tasks (slackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/ channel, weekly meetings, schedule working groups representative nominations, etc.)
  • create a mission statement for the team
  • coordinate the areas to tackle
  • outline the scope and the roadmap

If you have interest in contributing to any of the above, please join the kickoff meeting, if you can, or use the comments of this post to do so.

Everybody is welcome to join working groups and contribute to performance enhancements without specific nomination 🙂

Kickoff meeting

Given the large interest from many contributors, it sounds like getting together is the first step.

By looking at the CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. Meetings calendar, Tuesdays at 3PM UTC seem good candidates. @justinahinon has offered to run chats ad interim, the kick-off meeting will happen on Tuesday, November 2nd 2021 at 3PM UTC in the #performance Slack channel.

Agenda

  • Welcome
  • Contributor interest open floor
  • Defining areas of focus

Defining focus areas and working groups

As we have seen from the initial post comments, there are no shortage of areas in need of performance enhancements in WordPress (which is a good problem to have in a way). With that in mind, we will initially aim to keep the scope limited by defining the most impactful area of focus and create working groups if need be. Defined focus areas will be the main points of discussion during weekly chats.

An agenda item for the first meetings will be to define the initial focus areas for the team. Every contributor will be asked to self-assign themselves to one or two areas, to indicate what they would like to work on. The performance projects are assembled in a spreadsheet which can already be reviewed ahead of the kickoff meeting.

This is not exclusive of any performance contributions.

Props

Thanks to the following for their involvement in authoring, proofreading and providing feedback on this post.

@francina, @flixos90, @aristath, @tweetythierry, @justinahinon (in no particular order)

#agenda, #meeting, #performance, #performance-chat

FSE Program: Answers from Round Three of Questions

This post is part of a wider series that provides answers to questions gathered through the FSE Outreach Program. This round of questions was started on October 13th and ended on October 27th. Thank you to everyone who submitted a question so our knowledge can grow together! Stay tuned for future rounds and join the FSE Outreach Program if you’re keen to both learn more about these features and help shape how they evolve.

Continue reading

#5-9, #fse-answers, #fse-outreach-program

Dev chat summary – October 27, 2021

@audrasjb led the chat on this agenda. You can also read the Slack logs.

Highlighted blogblog (versus network, site) posts

Bringing to your attention some interesting reads and some call for feedback and/or volunteers:

After 1.5 year, @francina and @audrasjb decided to pass the CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. Team Representative baton for 2022. Everyone can nominate the people they think are best suited to be our new Core team reps, just comment in the above post.

Upcoming releases updates

Next minor releaseMinor Release A set of releases or versions having the same minor version number may be collectively referred to as .x , for example version 5.2.x to refer to versions 5.2, 5.2.1, 5.2.3, and all other versions in the 5.2 (five dot two) branch of that software. Minor Releases often make improvements to existing features and functionality.: WP 5.8.2

@desrosj confirmed WP 5.8.2 Release Candidaterelease candidate One of the final stages in the version release cycle, this version signals the potential to be a final release to the public. Also see alpha (beta). is still planned for Tuesday November 2, with a few tickets including #54207 which has been quite a pain for many, so fixing it sooner rather than later is best.

Next major releasemajor release A release, identified by the first two numbers (3.6), which is the focus of a full release cycle and feature development. WordPress uses decimaling count for major release versions, so 2.8, 2.9, 3.0, and 3.1 are sequential and comparable in scope.: WP 5.9

First the Release Squad for WordPress 5.9 was published. If anyone is interested in volunteering for one of the roles needing more help, please comment on that post. If anyone has any questions about the release squad roles, some answers are available in the Core team handbook.

@audrasjb and @chaion07 published the 5.9 Bug scrub schedule.

Next scrubs are scheduled on Thursday October 28, 2021 at 20:00 UTC and on Friday October 29, 2021 at 06:00 UTC.

Please note that anyone can run a bugbug A bug is an error or unexpected result. Performance improvements, code optimization, and are considered enhancements, not defects. After feature freeze, only bugs are dealt with, with regressions (adverse changes from the previous version) being the highest priority. scrub. Checkout the Leading Bug Scrubs section in the Core handbook.

Also, a WordPress 5.9 Editor Update (26 October) was published.

Component maintainers updates

Build/Test Tools – @sergeybiryukov

The SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/ Notifications workflow was modified to be a reusable one. See changeset [51921] and some follow-up changes on ticketticket Created for both bug reports and feature development on the bug tracker. #53363.

General – @sergeybiryukov

Work has continued on various coding standards fixes in core. See tickets #53359, #54177, #54279, #54295 for more details.

Help/About – @marybaum

Two tickets are getting closer to commit but not completely there. Copy reviews are done, the component maintainers have new patches. Should be able to commit both by next Monday’s component scrub.

Open Floor

@craigfrancis wanted to discuss #54042, as I’d like to make the IN() operator easier/safer, and likewise with quoting table/field identifiers. Given the amount of information shared in the PR, @audrasjb moved this ticket to 5.9, but it will need a deep review as soon as possible to be committed ahead of the feature freeze which is the target for such enhancements.

@marybaum asked if there is still feature freeze a week or so ahead of betaBeta A pre-release of software that is given out to a large group of users to trial under real conditions. Beta versions have gone through alpha testing in-house and are generally fairly close in look, feel and function to the final product; however, design changes often occur as part of the process. 1. Feature freeze is scheduled on November 9th, and Beta 1 is on the 16th.

@afragen shared a message of @peterwilsoncc from the #core-auto-updates Slack channel. The Upgrade/Install team will meet in this channel on next Tuesday to discuss a proposal concerning the 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. Dependencies feature.

#5-8-x, #5-9, #dev-chat, #summary

CSS Chat Summary: 21 October 2021

The meeting took place here on Slack. @dryanpress facilitated and @danfarrow wrote up these notes.

The meeting was short but props are due to @dryanpress for finding a way to run it despite having no internet!

CSSCSS Cascading Style Sheets. Custom Properties (#49930)

Thanks everybody!

#core-css, #summary

WordPress 5.9 Release Squad

Update on 5.9, the schedule and more on the 5.9 Development cycle page.

WordPress 5.9 is full steam ahead towards the December 14, 2021 release date. With the Go/No Go deadline behind us, the necessary roles required for this version’s release squad have become more clear, and the team is starting to take shape.

Below is the list of roles the squad roles for the 5.9 release with confirmed contributors listed. Any role listed with a hand raised emoji (✋) still need contributors and volunteers.

  • Release LeadRelease Lead The community member ultimately responsible for the Release.: @matt
  • Release Coordinators:
  • Triagetriage The act of evaluating and sorting bug reports, in order to decide priority, severity, and other factors. Leads: @chaion07, @audrasjb.
  • Editor Tech: @noisysocks, @mamaduka.
  • Editor Design:
  • CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. Tech: @hellofromtonya. ✋
  • Theme Leads: @kjellr, @jffng.
  • Technical Writer: @psykro. ✋
  • Documentation Leads: @mkaz, @milana_cap.
  • Marketing & Communications: @chanthaboune. ✋
  • 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) Lead:
  • Test Leads: @boniu91, @annezazu.

Some Notes

  • The release squad list on the 5.9 development cycle page has also been updated. As additional contributors are confirmed for the positions needing volunteers, they will only be added to the development cycle page (not accompanied by an additional post here).
  • @noisysocks is coordinating a group of feature-specific contributors, and will be the main information person for all editor related features.
  • All WordPress 5.9 related coordination will happen inside of the #5-9-release-leads SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/ room. This room is a public viewing area for transparency (and knowledge sharing!), but is a workspace for that release squad so please limit posting as much as possible for those not on the release squad.

Props @chanthaboune and @jeffpaul for peer review.

#5-9

Dev Chat Agenda for October 27, 2021

Here is the agenda for this week’s developer meeting to occur on October 27 2021, at 20:00 UTC.

Please note that depending on your timezone, the time may have changed with the end of daylight saving time.

Blogblog (versus network, site) Post Highlights and announcements

Bringing to your attention some interesting reads and some call for feedback and/or volunteers:

Next releases status update

Have you been working on 5.9 related issues? Let everyone know!

Components check-in and status updates

  • Check-in with each component for status updates.
  • Poll for components that need assistance.

Open Floor

Do you have something to propose for the agenda, or a specific item relevant to the usual agenda items above?

Please leave a comment, and say whether or not you’ll be in the chat, so the group can either give you the floor or bring up your topic for you accordingly.

This meeting happens in the #core channel. To join the meeting, you’ll need an account on the Making WordPress Slack.

#5-9, #agenda, #core, #dev-chat

Nominations for Core Team Reps 2022

This post kicks off the election process with nominations to replace @audrasjb and @francina as CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. team reps. We have been in the role for over a year now, so 2022 marks the time to get new folks!

The Role

In the WordPress open sourceOpen Source Open Source denotes software for which the original source code is made freely available and may be redistributed and modified. Open Source **must be** delivered via a licensing model, see GPL. project, each team has on average one or two representatives, abbreviated as reps

It is not called “team lead” for a reason. It’s an administrative role. While people elected as team reps will generally come from the pool of folks that people think of as experienced leaders, the team repTeam Rep A Team Rep is a person who represents the Make WordPress team to the rest of the project, make sure issues are raised and addressed as needed, and coordinates cross-team efforts. role is designed to change hands regularly.

This role has a time commitment attached to it. Not a huge amount, it’s at least two hours a week.

Here are the main tasks:

Full details on the Team Rep role is on the Team Update site.

How the election works

Please nominate people in the comments of this post. Self-nominations are welcome. The deadline is 10 November 2021.

After that, a poll will be opened for voting. It will stay open for about two weeks. The new reps will start their role on January 1st, 2022.

If you want to nominate someone in private, please reach out to @francina or @audrasjb on SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/.

Disclaimer: if you get nominated, please don’t feel like you have to say yes. The polls will only include the names of the people that are responding positively to a nomination.  So feel free to reply with a “Thank you, but no thank you”.

If you have any questions, please feel free to ask in the comments, we will be happy to reply.

Thanks to @audrasjb for the peer review.

#team-reps

WordPress 5.9 Editor Update – 26 October

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/ 11.9 (the last 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. release which will make its way into WP 5.9) will be cut on November 3 which is in 9 days!

The merge to CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. for this release will be tricky. I’m seeking volunteers to assist with the 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.. Let me know if you can help.

@mamaduka has ran an audit of our __experimental APIs. Please give it a look over.

I asked around to identity what the “must have” enhancements are for this release and have added them to the WordPress 5.9 Must-Haves project board. Please regularly check in with this project board. There are a bunch of bugs in the board, too, and you should also pay attention to them, but they’re slightly less important because bugs can be addressed after the feature freeze.

Here’s a overview of the “must have” enhancements:

🤙

#core-editor #5-9

A Week in Core – October 25, 2021

Welcome back to a new issue of Week in CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.. Let’s take a look at what changed on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. between October 18 and October 25, 2021.

  • 14 commits
  • 9 contributors
  • 37 tickets created
  • 5 tickets reopened
  • 31 tickets closed

The Core team is currently working on the next point (5.8.2) and major (5.9) releases 🛠

Worth noting that each feature slated to the 5.9 milestone has been validated, that the Twenty Twenty-Two Theme development is on the way, and the 5.9 bug scrub schedule has been published 🚀

Ticketticket Created for both bug reports and feature development on the bug tracker. numbers are based on the Trac timeline for the period above. The following is a summary of commits, organized by component and/or focus.

We can note that there has been a decrease in the number of commits. Hopefully this will increase again quickly.

Code changes

Build/Test Tools

  • Use the correct workflow name in notifications on workflow_run#53363
  • Restore SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/ notifications for older branches – #53363
  • Add @ticket references for page_on_front canonical tests – #53363
  • Adjustments as a follow up to [51921] – #53363
  • Modify the Slack notifications workflow to be a reusable one – #53363
  • Fix syntax for passing secrets to a called workflow – #53363
  • Pass required secrets to the Slack notifications workflow – #53363

Coding Standards

  • Rename $theHeaders variable to $processed_headers in WP_Http_Curl::request()#53359
  • Rename the $arrHeaders variable to $processed_headers in WP_Http_Streams::request()#53359
  • Escape id attributes in WP_Customize_Control::render_content() and ::print_template()#54295
  • Improve escaping in wp_login_form()#54279
  • Improve escaping in wp-admin/theme-install.php#54277

Docs

  • Use sign-up & signup consistently in wp-signup.php#54041, #53399

Help/About

  • Don’t output empty tags on Credits screen – #54275

Props

Thanks to the 9 people who contributed to WordPress Core on Trac last week: @audrasjb (3), @sabbirshouvo (3), @mukesh27 (3), @jeffpaul (1), @henry.wright (1), @SergeyBiryukov (1), @sabernhardt (1), @afragen (1), and @sayedulsayem (1).

Core committers: @sergeybiryukov (7), @desrosj (6), and @peterwilsoncc (1).

#5-8-2, #5-9, #core, #week-in-core