#66343 closed enhancement (fixed)
Register actions for DataViews in the server
| Reported by: | jorgefilipecosta | Owned by: | jorgefilipecosta |
|---|---|---|---|
| Priority: | normal | Milestone: | 7.2 |
| Component: | General | Version: | trunk |
| Severity: | normal | Keywords: | has-patch has-unit-tests gutenberg-merge |
| Cc: | Focuses: |
Description
Related to https://core.trac.wordpress.org/ticket/66229
We want to introduce the ability to register the actions used by DataViews in the server for any given entity.
The whole initiative is tracked in Gutenberg at https://github.com/WordPress/gutenberg/issues/83537
Change History (23)
This ticket was mentioned in PR #14276 on WordPress/wordpress-develop by @jorgefilipecosta.
3 weeks ago
#2
Backports the server side of the entity actions API from https://github.com/WordPress/gutenberg/pull/84650, part of https://github.com/WordPress/gutenberg/issues/83537.
Right now the actions DataViews shows for an entity, in the lists of the site editor and in the inspector of the editor, are only defined on the client. The editor computes the core ones, and plugins can only add or remove actions in JavaScript, with registerEntityAction() and unregisterEntityAction(), which only exist in the Gutenberg plugin. This PR lets them be registered on the server, the way the entity fields API (https://github.com/WordPress/wordpress-develop/pull/13911) does for fields.
This PR:
- Adds
WP_Entity_Actions_Registry, thewp_entity_actions_api_initaction,wp_register_entity_actions()andwp_unregister_entity_actions(), and thewp_get_registered_entity_actions(),wp_get_registered_entity_action_modules()andwp_get_all_registered_entity_action_modules()readers. The registry fireswp_entity_actions_api_initthe first time it is read afterinit, only accepts registrations while that action fires, reports misuse with_doing_it_wrong(), and keeps who registered each action in itsorigin. - Makes an action definition the serializable part of a DataViews action (
id,label,isPrimary,supportsBulk,contextand the modal options). The JavaScript parts (callback,RenderModal,isEligible,icon, …) come from a script module registered with the actions: its default export maps the id of each action to its parts, and it only applies to the actions it was registered with. The registry reports acontextor amodalSizethat DataViews does not support, which would otherwise hide the action without a word, and removes acallback,RenderModalorisEligibleset in PHP, which only a script module can provide. - Adds the
GET /wp/v2/entity-actions?kind=<kind>&name=<name>route, which returns the actions of an entity and its script modules, each with the ids of the actions it applies to. It requires the same capabilities as the view config route. When a post type or taxonomy has its items on/wp/v2/entity-actions, the route is left to it, and that is reported. - Adds the script modules of the registered actions to the import map of the pages that load the editor script, as dynamic
module_dependenciesofwp-editor.
Some notes:
- Nothing registers actions yet, so nothing changes on the screens: the route returns no actions and the import map stays the same. https://github.com/WordPress/gutenberg/pull/84660 registers the core actions on the server and makes the editor read the route.
- There is no
wp_update_entity_actions(). To change an action, a plugin unregisters it and registers it again with the script module of the original, which keeps its JavaScript parts. WP_Entity_Actions_Registryis not final and its members are protected, because the Gutenberg plugin replaces the registry with a subclass oninit, as it does for the entity fields registry.- The labels registered in PHP are translated on the server. The strings of a plugin's script module need https://github.com/WordPress/wordpress-develop/pull/14260: WordPress prints translations only for the enqueued script modules and their dependencies, not for the dynamic module dependencies of a classic script.
Testing Instructions
- Save this snippet as
wp-content/mu-plugins/entity-actions-test.php(src/wp-content/mu-plugins/in a wordpress-develop checkout):
<?php
add_action( 'init', function () {
wp_register_script_module( 'my-plugin/actions', '/my-plugin-actions.js' );
} );
add_action( 'wp_entity_actions_api_init', function () {
wp_register_entity_actions( 'my-plugin', 'postType', 'page', array( array( 'id' => 'my-plugin/feature', 'label' => 'Feature', 'supportsBulk' => true ) ), 'my-plugin/actions' );
} );
- Open
wp-admin/post-new.php?post_type=page. In the console, runawait wp.apiFetch( { path: '/wp/v2/entity-actions?kind=postType&name=page' } )and verify it returns the action, withoriginset to{ registeredBy: 'my-plugin' }, and themy-plugin/actionsmodule with[ 'my-plugin/feature' ]as its actions. - In the same console, run
JSON.parse( document.querySelector( 'script[type=importmap]' ).textContent ).imports[ 'my-plugin/actions' ]and verify it returns the URL of the module. - Run
await wp.apiFetch( { path: '/wp/v2/entity-actions?kind=postType&name=missing' } )and verify it fails withrest_entity_actions_invalid_entity. - Move the
wp_register_entity_actions()call into theinitcallback. WithWP_DEBUGon, reload and verify a notice says actions can only be registered and unregistered on thewp_entity_actions_api_initaction, and that the route no longer returns the action. - Delete the snippet and run
npm run test:php -- --group entity-actions.
Gutenberg PR: https://github.com/WordPress/gutenberg/pull/84650
Use of AI Tools
AI assistance: Yes
Used for: porting the code and the tests from the Gutenberg PR, and drafting this description; reviewed and edited by me.
This ticket was mentioned in PR #14509 on WordPress/wordpress-develop by @jorgefilipecosta.
3 weeks ago
#3
Backports the PHP changes of https://github.com/WordPress/gutenberg/pull/84660, a follow-up to https://github.com/WordPress/wordpress-develop/pull/14276.
Gutenberg now registers the core actions (Trash, Rename, Duplicate…) on the server, through the entity actions API, and the editors read them from /wp/v2/entity-actions. This PR makes Core register them too.
This PR:
- Copies the PHP files of
@wordpress/core-actionsfrom the Gutenberg build towp-includes/build/scripts/core-actions/, in thegutenberg-phpcopy task that copiesroutes.phpandpages.php, and loads itsindex.phpfromwp-settings.phpthe same way. The copy translates the labels with the default text domain instead ofgutenberg. - Adds
_wp_preload_entity_actions(), which preloads the actions of the post type the post editor edits. - Ports the tests of
register_core_entity_actions(), without the "Duplicate…" action of posts, which is only registered in the Gutenberg plugin.
Some notes:
- This needs a Gutenberg pin that includes https://github.com/WordPress/gutenberg/pull/84660, which comes in its own PR along with the files it generates. Until then
wp-includes/build/scripts/core-actions/doesn't exist, so the new tests fail. - With a pin at Gutenberg trunk, the actions also include "Set as homepage…" and "Set as posts page…" from https://github.com/WordPress/gutenberg/pull/84646. Only administrators get them, on pages.
Testing Instructions
- Set
gutenberg.shainpackage.jsontotrunk, then runnpm run gutenberg:downloadandnpm run build:dev. - Open
wp-admin/site-editor.php?p=%2Fpage. In the console, runawait wp.apiFetch( { path: '/wp/v2/entity-actions?kind=postType&name=page' } )and verify it returns the actions of pages and the@wordpress/core-actions/post_type_supportsmodule. - On the same screen, verify the actions menus of a draft and a published page, and rename, trash, restore and permanently delete a page. In the patterns screen, rename and duplicate a pattern.
- Open a page in the post editor and verify the actions menu of the inspector. Verify in the Network panel that the editor made no request to
/wp/v2/entity-actions, which is preloaded. - Run
npm run test:php -- --group entity-actions.
Gutenberg PR: https://github.com/WordPress/gutenberg/pull/84660
Use of AI Tools
AI assistance: Yes
Used for: porting the code and the tests from the Gutenberg PR, and drafting this description; reviewed and edited by me.
This ticket was mentioned in PR #14514 on WordPress/wordpress-develop by @jorgefilipecosta.
3 weeks ago
#4
Trac tickets: https://core.trac.wordpress.org/ticket/66343, https://core.trac.wordpress.org/ticket/65981
This PR combines three backport PRs and a Gutenberg pin update, so they can be tested together. It's for testing only, each piece is reviewed and committed in its own PR.
This PR:
- Includes https://github.com/WordPress/wordpress-develop/pull/14512, which registers the core entity fields on the server.
- Includes https://github.com/WordPress/wordpress-develop/pull/14509, which registers the core entity actions on the server.
- Includes https://github.com/WordPress/wordpress-develop/pull/14513, which updates the entity view configs for the server fields.
- Pins Gutenberg to
61ddc552e11d158d4043e4788a99c249a13b5fbb, a trunk build, and adds the files it copies over, includingwp-includes/build/scripts/core-actions/andwp-includes/build/scripts/core-fields/.
Some notes:
- The pin can't be the 24.2.0 one from https://github.com/WordPress/wordpress-develop/pull/14497: that release doesn't include https://github.com/WordPress/gutenberg/pull/84660, https://github.com/WordPress/gutenberg/pull/84696 or https://github.com/WordPress/gutenberg/pull/84700, so the actions and fields scripts aren't built and the new code registers nothing.
- https://github.com/WordPress/wordpress-develop/pull/14495 is needed because it adds
_rest_cast_empty_objects_from_schema()torest-api.php. The entity fields endpoint uses it to return empty objects as{}rather than[], as does the view config endpoint. It landed in r64503, so it's already in trunk and in the three PRs; nothing else to apply. - Two tests fail until the pin includes https://github.com/WordPress/gutenberg/pull/85139, which removes the
gutenbergtext domain from the labels:test_the_labels_are_translated_with_the_default_text_domainin the entity actions and in the entity fields tests.
Testing Instructions
- Check out this branch and run
npm run build:dev. The Gutenberg files are already committed. - Open
wp-admin/site-editor.php?p=%2Fpage. Verify the list shows the page fields and the actions menu of a page works: rename, trash, restore and permanently delete. Do the same in the templates and patterns screens. - Open a post in the post editor and verify the fields and the actions menu in the inspector. Verify in the Network panel that the editor made no request to
/wp/v2/entity-actionsor/wp/v2/entity-fields, which are preloaded. - Insert an image block, click "Edit image" in its toolbar, then open the Details tab. Verify it shows the attachment fields from the view config.
- Add the plugin below to
wp-content/mu-plugins/. Verify "Copy title" and "Show details…" appear in the page list row menu, in the bulk bar (only "Copy title", which supports bulk) and in the post editor actions menu, and that both run. - Run
npm run test:php -- --group entity-fields,entity-actions,view-config. Only the two text domain tests should fail.
<details>
<summary>Demo plugin: <code>demo-entity-actions.php</code></summary>
<?php /** * Plugin Name: Demo entity actions * Description: Registers two actions on posts and pages through the entity actions API. * * The PHP declares the serializable part of each action. The script module in * demo-entity-actions/actions.js provides the JavaScript parts, keyed by action id. */ add_action( 'init', static function () { wp_register_script_module( 'demo-entity-actions', plugins_url( 'demo-entity-actions/actions.js', __FILE__ ), array(), '1.0.1' ); } ); add_action( 'wp_entity_actions_api_init', static function () { $actions = array( array( 'id' => 'demo-copy-title', 'label' => 'Copy title', 'supportsBulk' => true, ), array( 'id' => 'demo-details', 'label' => 'Show details…', 'modalHeader' => 'Demo details', ), ); foreach ( array( 'post', 'page' ) as $post_type ) { wp_register_entity_actions( 'demo-entity-actions', 'postType', $post_type, $actions, 'demo-entity-actions' ); } } );
</details>
<details>
<summary>Demo plugin: <code>demo-entity-actions/actions.js</code></summary>
/** * The JavaScript parts of the demo actions, keyed by the ids registered in PHP. */ const { createElement: el } = window.wp.element; const { Button, __experimentalHStack: HStack, __experimentalVStack: VStack, } = window.wp.components; const getTitle = ( item ) => ( typeof item.title === 'string' ? item.title : item.title?.raw ?? item.title?.rendered ) || `#${ item.id }`; export default { 'demo-copy-title': { callback: async ( items, { registry, onActionPerformed } ) => { const titles = items.map( getTitle ).join( '\n' ); try { await window.navigator.clipboard.writeText( titles ); } catch ( error ) { // The clipboard may be unavailable; the notice still shows the titles. } registry .dispatch( 'core/notices' ) .createSuccessNotice( `Copied: ${ titles }`, { type: 'snackbar', } ); onActionPerformed?.( items ); }, }, 'demo-details': { isEligible: ( item ) => item.status !== 'trash', RenderModal: ( { items, closeModal } ) => el( VStack, { spacing: 4 }, el( 'ul', null, items.map( ( item ) => el( 'li', { key: item.id }, `${ getTitle( item ) } — id ${ item.id }, ${ item.status }` ) ) ), el( HStack, { justify: 'flex-end' }, el( Button, { variant: 'primary', onClick: closeModal }, 'Close' ) ) ), }, };
</details>
Use of AI Tools
AI assistance: Yes
Used for: combining the branches, staging the demo plugin, and drafting this description; reviewed and edited by me.
This ticket was mentioned in PR #14515 on WordPress/wordpress-develop by @jorgefilipecosta.
3 weeks ago
#5
Trac tickets: https://core.trac.wordpress.org/ticket/66343, https://core.trac.wordpress.org/ticket/66229
This PR combines two backport PRs and a Gutenberg pin update, so they can be tested together. It's for testing only, each piece is reviewed and committed in its own PR.
This PR:
- Includes https://github.com/WordPress/wordpress-develop/pull/14509, which registers the core entity actions on the server.
- Includes https://github.com/WordPress/wordpress-develop/pull/14513, which updates the entity view configs for the server fields.
- Pins Gutenberg to
e18c3cafbe1dc2f370fdc4cb7a44811766ea177c, the latest Gutenberg trunk commit with a published build, and adds the files it copies over, includingwp-includes/build/scripts/core-actions/.
Some notes:
- The current pin (
954fe7f) doesn't include https://github.com/WordPress/gutenberg/pull/84660 or https://github.com/WordPress/gutenberg/pull/84700, so the actions scripts aren't built and the new code registers nothing. - Unlike https://github.com/WordPress/wordpress-develop/pull/14514, the core entity fields (https://github.com/WordPress/wordpress-develop/pull/14512) aren't included.
test_the_labels_are_translated_with_the_default_text_domainin the entity actions tests fails until the pin includes https://github.com/WordPress/gutenberg/pull/85139, which removes thegutenbergtext domain from the labels.
Testing Instructions
- Check out this branch and run
npm run build:dev. The Gutenberg files are already committed. - Open
wp-admin/site-editor.php?p=%2Fpage. Verify the actions menu of a page works: rename, trash, restore and permanently delete. Do the same in the templates and patterns screens. - Open a post in the post editor and verify the actions menu in the inspector. Verify in the Network panel that the editor made no request to
/wp/v2/entity-actions, which is preloaded. - Insert an image block, click "Edit image" in its toolbar, then open the Details tab. Verify it shows the attachment fields from the view config.
- Add the plugin below to
wp-content/mu-plugins/. Verify "Copy title" and "Show details…" appear in the page list row menu, in the bulk bar (only "Copy title", which supports bulk) and in the post editor actions menu, and that both run. - Run
npm run test:php -- --group entity-actions,view-config. Only the text domain test should fail.
<details>
<summary>Demo plugin: <code>demo-entity-actions.php</code></summary>
<?php /** * Plugin Name: Demo entity actions * Description: Registers two actions on posts and pages through the entity actions API. * * The PHP declares the serializable part of each action. The script module in * demo-entity-actions/actions.js provides the JavaScript parts, keyed by action id. */ add_action( 'init', static function () { wp_register_script_module( 'demo-entity-actions', plugins_url( 'demo-entity-actions/actions.js', __FILE__ ), array(), '1.0.1' ); } ); add_action( 'wp_entity_actions_api_init', static function () { $actions = array( array( 'id' => 'demo-copy-title', 'label' => 'Copy title', 'supportsBulk' => true, ), array( 'id' => 'demo-details', 'label' => 'Show details…', 'modalHeader' => 'Demo details', ), ); foreach ( array( 'post', 'page' ) as $post_type ) { wp_register_entity_actions( 'demo-entity-actions', 'postType', $post_type, $actions, 'demo-entity-actions' ); } } );
</details>
<details>
<summary>Demo plugin: <code>demo-entity-actions/actions.js</code></summary>
/** * The JavaScript parts of the demo actions, keyed by the ids registered in PHP. */ const { createElement: el } = window.wp.element; const { Button, __experimentalHStack: HStack, __experimentalVStack: VStack, } = window.wp.components; const getTitle = ( item ) => ( typeof item.title === 'string' ? item.title : item.title?.raw ?? item.title?.rendered ) || `#${ item.id }`; export default { 'demo-copy-title': { callback: async ( items, { registry, onActionPerformed } ) => { const titles = items.map( getTitle ).join( '\n' ); try { await window.navigator.clipboard.writeText( titles ); } catch ( error ) { // The clipboard may be unavailable; the notice still shows the titles. } registry .dispatch( 'core/notices' ) .createSuccessNotice( `Copied: ${ titles }`, { type: 'snackbar', } ); onActionPerformed?.( items ); }, }, 'demo-details': { isEligible: ( item ) => item.status !== 'trash', RenderModal: ( { items, closeModal } ) => el( VStack, { spacing: 4 }, el( 'ul', null, items.map( ( item ) => el( 'li', { key: item.id }, `${ getTitle( item ) } — id ${ item.id }, ${ item.status }` ) ) ), el( HStack, { justify: 'flex-end' }, el( Button, { variant: 'primary', onClick: closeModal }, 'Close' ) ) ), }, };
</details>
Use of AI Tools
AI assistance: Yes
Used for: combining the branches, updating the pin, and drafting this description; reviewed and edited by me.
This ticket was mentioned in PR #14516 on WordPress/wordpress-develop by @jorgefilipecosta.
3 weeks ago
#8
Backports the preload of https://github.com/WordPress/gutenberg/pull/85081 and its Gutenberg counterpart for the site editor actions.
The editors read the fields and actions of the post types they show from /wp/v2/entity-fields and /wp/v2/entity-actions. Core preloads the fields in the site editor and the actions in the post editor, but not the other way around.
This PR:
- Makes
_wp_preload_entity_fields()also preload the fields of the edited post type in the post editor, which the post summary of its inspector reads since https://github.com/WordPress/gutenberg/pull/85081. - Makes
_wp_preload_entity_actions()also preload, in the site editor, the actions of the edited post and of the post types its screen lists (pages, templates, patterns and template parts), reusing_wp_get_site_editor_screen_post_types(). - Replaces the test that asserted the post editor does not preload the fields, and covers the site editor actions per screen.
The new requests only happen once Core's Gutenberg pin includes the code that reads both routes. Until then the preloads go unused, as the existing ones do.
Testing Instructions
- With a Gutenberg pin that includes https://github.com/WordPress/gutenberg/pull/85081, open a page in the post editor and verify no
/wp/v2/entity-fields?kind=postType&name=pagerequest is made. - Open
wp-admin/site-editor.php?p=%2Fpageand verify no/wp/v2/entity-actions?kind=postType&name=pagerequest is made. Do the same on?p=%2Ftemplate(wp_template) and?p=%2Fpattern(wp_blockandwp_template_part). - Run
npm run test:php -- --group entity-fields,entity-actions.
Use of AI Tools
AI assistance: Yes
Used for: writing the code and the tests, and drafting this description; reviewed and edited by me.
This ticket was mentioned in PR #14545 on WordPress/wordpress-develop by @jorgefilipecosta.
3 weeks ago
#10
Removes single from the context values the entity actions registry supports, leaving list.
single came from the DataViews Action type, which describes context as "only a meta information for now". No screen shows the actions of that context: the editor's post actions menu calls usePostActions() without a context, so it keeps only the actions without one, and the lists keep list. A plugin could register an action with context => 'single' and get no notice, but the action would show nowhere. Removing it before 7.2 ships keeps the option to add it later with a defined meaning, rather than having to support it forever.
This PR:
- Sets
WP_Entity_Actions_Registry::SUPPORTED_VALUES['context']toarray( 'list' ), sosingleis reported with_doing_it_wrong(), like any other unsupported value, and is no longer in the/wp/v2/entity-actionsschemaenum. - Notes in the registry why the value from the DataViews types is left out.
- Uses
singleas the unsupported context in the invalid values test.
Testing Instructions
- Register an action with
'context' => 'single'onwp_entity_actions_api_initand verify a_doing_it_wrong()notice names it ("context is not one of list."). - Verify the
contextproperty ofOPTIONS /wp/v2/entity-actionsonly listslist. - Run
npm run test:php -- --group entity-actions.
Use of AI Tools
AI assistance: Yes
Used for: writing the code and the tests, and drafting this description; reviewed and edited by me.
@jorgefilipecosta commented on PR #14545:
3 weeks ago
#12
This ticket was mentioned in PR #14808 on WordPress/wordpress-develop by @mciampini.
3 weeks ago
#14
Backports the PHP test updates for WordPress/gutenberg#85396.
Core copies the action definitions from the Gutenberg build. That change supplies Trash as the base label and adds a translated ellipsis when the action appears in a menu. This PR updates the registered-action assertion and both translation hooks in the default-text-domain test to expect Trash.
Keep this PR as a draft until Core's Gutenberg pin includes #85396. The current pin still supplies Trash…, so these test expectations require that sync.
Testing Instructions
After syncing a Gutenberg build containing #85396, run:
npm run test:php -- --filter Tests_Entity_Actions_RegisterCoreEntityActions
The registered trash action should have the label Trash, and its translation should use the default text domain.
<details>
<summary>Local verification</summary>
PHP syntax and coding standards passed. Runtime PHPUnit verification is blocked locally because Docker has exhausted its network address pools.
</details>
Use of AI Tools
AI assistance: Yes. Codex ported the test expectations and drafted this description.
@oandregal commented on PR #14808:
2 weeks ago
#15
Added myself as a reviewer. Let me know when this has ported all changes from Gutenberg.
@mciampini commented on PR #14808:
2 weeks ago
#16
@oandregal
The two label-test failures are expected until Core syncs a Gutenberg build containing WordPress/gutenberg#85396. The current pinned build still registers Trash…, while the updated action-definition and translation tests expect Trash.
These test updates should land in the same Core changeset as that build sync. With the updated action definitions synced locally, all 16 tests passed on both single-site and multisite.
@oandregal commented on PR #14808:
2 weeks ago
#17
Even though it's not required, we could take this pull request to also update the tests here that register actions with the ellipsis.
@mciampini commented on PR #14808:
2 weeks ago
#18
@oandregal I won't be around for most of next week, would you be able to take this over and merge it when it's time?
@Mamaduka commented on PR #14808:
2 weeks ago
#19
I'll update and commit this after the sync patch lands, not a problem.
@lancewillett commented on PR #14808:
13 days ago
#21
@Mamaduka The label expectation fix landed in https://core.trac.wordpress.org/changeset/64894 on release day. This PR also changes the assertion at line 490. Is that still needed on top of r64894? If not, this can close.
@Mamaduka commented on PR #14808:
13 days ago
#22
I'll defer to @ciampo or @oandregal on that. It's not clear why the branch contains a wp_default_script_modules change; I don't see it in the linked Gutenberg PR: https://github.com/WordPress/gutenberg/pull/85396.
@oandregal commented on PR #14808:
12 days ago
#23
It looks like Gutenberg's been already synced and this PR included. Nothing else to address here.
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)
In 64517: