Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an async __unstablePreSavePost hook; resolving with false prevents saving #58022

Merged
merged 12 commits into from
Aug 2, 2024

Conversation

adamsilverstein
Copy link
Member

@adamsilverstein adamsilverstein commented Jan 19, 2024

What?

  • Add a new experimental hook __unstablePreSavePost. resolving with false will prevent save from occurring.

Fixes #13413

Why?

Useful for pre-save validation where a plugin wants to validate a set of requirements before allowing the post to save. Instead of trying to disable the save button itself, this hook provides a validation opportunity _right before the post save is actually triggered. When validation fails, plugins can add a visual indication of the issue in their UI and resolve to false here to prevent the save from occurring.

See #13413 for additional discussion of use cases.

How?

  • Add a new async call to applyFilters in the savePost action right before the save actually occurs.
  • Returns early if the filter resolves to false, same as what happens when isEditedPostSaveable returning false

Testing Instructions

  1. Edit a page and click update, note save works as expected.
  2. Add the following code in the console which will prevent a save from happening and returning an error:
    wp.hooks.addFilter('editor.__unstablePreSavePost', 'editor', function(){ return Promise.resolve( { message:"This is the error message." } ) } );
  3. Try making a change and clicking Update - note a save is not completed, the error message shows at the top of the editor
  4. Add another filter that resolves to true:
    wp.hooks.removeAllFilters( 'editor.__unstablePreSavePost' ); wp.hooks.addFilter('editor.__unstablePreSavePost', 'editor', function(){ return Promise.resolve(false); } );
  5. Try clicking the update button, it will work as expected

image

);
if ( ! preSaveOK ) {
return;
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for starting to implement this! 🚀

Some further improvements would be nice:

  1. The hook should be able to return/throw an error. Like Error( 'ACF validation failed' ). The code further down the savePost function will then display a notice with that error.
  2. The hook should be able to inspect also the edits, and maybe even change them. In addition to the options that are already passed to it (in practice we inspect options.isAutosave).

The result would look like:

try {
  filteredEdits = await applyFilters(
    'editor.__unstablePreSavePost',
    Promise.resolve( edits ),
    options
  );
} catch ( err ) {
  error = err;
}

if ( ! error ) {
  // do save and the SavePost hook
}

What do you think?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👋 Thanks a lot for working on this, Adam! I was pointed to this PR by Jarda, as I have a somewhat related use case:

I have an entity (a wp_navigation postType) that is loaded via useEntityRecords(). The entity has a post meta field registered (which is returned by the endpoint). When saving the entity (after it has had some edits), I’d like to include the post meta, even if the latter doesn't have any edits. (See the bottom of this comment for more context.)

It seems that an __unstablePreSavePost filter -- if Jarda's suggestion of allowing modifications to edits is applied -- could solve that problem (although I'd need it to work in the Site Editor rather than in the Post Editor).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

although I'd need it to work in the Site Editor rather than in the Post Editor

Do we need to add it there separately @ockham?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The hook should be able to inspect also the edits, and maybe even change them. In addition to the options that are already passed to it (in practice we inspect options.isAutosave).

My only goal here is to prevent saving, I don't thing we should enable changing the edits at this point, what would the use case for that feature be?

I have an entity (a wp_navigation postType) that is loaded via useEntityRecords(). The entity has a post meta field registered (which is returned by the endpoint). When saving the entity (after it has had some edits), I’d like to include the post meta, even if the latter doesn't have any edits.

@ockham Ah, this does sound like a valid use case for being able to modify the edits before a save, have you already solved this elsewhere?

This would complicate the use of the proposed preSave hook as I intended - simply returning an error message to hook into the existing error handling logic to prevent saving.

Since this proposal changes the use case for the hook, I would prefer to consider it in a follow up issue, what do you think?

Copy link

github-actions bot commented May 8, 2024

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

Unlinked Accounts

The following contributors have not linked their GitHub and WordPress.org accounts: @aduth, @lex127, @audiovisuel-uqam, @eballeste, @jenilk, @zhitaryksergey, @christianMiguez.

Contributors, please read how to link your accounts to ensure your work is properly credited in WordPress releases.

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Unlinked contributors: aduth, lex127, audiovisuel-uqam, eballeste, jenilk, zhitaryksergey, christianMiguez.

Co-authored-by: adamsilverstein <[email protected]>
Co-authored-by: jsnajdr <[email protected]>
Co-authored-by: ockham <[email protected]>
Co-authored-by: sadmansh <[email protected]>
Co-authored-by: sc0ttkclark <[email protected]>
Co-authored-by: youknowriad <[email protected]>
Co-authored-by: gziolo <[email protected]>
Co-authored-by: acafourek <[email protected]>
Co-authored-by: marcwieland95 <[email protected]>
Co-authored-by: margolisj <[email protected]>
Co-authored-by: noisysocks <[email protected]>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

@adamsilverstein
Copy link
Member Author

@jsnajdr Getting back to this after a break, thanks for the feedback - I like the idea of using an Error and of being able to modify the edits.

I applied your suggestions as I understood them, can you take another look?

@adamsilverstein adamsilverstein requested a review from jsnajdr May 8, 2024 19:44
@sadmansh
Copy link

@jsnajdr can you take a look at this please when you have a moment?

Copy link
Member

@jsnajdr jsnajdr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm pointing out three little bugs that should be fixed before merging. Otherwise this looks very good, thanks for working on this and addressing all feedback 👍

packages/editor/src/store/actions.js Outdated Show resolved Hide resolved
packages/editor/src/store/actions.js Outdated Show resolved Hide resolved
packages/editor/src/store/actions.js Outdated Show resolved Hide resolved
@jsnajdr
Copy link
Member

jsnajdr commented Jun 4, 2024

Hi @adamsilverstein 👋 Do you plan to work on this PR? It's very close to being finished and it would be nice to get it into WordPress 6.6. I could take it over from you and get it merged if you agree.

@sc0ttkclark
Copy link

Excited for this PR

@adamsilverstein
Copy link
Member Author

Hi @adamsilverstein 👋 Do you plan to work on this PR? It's very close to being finished and it would be nice to get it into WordPress 6.6. I could take it over from you and get it merged if you agree.

Thanks for the ping @jsnajdr (and @bph). I will get back to updating this soon!

@adamsilverstein
Copy link
Member Author

@jsnajdr I have tried to address all your feedback, please review again when you have a moment!

@adamsilverstein
Copy link
Member Author

I have updated the PR so functionality is restored and tests pass. Appreciate any reviews/feedback.

Copy link
Member

@jsnajdr jsnajdr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, let's finally merge this 🙂

In a followup we can fine-tune the error handling and also start passing edits to the hook. Hopefully the post-meta-saving code in block hooks will be able to use the hook and validate that it's really useful.

@jsnajdr jsnajdr merged commit 3c7d4d6 into WordPress:trunk Aug 2, 2024
61 of 62 checks passed
@github-actions github-actions bot added this to the Gutenberg 19.0 milestone Aug 2, 2024
@talldan
Copy link
Contributor

talldan commented Aug 2, 2024

Sorry for the late feedback, I only just saw this.

I might be missing something, but I don't think this should ship with the __unstable prefix. Background is that the project no longer ships new __experimental or __unstable APIs since this discussion resulted in some changes - https://make.wordpress.org/core/2022/08/10/proposal-stop-merging-experimental-apis-from-gutenberg-to-wordpress-core/. Efforts are now being made to deprecate APIs with those prefixes where it's possible.

Regardless, __unstable means not for external use, and it seems like the goal of this is for external use, so I don't think it should ship in a release with the prefix.

@jsnajdr
Copy link
Member

jsnajdr commented Aug 2, 2024

Sure, let's remove the __unstable prefix. From both preSavePost and savePost hooks. How much time do we have? Does the no-__unstable rule apply for plugin releases, or only for Core releases?

@jsnajdr
Copy link
Member

jsnajdr commented Aug 2, 2024

I'm proposing the stabilization and some followup changes in #64198.

try {
error = await applyFilters(
'editor.__unstablePreSavePost',
Promise.resolve( false ),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I'm not wrong we use this technique (a promise filter) because we don't support async actions yet right? Can we implement async action instead? await doAsyncAction( 'editor.__unstablePreSavePost' )

I have another use-case for this and maybe it's time to fix that once and for all.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea. I'm working on this and one little obstacle is that currentFilter()/currentAction() don't make sense any more, because there can be multiple hooks running at the same time.

If you use the promise filter technique with sync hooks this problem is invisible. Because the hook merely sets up a promise chain and returns. Only later the actual data will flow through the chain. This will change when runHook will start waiting for each promise returned from a handler to resolve.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a draft PR for async hooks: #64204

@talldan
Copy link
Contributor

talldan commented Aug 5, 2024

Sure, let's remove the __unstable prefix. From both preSavePost and savePost hooks. How much time do we have? Does the no-__unstable rule apply for plugin releases, or only for Core releases?

Thanks for spinning up a PR quickly. I'll give it a review.

It's mostly core releases that are a concern, though ideally it also wouldn't ship in a plugin release. If it does I think the usual rule is deprecate for two plugin versions and then remove. It's a bit of hassle that's usually better to avoid where possible.

Next plugin release (19.0) is on 14th August, with the RC on 7th August, so there should be time to rectify.

@jeffpaul
Copy link
Member

jeffpaul commented Nov 8, 2024

@lex127 mind sharing your WordPress.org username so I can ensure its included in the 6.7 credits listing?

@jeffpaul
Copy link
Member

jeffpaul commented Nov 8, 2024

@audiovisuel-uqam mind sharing your WordPress.org username so I can ensure its included in the 6.7 credits listing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[Feature] Extensibility The ability to extend blocks or the editing experience [Type] Enhancement A suggestion for improvement.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Extensibility: Add a way for third parties to perform additional save validation
8 participants