diff --git a/lib/compat/wordpress-7.3/navigation-auto-add-pages.php b/lib/compat/wordpress-7.3/navigation-auto-add-pages.php new file mode 100644 index 00000000000000..0e61b375ed8564 --- /dev/null +++ b/lib/compat/wordpress-7.3/navigation-auto-add-pages.php @@ -0,0 +1,358 @@ + 'boolean', + 'description' => __( 'Whether newly published pages are added to the menu.', 'gutenberg' ), + 'single' => true, + 'default' => false, + 'sanitize_callback' => 'rest_sanitize_boolean', + 'show_in_rest' => true, + ) + ); +} +add_action( 'init', 'gutenberg_register_navigation_auto_add_pages_meta' ); + +/** + * Builds a Navigation Link block (or a Navigation Submenu block, when it has + * inner blocks) pointing at a page. + * + * Matches the blocks the Page List block creates when it is detached into + * links, including the URL binding that keeps the link in step with the + * page's permalink. + * + * @param WP_Post $page The page to link to. + * @param array $inner_blocks Optional. Parsed blocks nested under the link. + * @param bool $filter_label Optional. Whether to filter the label with + * kses, for a user who can't post unfiltered + * HTML. Default false. + * @return array A parsed block. + */ +function gutenberg_navigation_build_page_link_block( $page, $inner_blocks = array(), $filter_label = false ) { + $label = '' !== $page->post_title ? $page->post_title : __( '(no title)', 'gutenberg' ); + return array( + 'blockName' => empty( $inner_blocks ) ? 'core/navigation-link' : 'core/navigation-submenu', + 'attrs' => array( + 'label' => $filter_label ? wp_kses_post( $label ) : $label, + 'type' => 'page', + 'id' => (int) $page->ID, + 'url' => get_permalink( $page ), + 'kind' => 'post-type', + 'metadata' => array( + 'bindings' => array( + 'url' => array( + 'source' => 'core/post-data', + 'args' => array( 'field' => 'link' ), + ), + ), + ), + ), + 'innerBlocks' => $inner_blocks, + 'innerHTML' => '', + 'innerContent' => array_fill( 0, count( $inner_blocks ), null ), + ); +} + +/** + * Checks whether a block is a Navigation Link or Submenu pointing at a page. + * + * @param array $block Parsed block. + * @param int $page_id Page ID. + * @return bool Whether the block links to the page. + */ +function gutenberg_navigation_block_links_to_page( $block, $page_id ) { + if ( ! in_array( $block['blockName'] ?? null, array( 'core/navigation-link', 'core/navigation-submenu' ), true ) ) { + return false; + } + $attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array(); + if ( ! isset( $attrs['id'] ) || ! is_numeric( $attrs['id'] ) || (int) $attrs['id'] !== $page_id ) { + return false; + } + $kind = isset( $attrs['kind'] ) ? $attrs['kind'] : ''; + $type = isset( $attrs['type'] ) ? $attrs['type'] : ''; + return 'post-type' === $kind || 'page' === $type; +} + +/** + * Checks whether any block in a tree links to the given page. + * + * @param array $blocks Parsed blocks. + * @param int $page_id Page ID. + * @return bool Whether a Navigation Link or Submenu for the page exists. + */ +function gutenberg_navigation_blocks_link_to_page( $blocks, $page_id ) { + foreach ( $blocks as $block ) { + if ( ! is_array( $block ) ) { + continue; + } + if ( gutenberg_navigation_block_links_to_page( $block, $page_id ) ) { + return true; + } + if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) && gutenberg_navigation_blocks_link_to_page( $block['innerBlocks'], $page_id ) ) { + return true; + } + } + + return false; +} + +/** + * Checks whether a Page List block lists a page. + * + * Like the Page List block, it lists published pages under published parent + * pages: every page or, with a parent page set, the pages under that page. + * + * @param int $parent_page_id The Page List's parent page, or 0 for all pages. + * @param WP_Post $page The page. + * @return bool Whether the Page List lists the page. + */ +function gutenberg_navigation_page_list_lists_page( $parent_page_id, $page ) { + foreach ( get_post_ancestors( $page ) as $ancestor_id ) { + if ( $parent_page_id === (int) $ancestor_id ) { + return true; + } + if ( 'publish' !== get_post_status( $ancestor_id ) ) { + return false; + } + } + + return 0 === $parent_page_id; +} + +/** + * Checks whether a Page List block in a tree shows a page. + * + * A Page List shows every page or, with `parentPageID` set, the pages under + * that page. + * + * @param array $blocks Parsed blocks. + * @param WP_Post $page The page. + * @return bool Whether a Page List block in the tree shows the page. + */ +function gutenberg_navigation_page_list_shows_page( $blocks, $page ) { + foreach ( $blocks as $block ) { + if ( ! is_array( $block ) ) { + continue; + } + if ( 'core/page-list' === ( $block['blockName'] ?? null ) ) { + $attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array(); + // A value that isn't an integer fails the block's attribute + // validation, which falls back to the default, 0. + $parent_page_id = isset( $attrs['parentPageID'] ) && is_numeric( $attrs['parentPageID'] ) && rest_is_integer( $attrs['parentPageID'] ) ? (int) $attrs['parentPageID'] : 0; + if ( gutenberg_navigation_page_list_lists_page( $parent_page_id, $page ) ) { + return true; + } + } + if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) && gutenberg_navigation_page_list_shows_page( $block['innerBlocks'], $page ) ) { + return true; + } + } + + return false; +} + +/** + * Inserts a link to a page among its sibling blocks in page order. + * + * The link goes before the first link to a page that sorts after it by menu + * order and then title, as the Page List block sorts pages. When no linked + * page sorts after it, it goes after the last link to a page, or at the end + * when there is none. Other blocks keep their places. + * + * @param array $blocks Parsed sibling blocks, modified in place. + * @param WP_Post $page The page the link points at. + * @param array $link Parsed block linking to the page. + * @return void + */ +function gutenberg_navigation_insert_page_link( &$blocks, $page, $link ) { + $before = null; + $after = null; + foreach ( array_values( $blocks ) as $index => $block ) { + if ( ! is_array( $block ) ) { + continue; + } + $attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array(); + $sibling_id = isset( $attrs['id'] ) && is_numeric( $attrs['id'] ) ? (int) $attrs['id'] : 0; + $sibling = $sibling_id && gutenberg_navigation_block_links_to_page( $block, $sibling_id ) + ? get_post( $sibling_id ) + : null; + if ( ! $sibling || 'page' !== $sibling->post_type ) { + continue; + } + $order = $sibling->menu_order <=> $page->menu_order; + if ( 0 === $order ) { + // Close to the database's collation, by which the Page List sorts + // titles: case and accents are ignored. + $order = strcasecmp( remove_accents( $sibling->post_title ), remove_accents( $page->post_title ) ); + } + if ( $order > 0 ) { + $before = $index; + break; + } + $after = $index + 1; + } + + array_splice( $blocks, $before ?? $after ?? count( $blocks ), 0, array( $link ) ); +} + +/** + * Nests a link to a page under the first block in a tree that links to the + * page's parent, in page order among the parent's other links. + * + * A Navigation Link for the page becomes a Navigation Submenu with the same + * attributes. With submenus set to open on click, the parent's item then + * opens the submenu instead of the page, as a parent page does in a Page + * List. + * + * @param array $blocks Parsed blocks, modified in place. + * @param WP_Post $page The child page. + * @param array $link Parsed block linking to the page. + * @return bool Whether a parent block was found. + */ +function gutenberg_navigation_nest_block_under_page( &$blocks, $page, $link ) { + foreach ( $blocks as &$block ) { + if ( ! is_array( $block ) ) { + continue; + } + $inner_blocks = isset( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ? $block['innerBlocks'] : array(); + if ( gutenberg_navigation_block_links_to_page( $block, $page->post_parent ) ) { + gutenberg_navigation_insert_page_link( $inner_blocks, $page, $link ); + $block['blockName'] = 'core/navigation-submenu'; + $block['innerBlocks'] = $inner_blocks; + $block['innerHTML'] = ''; + $block['innerContent'] = array_fill( 0, count( $inner_blocks ), null ); + return true; + } + if ( ! empty( $inner_blocks ) && gutenberg_navigation_nest_block_under_page( $inner_blocks, $page, $link ) ) { + $block['innerBlocks'] = $inner_blocks; + return true; + } + } + + return false; +} + +/** + * Adds a link to a newly published page to every Navigation Menu that has + * "Auto add new pages" switched on. + * + * A top-level page is added to the menu in page order. A child page is nested + * under the link to its parent, which becomes a submenu; a menu with no link + * to the parent is left alone, and so is a menu with a Page List block that + * already shows the page. Like `_wp_auto_add_pages_to_menu()` for classic + * menus, only the transition into `publish` counts, and a page the menu + * already links to is not added again. + * + * @param string $new_status New post status. + * @param string $old_status Old post status. + * @param WP_Post $post The post being transitioned. + * @return void + */ +function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status, $post ) { + if ( 'publish' !== $new_status || 'publish' === $old_status || 'page' !== $post->post_type ) { + return; + } + + $menus = get_posts( + array( + 'post_type' => 'wp_navigation', + 'post_status' => 'any', + 'posts_per_page' => -1, + 'meta_key' => 'wp_navigation_auto_add_pages', + 'meta_value' => '1', + 'no_found_rows' => true, + 'update_post_term_cache' => false, + ) + ); + + // The kses filters on the post fields the current user saves, with their + // priorities. They're there when the user can't post unfiltered HTML. + $kses_filters = array(); + foreach ( + array( + 'title_save_pre' => 'wp_filter_kses', + 'content_save_pre' => 'wp_filter_post_kses', + 'excerpt_save_pre' => 'wp_filter_post_kses', + 'content_filtered_save_pre' => 'wp_filter_post_kses', + ) as $hook => $callback + ) { + $priority = has_filter( $hook, $callback ); + if ( false !== $priority ) { + $kses_filters[] = array( $hook, $callback, $priority ); + } + } + $filters_content = false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' ); + + foreach ( $menus as $menu ) { + $blocks = parse_blocks( $menu->post_content ); + if ( gutenberg_navigation_page_list_shows_page( $blocks, $post ) || gutenberg_navigation_blocks_link_to_page( $blocks, $post->ID ) ) { + continue; + } + + $link = gutenberg_navigation_build_page_link_block( $post, array(), $filters_content ); + if ( empty( $post->post_parent ) ) { + gutenberg_navigation_insert_page_link( $blocks, $post, $link ); + } elseif ( ! gutenberg_navigation_nest_block_under_page( $blocks, $post, $link ) ) { + continue; + } + + /** + * The parsed blocks, with the link added. + * + * @var array, innerBlocks: array>, innerHTML: string, innerContent: array}> $blocks + */ + $content = serialize_blocks( $blocks ); + + // The menu's items were filtered when they were saved, by a user + // allowed to save them. Filtering them again here, as the user who + // publishes the page, would strip what that user can't post, such as + // an icon in a link's label. Only the new link's label comes from this + // user, so only it is filtered (above), and the kses filters are + // lifted for this save alone, which also writes back the menu's + // title. + foreach ( $kses_filters as list( $hook, $callback, $priority ) ) { + remove_filter( $hook, $callback, $priority ); + } + try { + wp_update_post( + array( + 'ID' => $menu->ID, + 'post_content' => wp_slash( $content ), + ) + ); + } finally { + foreach ( $kses_filters as list( $hook, $callback, $priority ) ) { + add_filter( $hook, $callback, $priority ); + } + } + } +} +add_action( 'transition_post_status', 'gutenberg_navigation_auto_add_page_on_publish', 10, 3 ); diff --git a/lib/load.php b/lib/load.php index dacded620eed44..06b8a8229e6724 100644 --- a/lib/load.php +++ b/lib/load.php @@ -159,6 +159,7 @@ function gutenberg_get_experiment_default( $name ) { // WordPress 7.3 compat. require __DIR__ . '/compat/wordpress-7.3/kses.php'; +require __DIR__ . '/compat/wordpress-7.3/navigation-auto-add-pages.php'; // Experimental features. require __DIR__ . '/experimental/block-editor-settings-mobile.php'; diff --git a/package-lock.json b/package-lock.json index 9dab61d5a585dd..1d35ab3cc9bb02 100644 --- a/package-lock.json +++ b/package-lock.json @@ -45720,7 +45720,8 @@ "@wordpress/icons": "file:../../packages/icons", "@wordpress/lazy-editor": "file:../../packages/lazy-editor", "@wordpress/route": "file:../../packages/route", - "@wordpress/routes-lock-unlock": "file:../lock-unlock" + "@wordpress/routes-lock-unlock": "file:../lock-unlock", + "@wordpress/ui": "file:../../packages/ui" }, "devDependencies": { "@types/react": "^19.3.0" diff --git a/packages/block-editor/CHANGELOG.md b/packages/block-editor/CHANGELOG.md index ce8a126e70e439..4e32f39835d86e 100644 --- a/packages/block-editor/CHANGELOG.md +++ b/packages/block-editor/CHANGELOG.md @@ -9,6 +9,7 @@ ### Bug Fixes +- Keep a controlled block's inner blocks reference stable when the root blocks are reset and its preserved sub-tree is unchanged, so nested controllers such as a Navigation block inside a template part no longer report an edit they did not make. That spurious edit could shadow menu content refetched from the server, leaving the block stale until a reload ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). - List View: Pasting a file without upload permissions no longer replaces the focused block ([#87852](https://github.com/WordPress/gutenberg/pull/87852)). - Edit as HTML: Keep the block HTML visible when the block has a text gradient ([#86370](https://github.com/WordPress/gutenberg/pull/86370)). - Stop forwarding `pointerdown`, `mousedown`, and `click` from the editor canvas iframe to the parent document, where they closed plugin popups on their own clicks ([#87851](https://github.com/WordPress/gutenberg/pull/87851)). diff --git a/packages/block-editor/src/store/reducer.ts b/packages/block-editor/src/store/reducer.ts index ef91c079bb387a..6f2427c1f1ac4b 100644 --- a/packages/block-editor/src/store/reducer.ts +++ b/packages/block-editor/src/store/reducer.ts @@ -776,18 +776,39 @@ const withBlockReset = const fixedClientIds: string[] = []; for ( const clientId of newState.controlledInnerBlocks ) { const controlledOrder = newState.order.get( clientId )!; - const innerBlocks = controlledOrder.map( - ( id ) => state!.tree.get( id ) as TreeBlock + // When the preserved sub-tree is unchanged, keep the previous + // entry so `getBlocks( clientId )` keeps its reference: the + // controller syncing those blocks to its entity would otherwise + // see a change it did not make and report it as an edit. + const previousEntry = state!.tree.get( + 'controlled||' + clientId ); + const isUnchanged = + previousEntry?.innerBlocks.length === + controlledOrder.length && + controlledOrder.every( + ( id, index ) => + previousEntry.innerBlocks[ index ] === + state!.tree.get( id ) + ); + const innerBlocks = isUnchanged + ? previousEntry.innerBlocks + : controlledOrder.map( + ( id ) => state!.tree.get( id ) as TreeBlock + ); const existingEntry = newState.tree.get( clientId ); - if ( existingEntry ) { + // A preserved entry already has none, so it keeps its reference. + if ( existingEntry?.innerBlocks.length ) { newState.tree.set( clientId, { ...existingEntry, innerBlocks: [], } ); fixedClientIds.push( clientId ); } - newState.tree.set( 'controlled||' + clientId, { innerBlocks } ); + newState.tree.set( + 'controlled||' + clientId, + isUnchanged ? previousEntry : { innerBlocks } + ); const preserveTreeEntry = ( blockId: string ) => { const treeEntry = state!.tree.get( blockId ); if ( ! treeEntry ) { diff --git a/packages/block-editor/src/store/test/reducer.ts b/packages/block-editor/src/store/test/reducer.ts index 0a7d75383aec91..9a0177f4365f1a 100644 --- a/packages/block-editor/src/store/test/reducer.ts +++ b/packages/block-editor/src/store/test/reducer.ts @@ -3252,6 +3252,78 @@ describe( 'state', () => { ).toEqual( [ 'content-inner' ] ); } ); + it( 'should keep the controlled inner blocks references across RESET_BLOCKS when the sub-trees are preserved', () => { + const resetAction = { + type: 'RESET_BLOCKS' as const, + blocks: [ + partial< Block >( { + clientId: 'chicken', + name: 'core/test-block', + attributes: {}, + innerBlocks: [], + } ), + ], + }; + let state = blocks( undefined, resetAction ); + // A controlled block (`chicken`) with a nested controlled + // block (`content`), like a template part holding a + // navigation block. + state = blocks( state, { + type: 'SET_HAS_CONTROLLED_INNER_BLOCKS', + clientId: 'chicken', + hasControlledInnerBlocks: true, + } ); + state = blocks( state, { + type: 'REPLACE_INNER_BLOCKS', + rootClientId: 'chicken', + blocks: [ + partial< Block >( { + clientId: 'content', + name: 'core/test-block', + attributes: {}, + innerBlocks: [], + } ), + ], + } ); + state = blocks( state, { + type: 'SET_HAS_CONTROLLED_INNER_BLOCKS', + clientId: 'content', + hasControlledInnerBlocks: true, + } ); + state = blocks( state, { + type: 'REPLACE_INNER_BLOCKS', + rootClientId: 'content', + blocks: [ + partial< Block >( { + clientId: 'content-inner', + name: 'core/test-block', + attributes: {}, + innerBlocks: [], + } ), + ], + } ); + const before = partial< State >( { blocks: state } ); + + const after = partial< State >( { + blocks: blocks( state, resetAction ), + } ); + + // Nothing under the controlled blocks changed, so their + // block lists keep their references and the controllers + // syncing them do not see a change. + expect( getBlocks( after, 'chicken' ) ).toBe( + getBlocks( before, 'chicken' ) + ); + expect( getBlocks( after, 'content' ) ).toBe( + getBlocks( before, 'content' ) + ); + expect( + getBlocks( after, 'content' ).map( + ( b ) => ( b as Block ).clientId + ) + ).toEqual( [ 'content-inner' ] ); + } ); + it( 'should ignore inner blocks in RESET_BLOCKS for a controlled block with no inner blocks', () => { const original = blocks( undefined, { type: 'RESET_BLOCKS', diff --git a/packages/block-library/CHANGELOG.md b/packages/block-library/CHANGELOG.md index 209302f4b94c8a..f028c7a27a9177 100644 --- a/packages/block-library/CHANGELOG.md +++ b/packages/block-library/CHANGELOG.md @@ -4,6 +4,7 @@ ### Enhancements +- Navigation: Add an "Auto add new pages" menu setting. While it is on, publishing a page adds a link to the menu, as classic menus do: a top-level page is added, and a child page is nested under the link to its parent, which becomes a submenu ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). - Tab List: Add font style support ([#87824](https://github.com/WordPress/gutenberg/pull/87824)). ### Bug Fixes diff --git a/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx b/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx new file mode 100644 index 00000000000000..019308a955a7a6 --- /dev/null +++ b/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx @@ -0,0 +1,83 @@ +import { store as coreStore } from '@wordpress/core-data'; +import { useDispatch, useSelect } from '@wordpress/data'; +import { __ } from '@wordpress/i18n'; +import { SwitchControl } from '@wordpress/ui'; + +const META_KEY = 'wp_navigation_auto_add_pages'; + +type NavigationMenuRecord = { + meta?: Record< string, unknown >; +}; + +type Props = { + /** The `wp_navigation` post the block displays. */ + menuId: number; + /** + * Class for the wrapper, in place of the default one that sets the + * setting apart below a menu's list of links. + */ + className?: string; +}; + +/** + * The menu's "Auto add new pages" setting. + * + * It belongs to the Navigation Menu rather than to the block, so a change is + * an edit to the menu record and is saved along with the block's other menu + * edits. It renders nothing for a user who cannot update the menu, or when the + * server has no such setting, as in a WordPress release without it. + * + * @param props + * @param props.menuId + * @param props.className + */ +export default function AutoAddPagesControl( { + menuId, + className = 'wp-block-navigation__auto-add-pages', +}: Props ) { + const { canUpdate, hasSetting, isEnabled } = useSelect( + ( select ) => { + const { canUser, getEditedEntityRecord } = select( coreStore ); + const record = getEditedEntityRecord( + 'postType', + 'wp_navigation', + menuId + ) as NavigationMenuRecord | undefined; + return { + canUpdate: !! canUser( 'update', { + kind: 'postType', + name: 'wp_navigation', + id: menuId, + } ), + // The REST API lists every registered meta key. + hasSetting: !! record?.meta && META_KEY in record.meta, + isEnabled: !! record?.meta?.[ META_KEY ], + }; + }, + [ menuId ] + ); + const { editEntityRecord } = useDispatch( coreStore ); + + if ( ! canUpdate || ! hasSetting ) { + return null; + } + + const setEnabled = ( value: boolean ) => { + editEntityRecord( 'postType', 'wp_navigation', menuId, { + meta: { [ META_KEY ]: value }, + } ); + }; + + return ( +
+ +
+ ); +} diff --git a/packages/block-library/src/navigation/edit/menu-inspector-controls.tsx b/packages/block-library/src/navigation/edit/menu-inspector-controls.tsx index c7ecb2fc0119c5..62de1f5d959738 100644 --- a/packages/block-library/src/navigation/edit/menu-inspector-controls.tsx +++ b/packages/block-library/src/navigation/edit/menu-inspector-controls.tsx @@ -14,6 +14,7 @@ import useNavigationMenu from '../use-navigation-menu'; import LeafMoreMenu from './leaf-more-menu'; import { NavigationLinkUI } from './navigation-link-ui'; import NavigationListViewHeader from './navigation-list-view-header'; +import AutoAddPagesControl from './auto-add-pages-control'; import type { MainContentProps, MenuInspectorControlsProps, @@ -88,6 +89,9 @@ const MainContent = ( { additionalBlockContent={ NavigationLinkUI } onSelect={ openListViewContentPanel } /> + { navigationMenu && ( + + ) } ); }; diff --git a/packages/block-library/src/navigation/edit/test/auto-add-pages-control.jsdom.test.tsx b/packages/block-library/src/navigation/edit/test/auto-add-pages-control.jsdom.test.tsx new file mode 100644 index 00000000000000..63d3b030bfd335 --- /dev/null +++ b/packages/block-library/src/navigation/edit/test/auto-add-pages-control.jsdom.test.tsx @@ -0,0 +1,60 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import apiFetch from '@wordpress/api-fetch'; +import { store as coreStore } from '@wordpress/core-data'; +import { createRegistry, RegistryProvider } from '@wordpress/data'; +import AutoAddPagesControl from '../auto-add-pages-control'; + +// The store's resolvers would otherwise fetch what the tests provide. +vi.mock( import( '@wordpress/api-fetch' ) ); + +function renderControl( meta: Record< string, unknown > | undefined ) { + const registry = createRegistry(); + registry.register( coreStore ); + const { addEntities, receiveEntityRecords, receiveUserPermission } = + registry.dispatch( coreStore ); + addEntities( [ + { + kind: 'postType', + name: 'wp_navigation', + baseURL: '/wp/v2/navigation', + baseURLParams: { context: 'edit' }, + }, + ] ); + receiveEntityRecords( 'postType', 'wp_navigation', { + id: 1, + ...( meta ? { meta } : {} ), + } ); + receiveUserPermission( 'update/postType/wp_navigation/1', true ); + render( + + + + ); +} + +describe( 'AutoAddPagesControl', () => { + beforeEach( () => { + vi.mocked( apiFetch ).mockImplementation( + () => new Promise( () => {} ) + ); + } ); + + it( 'shows the setting saved with the menu', () => { + renderControl( { wp_navigation_auto_add_pages: true } ); + + expect( + screen.getByRole( 'switch', { name: 'Auto add new pages' } ) + ).toBeChecked(); + } ); + + it( 'renders nothing when the server has no such setting', () => { + // As in a WordPress release without the server side of the setting, + // where the REST API drops the meta on save. + renderControl( undefined ); + + expect( + screen.queryByRole( 'switch', { name: 'Auto add new pages' } ) + ).not.toBeInTheDocument(); + } ); +} ); diff --git a/packages/block-library/src/navigation/editor.scss b/packages/block-library/src/navigation/editor.scss index 14940f24fa5bf1..9922a87da1e781 100644 --- a/packages/block-library/src/navigation/editor.scss +++ b/packages/block-library/src/navigation/editor.scss @@ -626,6 +626,13 @@ body.editor-styles-wrapper .wp-block-navigation__responsive-container.is-menu-op margin-left: 24px; } +// The menu's own settings follow its items and their appender, set apart by a line. +.wp-block-navigation__auto-add-pages { + margin-top: $grid-unit-30; + padding-top: $grid-unit-30; + border-top: 1px solid var(--wpds-color-stroke-surface-neutral); +} + .editor-sidebar__panel .wp-block-navigation__submenu-header { margin-top: 0; margin-bottom: 0; diff --git a/packages/block-library/src/private-apis.ts b/packages/block-library/src/private-apis.ts index a7bee3d71c9e79..ad64436e1042cb 100644 --- a/packages/block-library/src/private-apis.ts +++ b/packages/block-library/src/private-apis.ts @@ -1,5 +1,6 @@ import { NAVIGATION_OVERLAY_TEMPLATE_PART_AREA } from './navigation/constants'; import { NavigationLinkUI } from './navigation/edit/navigation-link-ui'; +import AutoAddPagesControl from './navigation/edit/auto-add-pages-control'; import { AddSubmenuItem } from './navigation/edit/leaf-more-menu'; import { lock } from './lock-unlock'; @@ -10,5 +11,6 @@ export const privateApis = {}; lock( privateApis, { NAVIGATION_OVERLAY_TEMPLATE_PART_AREA, NavigationLinkUI, + AutoAddPagesControl, AddSubmenuItem, } ); diff --git a/packages/core-data/CHANGELOG.md b/packages/core-data/CHANGELOG.md index 519341508a4438..0b2037d14e2c3c 100644 --- a/packages/core-data/CHANGELOG.md +++ b/packages/core-data/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +### Enhancements + +- Invalidate the loaded `wp_navigation` records when a page publish is received, so a Navigation block picks up the link that "Auto add new pages" appended on the server without a reload ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). +- `getEntityRecord`: When a refetch brings content that changed on the server and the record has no unsaved changes, drop the blocks kept as an edit since its last save, so the editor shows the new content ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). + ### Bug Fixes - `getEntityRecord`: Don't request the entity configs when no entity name is given, such as when a Cover block outside a post reads the featured image ([#87388](https://github.com/WordPress/gutenberg/pull/87388)). diff --git a/packages/core-data/src/resolvers.ts b/packages/core-data/src/resolvers.ts index 568869e19b60a0..27e45f76426cac 100644 --- a/packages/core-data/src/resolvers.ts +++ b/packages/core-data/src/resolvers.ts @@ -2,6 +2,7 @@ import { camelCase } from 'change-case'; import { addQueryArgs } from '@wordpress/url'; import { decodeEntities } from '@wordpress/html-entities'; import apiFetch from '@wordpress/api-fetch'; +import { __unstableSerializeAndClean } from '@wordpress/blocks'; import type { Block } from '@wordpress/blocks'; import { STORE_NAME } from './name'; import { @@ -139,6 +140,20 @@ export const getEntityRecord = ...entityConfig.baseURLParams, ...query, } ); + // The record's saved content, as stored. Not every caller of the + // resolver provides `select` in tests. + const getSavedContent = () => + ( + select?.getRawEntityRecord( kind, name, key ) as + { content?: unknown } | undefined + )?.content; + // A save that lands while the request is out stores content newer + // than the response carries. + const savedContentBeforeFetch = + ! query && entityConfig.transientEdits + ? getSavedContent() + : undefined; + const response = await apiFetch( { path, parse: false } ); const record: RestRecord = await response.json(); const permissions = getUserPermissionsFromAllowHeader( @@ -268,7 +283,48 @@ export const getEntityRecord = } ); } + // After a save, the blocks parsed from a record's content stay as + // a transient edit, and the editor shows them in place of the + // content. A refetch can bring content changed on the server, as + // when publishing a page adds a link to a Navigation Menu, so drop + // those edits and let the editor parse the new content, but only + // when the blocks hold nothing beyond the saved content. Typing + // that continues in the same attribute after a save changes only + // the blocks, and must not be lost. Nor must a save that landed + // while the request was out. + const fetchedContent = ( + record.content as { raw?: unknown } | undefined + )?.raw; + const getTransientBlocks = () => + select?.getEntityRecordEdits( kind, name, key )?.blocks as + Block[] | undefined; + const shouldDropTransientEdits = + ! query && + !! entityConfig.transientEdits && + typeof fetchedContent === 'string' && + Array.isArray( getTransientBlocks() ) && + ! select.hasEditsForEntityRecord( kind, name, key ) && + typeof getSavedContent() === 'string' && + getSavedContent() === savedContentBeforeFetch && + getSavedContent() !== fetchedContent && + __unstableSerializeAndClean( getTransientBlocks()! ) === + getSavedContent(); + registry.batch( () => { + if ( shouldDropTransientEdits ) { + dispatch( { + type: 'EDIT_ENTITY_RECORD', + kind, + name, + recordId: key, + edits: Object.fromEntries( + Object.keys( + entityConfig.transientEdits ?? {} + ).map( ( edit ) => [ edit, undefined ] ) + ), + meta: { undo: undefined }, + } ); + } dispatch.receiveEntityRecords( kind, name, record, query ); dispatch.receiveUserPermissions( receiveUserPermissionArgs ); dispatch.finishResolutions( 'canUser', canUserResolutionsArgs ); @@ -278,26 +334,40 @@ export const getEntityRecord = } }; -// Whenever a template is saved, the active templates might be updated, so -// invalidate the site settings when a template is updated or deleted. getEntityRecord.shouldInvalidate = ( action: Action, kind: string, name: string ) => { - return ( - kind === 'root' && - name === 'site' && - ( ( action.type === 'RECEIVE_ITEMS' && - // Making sure persistedEdits is set seems to be the only way of - // knowing whether it's an update or fetch. Only an update would - // have persistedEdits. - action.persistedEdits && - action.persistedEdits.status !== 'auto-draft' ) || - action.type === 'REMOVE_ITEMS' ) && - action.kind === 'postType' && - action.name === 'wp_template' - ); + // Whenever a template is saved, the active templates might be updated, so + // invalidate the site settings when a template is updated or deleted. + if ( kind === 'root' && name === 'site' ) { + return ( + ( ( action.type === 'RECEIVE_ITEMS' && + // Making sure persistedEdits is set seems to be the only way of + // knowing whether it's an update or fetch. Only an update would + // have persistedEdits. + action.persistedEdits && + action.persistedEdits.status !== 'auto-draft' ) || + action.type === 'REMOVE_ITEMS' ) && + action.kind === 'postType' && + action.name === 'wp_template' + ); + } + + // Publishing a page appends a link to every Navigation Menu with "Auto add + // pages" switched on, so the menus held in the store are stale as soon as + // the page save is received. + if ( kind === 'postType' && name === 'wp_navigation' ) { + return ( + action.type === 'RECEIVE_ITEMS' && + action.kind === 'postType' && + action.name === 'page' && + action.persistedEdits?.status === 'publish' + ); + } + + return false; }; /** diff --git a/packages/core-data/src/test/resolvers.jsdom.test.ts b/packages/core-data/src/test/resolvers.jsdom.test.ts index f88a1a4f464192..7927de5f3521ae 100644 --- a/packages/core-data/src/test/resolvers.jsdom.test.ts +++ b/packages/core-data/src/test/resolvers.jsdom.test.ts @@ -1,5 +1,18 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { + afterAll, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from 'vitest'; import triggerFetch from '@wordpress/api-fetch'; +import { + createBlock, + registerBlockType, + unregisterBlockType, +} from '@wordpress/blocks'; import type { Mock } from 'vitest'; import { getEntitySyncManager } from '../entity-sync'; import { @@ -450,6 +463,202 @@ describe( 'getEntityRecord', () => { ).not.toHaveBeenCalled(); expect( triggerFetch ).not.toHaveBeenCalled(); } ); + + describe( 'a refetch of a record whose blocks are held as an edit', () => { + const MENU_ENTITIES = [ + { + name: 'wp_navigation', + kind: 'postType', + baseURL: '/wp/v2/navigation', + baseURLParams: { context: 'edit' }, + transientEdits: { blocks: true, selection: true }, + }, + ]; + const dropEditsAction = { + type: 'EDIT_ENTITY_RECORD', + kind: 'postType', + name: 'wp_navigation', + recordId: 1, + edits: { blocks: undefined, selection: undefined }, + meta: { undo: undefined }, + }; + const SAVED_CONTENT = ''; + + beforeAll( () => { + registerBlockType( 'test/link', { + apiVersion: 3, + title: 'Test Link', + category: 'text', + attributes: { label: { type: 'string' } }, + save: () => null, + } ); + } ); + + afterAll( () => { + unregisterBlockType( 'test/link' ); + } ); + + async function refetch( { + storedContent = SAVED_CONTENT, + storedContentBeforeFetch = storedContent, + fetchedContent, + hasUnsavedChanges = false, + label = 'Home', + }: { + storedContent?: string; + // The stored content when the request goes out, if a save + // changes it while the request is out. + storedContentBeforeFetch?: string; + fetchedContent: string; + hasUnsavedChanges?: boolean; + // The label in the blocks held as an edit. + label?: string; + } ) { + let hasFetched = false; + apiFetchMock.mockImplementation( () => { + hasFetched = true; + return { + json: () => + Promise.resolve( { + id: 1, + content: { raw: fetchedContent }, + } ), + }; + } ); + const select = { + getRawEntityRecord: vi.fn( () => ( { + id: 1, + content: hasFetched + ? storedContent + : storedContentBeforeFetch, + } ) ), + getEntityRecordEdits: vi.fn( () => ( { + blocks: [ createBlock( 'test/link', { label } ) ], + selection: {}, + } ) ), + hasEditsForEntityRecord: vi.fn( () => hasUnsavedChanges ), + }; + await getEntityRecord( + 'postType', + 'wp_navigation', + 1 + )( + thunkArgs( { + dispatch, + registry, + select, + resolveSelect: { + getEntityConfig: mockEntityConfig( MENU_ENTITIES ), + getEditedEntityRecord: vi.fn(), + }, + } ) + ); + } + + it( 'drops the blocks when the content changed on the server and nothing is unsaved', async () => { + await refetch( { + fetchedContent: SAVED_CONTENT + SAVED_CONTENT, + } ); + + expect( dispatch ).toHaveBeenCalledWith( dropEditsAction ); + // Dropped before the new record arrives, so the editor parses it. + expect( + dispatch.mock.invocationCallOrder[ + dispatch.mock.calls.findIndex( + ( [ action ] ) => action?.type === 'EDIT_ENTITY_RECORD' + ) + ] + ).toBeLessThan( + dispatch.receiveEntityRecords.mock.invocationCallOrder[ 0 ] + ); + } ); + + it( 'keeps the blocks when there are unsaved changes', async () => { + await refetch( { + fetchedContent: SAVED_CONTENT + SAVED_CONTENT, + hasUnsavedChanges: true, + } ); + + expect( dispatch ).not.toHaveBeenCalledWith( dropEditsAction ); + } ); + + it( 'keeps the blocks when they hold typing that was not saved', async () => { + // Typing that continues in the same attribute after a save only + // changes the blocks, which are a transient edit, so the record + // doesn't count as changed. + await refetch( { + fetchedContent: SAVED_CONTENT + SAVED_CONTENT, + label: 'Home page', + } ); + + expect( dispatch ).not.toHaveBeenCalledWith( dropEditsAction ); + } ); + + it( 'keeps the blocks when a save changed the content while the request was out', async () => { + // A save that lands while the request is out stores newer content + // than the response carries. + const newerContent = ''; + await refetch( { + storedContentBeforeFetch: SAVED_CONTENT, + storedContent: newerContent, + fetchedContent: SAVED_CONTENT + SAVED_CONTENT, + label: 'Home page', + } ); + + expect( dispatch ).not.toHaveBeenCalledWith( dropEditsAction ); + } ); + + it( 'keeps the blocks when the content is unchanged', async () => { + await refetch( { + fetchedContent: SAVED_CONTENT, + } ); + + expect( dispatch ).not.toHaveBeenCalledWith( dropEditsAction ); + } ); + } ); +} ); + +describe( 'getEntityRecord.shouldInvalidate', () => { + const receivePage = ( persistedEdits?: Record< string, unknown > ) => ( { + type: 'RECEIVE_ITEMS', + kind: 'postType', + name: 'page', + items: [ { id: 2 } ], + persistedEdits, + } ); + const shouldInvalidateMenus = ( action: unknown ) => + getEntityRecord.shouldInvalidate( + action as Parameters< + typeof getEntityRecord.shouldInvalidate + >[ 0 ], + 'postType', + 'wp_navigation' + ); + + it( 'invalidates menus when a page is published', () => { + expect( + shouldInvalidateMenus( receivePage( { status: 'publish' } ) ) + ).toBe( true ); + } ); + + it( 'leaves menus alone when a page is fetched or saved without publishing', () => { + expect( shouldInvalidateMenus( receivePage() ) ).toBe( false ); + expect( + shouldInvalidateMenus( receivePage( { status: 'draft' } ) ) + ).toBe( false ); + expect( + shouldInvalidateMenus( receivePage( { title: 'Renamed' } ) ) + ).toBe( false ); + } ); + + it( 'leaves menus alone when another post type is published', () => { + expect( + shouldInvalidateMenus( { + ...receivePage( { status: 'publish' } ), + name: 'post', + } ) + ).toBe( false ); + } ); } ); describe( 'getEntityRecords', () => { diff --git a/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/index.jsx b/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/index.jsx index 65e50a7ff15f39..bddad37733994b 100644 --- a/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/index.jsx +++ b/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/index.jsx @@ -40,7 +40,10 @@ export default function SidebarNavigationScreenNavigationMenu( { backPath } ) { [ postId ] ); - const isLoading = isResolving || isSaving || isDeleting; + // A menu fetched again, as after a page publish adds a link to it, keeps + // the screen in place rather than swapping it for a spinner. + const isLoading = + ( isResolving && ! navigationMenu ) || isSaving || isDeleting; const { handleSave, handleDelete, handleDuplicate } = useNavigationMenuHandlers(); diff --git a/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/single-navigation-menu.jsx b/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/single-navigation-menu.jsx index 03c9c97aba84a7..86126077f8dfd3 100644 --- a/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/single-navigation-menu.jsx +++ b/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/single-navigation-menu.jsx @@ -1,10 +1,16 @@ import { __ } from '@wordpress/i18n'; import { decodeEntities } from '@wordpress/html-entities'; +import { privateApis as blockLibraryPrivateApis } from '@wordpress/block-library'; +import { unlock } from '../../lock-unlock'; import { SidebarNavigationScreenWrapper } from '../sidebar-navigation-screen-navigation-menus'; import ScreenNavigationMoreMenu from './more-menu'; import NavigationMenuEditor from './navigation-menu-editor'; import buildNavigationLabel from '../sidebar-navigation-screen-navigation-menus/build-navigation-label'; +const { AutoAddPagesControl } = unlock( blockLibraryPrivateApis ); + +const AUTO_ADD_PAGES_META_KEY = 'wp_navigation_auto_add_pages'; + export default function SingleNavigationMenu( { navigationMenu, backPath, @@ -13,6 +19,11 @@ export default function SingleNavigationMenu( { handleSave, } ) { const menuTitle = navigationMenu?.title?.rendered; + // The REST API lists every registered meta key, so a WordPress release + // without the setting's server side leaves it out, and the footer with it. + const hasAutoAddPagesSetting = + !! navigationMenu?.meta && + AUTO_ADD_PAGES_META_KEY in navigationMenu.meta; return ( + ) + } > diff --git a/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/test/single-navigation-menu.jsdom.test.ts b/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/test/single-navigation-menu.jsdom.test.ts new file mode 100644 index 00000000000000..f6655db032fe83 --- /dev/null +++ b/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/test/single-navigation-menu.jsdom.test.ts @@ -0,0 +1,88 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { ReactNode } from 'react'; +import { createElement, createRoot, flushSync } from '@wordpress/element'; +import SingleNavigationMenu from '../single-navigation-menu'; + +// The screen's own parts, which need the site editor around them. +vi.mock( import( '../../sidebar-navigation-screen-navigation-menus' ), () => ( { + SidebarNavigationScreenWrapper: ( { + footer, + children, + }: { + footer?: ReactNode; + children?: ReactNode; + } ) => + createElement( + 'div', + null, + children, + footer ? createElement( 'footer', null, footer ) : null + ), +} ) ); +vi.mock( import( '../more-menu' ), () => ( { default: vi.fn() } ) ); +vi.mock( import( '../navigation-menu-editor' ), () => ( { + default: vi.fn(), +} ) ); +vi.mock( import( '@wordpress/block-library' ), () => ( { privateApis: {} } ) ); +vi.mock( import( '../../../lock-unlock' ), () => ( { + unlock: vi.fn().mockReturnValue( { + AutoAddPagesControl: () => + createElement( 'span', null, 'Auto add new pages' ), + } ), +} ) ); + +const roots: ReturnType< typeof createRoot >[] = []; + +function renderScreen( navigationMenu: Record< string, unknown > ) { + const container = document.createElement( 'div' ); + document.body.append( container ); + const root = createRoot( container ); + roots.push( root ); + flushSync( () => + root.render( + createElement( SingleNavigationMenu, { + navigationMenu, + backPath: '/navigation', + handleDelete: vi.fn(), + handleDuplicate: vi.fn(), + handleSave: vi.fn(), + } ) + ) + ); +} + +describe( 'SingleNavigationMenu', () => { + beforeEach( () => { + // Renders are flushed directly, without act(). + ( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } + ).IS_REACT_ACT_ENVIRONMENT = false; + } ); + + afterEach( () => { + roots.splice( 0 ).forEach( ( root ) => root.unmount() ); + document.body.replaceChildren(); + } ); + + it( 'shows the setting in the footer when the menu has it', () => { + renderScreen( { + id: 1, + title: { rendered: 'Menu' }, + meta: { wp_navigation_auto_add_pages: false }, + } ); + + expect( document.querySelector( 'footer' ) ).not.toBeNull(); + } ); + + it( 'leaves out the footer when the server has no such setting', () => { + // As in a WordPress release without the server side of the setting. + renderScreen( { id: 1, title: { rendered: 'Menu' } } ); + renderScreen( { + id: 2, + title: { rendered: 'Menu' }, + meta: { footnotes: '' }, + } ); + + expect( document.querySelector( 'footer' ) ).toBeNull(); + } ); +} ); diff --git a/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/use-navigation-menu-handlers.js b/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/use-navigation-menu-handlers.js index 026fbdf534948f..211115c5998213 100644 --- a/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/use-navigation-menu-handlers.js +++ b/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/use-navigation-menu-handlers.js @@ -148,6 +148,10 @@ function useDuplicateNavigationMenu() { ), content: navigationMenu?.content?.raw, status: 'publish', + meta: { + wp_navigation_auto_add_pages: + navigationMenu?.meta?.wp_navigation_auto_add_pages, + }, }, { throwOnError: true, diff --git a/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menus/index.jsx b/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menus/index.jsx index 57631e77bfff0d..ea0274abce7649 100644 --- a/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menus/index.jsx +++ b/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menus/index.jsx @@ -130,6 +130,7 @@ export function SidebarNavigationScreenWrapper( { title, description, backPath, + footer, } ) { return ( ); } diff --git a/phpunit/navigation-auto-add-pages-test.php b/phpunit/navigation-auto-add-pages-test.php new file mode 100644 index 00000000000000..ac93ac3f765abc --- /dev/null +++ b/phpunit/navigation-auto-add-pages-test.php @@ -0,0 +1,781 @@ +user->create( array( 'role' => 'administrator' ) ); + if ( is_multisite() ) { + grant_super_admin( self::$admin_id ); + } + } + + public static function wpTearDownAfterClass() { + self::delete_user( self::$admin_id ); + } + + public function set_up() { + parent::set_up(); + // The test framework unregisters every meta key after each test. + gutenberg_register_navigation_auto_add_pages_meta(); + // Content is saved unfiltered, as by an administrator, unless a test + // turns kses on. + kses_remove_filters(); + } + + public function tear_down() { + $this->delete_all_posts_of_type( 'wp_navigation' ); + $this->delete_all_posts_of_type( 'page' ); + $this->delete_all_posts_of_type( 'post' ); + parent::tear_down(); + } + + private function delete_all_posts_of_type( $post_type ) { + $posts = get_posts( + array( + 'post_type' => $post_type, + 'post_status' => 'any', + 'posts_per_page' => -1, + 'fields' => 'ids', + ) + ); + foreach ( $posts as $post_id ) { + wp_delete_post( $post_id, true ); + } + } + + private function create_menu( $content, $auto_add = null ) { + $menu_id = self::factory()->post->create( + array( + 'post_type' => 'wp_navigation', + 'post_status' => 'publish', + 'post_title' => 'Menu', + 'post_content' => wp_slash( $content ), + ) + ); + if ( null !== $auto_add ) { + update_post_meta( $menu_id, self::META_KEY, $auto_add ); + } + return $menu_id; + } + + private function get_menu_blocks( $menu_id ) { + $blocks = parse_blocks( get_post( $menu_id )->post_content ); + return array_values( + array_filter( + $blocks, + static function ( $block ) { + return null !== $block['blockName']; + } + ) + ); + } + + private function publish_new_page( $args = array() ) { + $page_id = self::factory()->post->create( + array_merge( + array( + 'post_type' => 'page', + 'post_status' => 'draft', + 'post_title' => 'New Page', + ), + $args + ) + ); + wp_publish_post( $page_id ); + return $page_id; + } + + /** + * Logs in an Editor who can publish pages but can't post unfiltered HTML, + * as on multisite or with `DISALLOW_UNFILTERED_HTML`, and turns kses on. + * + * @return callable The `map_meta_cap` filter, to remove after the test. + */ + private function log_in_editor_without_unfiltered_html() { + $deny_unfiltered_html = static function ( $caps, $cap ) { + return 'unfiltered_html' === $cap ? array( 'do_not_allow' ) : $caps; + }; + add_filter( 'map_meta_cap', $deny_unfiltered_html, 10, 2 ); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'editor' ) ) ); + kses_init(); + return $deny_unfiltered_html; + } + + /** + * A menu item whose label and URL hold markup and an ampersand, which + * kses would strip or encode. + * + * @return string Serialized Navigation Link block. + */ + private function link_with_markup() { + return serialize_block( + array( + 'blockName' => 'core/navigation-link', + 'attrs' => array( + 'label' => ' Home', + 'url' => 'https://example.com/?a=1&b=2', + 'kind' => 'custom', + ), + 'innerBlocks' => array(), + 'innerHTML' => '', + 'innerContent' => array(), + ) + ); + } + + private function page_link_markup( $page_id ) { + return sprintf( + '', + get_the_title( $page_id ), + $page_id, + get_permalink( $page_id ) + ); + } + + private function get_labels( $blocks ) { + return array_map( + static function ( $block ) { + return $block['attrs']['label']; + }, + $blocks + ); + } + + private function assert_page_link_block( $block, $page_id ) { + $page = get_post( $page_id ); + $this->assertSame( 'core/navigation-link', $block['blockName'] ); + $this->assertSame( $page_id, $block['attrs']['id'] ); + $this->assertSame( $page->post_title, $block['attrs']['label'] ); + $this->assertSame( get_permalink( $page ), $block['attrs']['url'] ); + $this->assertSame( 'page', $block['attrs']['type'] ); + $this->assertSame( 'post-type', $block['attrs']['kind'] ); + $this->assertSame( + array( + 'url' => array( + 'source' => 'core/post-data', + 'args' => array( 'field' => 'link' ), + ), + ), + $block['attrs']['metadata']['bindings'] + ); + } + + /* + * Meta registration. + */ + + public function test_meta_is_registered_as_boolean_for_rest() { + $registered = get_registered_meta_keys( 'post', 'wp_navigation' ); + + $this->assertArrayHasKey( self::META_KEY, $registered ); + $this->assertSame( 'boolean', $registered[ self::META_KEY ]['type'] ); + $this->assertTrue( $registered[ self::META_KEY ]['single'] ); + $this->assertNotEmpty( $registered[ self::META_KEY ]['show_in_rest'] ); + $this->assertFalse( $registered[ self::META_KEY ]['default'] ); + $this->assertTrue( post_type_supports( 'wp_navigation', 'custom-fields' ) ); + } + + public function test_meta_is_readable_and_writable_through_rest() { + wp_set_current_user( self::$admin_id ); + $menu_id = $this->create_menu( '' ); + + $request = new WP_REST_Request( 'GET', '/wp/v2/navigation/' . $menu_id ); + $request->set_param( 'context', 'edit' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertSame( 200, $response->get_status() ); + $this->assertFalse( $response->get_data()['meta'][ self::META_KEY ] ); + + $request = new WP_REST_Request( 'POST', '/wp/v2/navigation/' . $menu_id ); + $request->set_body_params( array( 'meta' => array( self::META_KEY => true ) ) ); + $response = rest_get_server()->dispatch( $request ); + $this->assertSame( 200, $response->get_status() ); + $this->assertTrue( $response->get_data()['meta'][ self::META_KEY ] ); + $this->assertTrue( (bool) get_post_meta( $menu_id, self::META_KEY, true ) ); + } + + /* + * Auto add on publish. + */ + + public function test_publishing_a_top_level_page_appends_a_link_to_a_menu_with_the_setting_on() { + $menu_id = $this->create_menu( + '', + true + ); + + $page_id = $this->publish_new_page( array( 'post_title' => 'About us' ) ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertCount( 2, $blocks ); + $this->assertSame( 'Home', $blocks[0]['attrs']['label'], 'Existing items are left in place.' ); + $this->assert_page_link_block( $blocks[1], $page_id ); + } + + public function test_a_menu_with_the_setting_off_or_missing_is_untouched() { + $content = ''; + $off_id = $this->create_menu( $content, false ); + $unset_id = $this->create_menu( $content ); + + $this->publish_new_page(); + + $this->assertSame( $content, get_post( $off_id )->post_content ); + $this->assertSame( $content, get_post( $unset_id )->post_content ); + } + + public function test_a_page_already_in_the_menu_is_not_added_twice() { + $page_id = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_status' => 'draft', + ) + ); + // Nested inside a submenu, to prove the check is recursive. + $content = sprintf( + '', + $page_id + ); + $menu_id = $this->create_menu( $content, true ); + + wp_publish_post( $page_id ); + + $this->assertSame( $content, get_post( $menu_id )->post_content ); + } + + public function test_other_post_types_and_republished_pages_are_ignored() { + $menu_id = $this->create_menu( '', true ); + + $parent_id = $this->publish_new_page( array( 'post_title' => 'Parent' ) ); + $this->assertCount( 1, $this->get_menu_blocks( $menu_id ), 'The top-level parent is added.' ); + + $post_id = self::factory()->post->create( array( 'post_status' => 'draft' ) ); + wp_publish_post( $post_id ); + $this->assertCount( 1, $this->get_menu_blocks( $menu_id ), 'A post is not added.' ); + + wp_update_post( + array( + 'ID' => $parent_id, + 'post_title' => 'Parent renamed', + ) + ); + $this->assertCount( 1, $this->get_menu_blocks( $menu_id ), 'Updating a published page adds nothing.' ); + } + + public function test_a_scheduled_page_is_added_when_it_publishes() { + $menu_id = $this->create_menu( '', true ); + $page_id = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_status' => 'future', + 'post_date' => gmdate( 'Y-m-d H:i:s', time() + DAY_IN_SECONDS ), + ) + ); + $this->assertCount( 0, $this->get_menu_blocks( $menu_id ), 'Scheduling alone adds nothing.' ); + + // `check_and_publish_future_post()` refuses to publish before the scheduled + // time, so call what it calls once the time arrives. + wp_publish_post( $page_id ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertCount( 1, $blocks ); + $this->assert_page_link_block( $blocks[0], $page_id ); + } + + public function test_every_menu_with_the_setting_on_receives_the_link() { + $first_id = $this->create_menu( '', true ); + $second_id = $this->create_menu( '', true ); + + $page_id = $this->publish_new_page(); + + $this->assert_page_link_block( $this->get_menu_blocks( $first_id )[0], $page_id ); + $this->assert_page_link_block( $this->get_menu_blocks( $second_id )[0], $page_id ); + } + + public function test_a_page_published_by_a_user_without_unfiltered_html_is_added() { + $menu_id = $this->create_menu( '', true ); + $filter = $this->log_in_editor_without_unfiltered_html(); + + $page_id = $this->publish_new_page( array( 'post_title' => 'Terms & "Conditions"' ) ); + kses_remove_filters(); + remove_filter( 'map_meta_cap', $filter, 10 ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertCount( 1, $blocks ); + $this->assert_page_link_block( $blocks[0], $page_id ); + } + + public function test_a_page_published_by_a_user_without_unfiltered_html_leaves_the_menus_markup_alone() { + // The menu was saved by someone allowed to post unfiltered HTML. A + // page published by someone who isn't must not filter it again. + $menu_id = $this->create_menu( $this->link_with_markup(), true ); + $before = $this->get_menu_blocks( $menu_id ); + $this->assertStringStartsWith( 'log_in_editor_without_unfiltered_html(); + + $page_id = $this->publish_new_page( array( 'post_title' => 'Contact' ) ); + kses_remove_filters(); + remove_filter( 'map_meta_cap', $filter, 10 ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertCount( 2, $blocks ); + $this->assertSame( $before[0], $blocks[0] ); + $this->assert_page_link_block( $blocks[1], $page_id ); + } + + public function test_publishing_leaves_the_kses_filters_as_they_were() { + $this->create_menu( $this->link_with_markup(), true ); + $filter = $this->log_in_editor_without_unfiltered_html(); + // A site that lets this user keep markup in titles. + remove_filter( 'title_save_pre', 'wp_filter_kses' ); + + $this->publish_new_page( array( 'post_title' => 'Contact' ) ); + $content_filter = has_filter( 'content_save_pre', 'wp_filter_post_kses' ); + $title_filter = has_filter( 'title_save_pre', 'wp_filter_kses' ); + kses_remove_filters(); + remove_filter( 'map_meta_cap', $filter, 10 ); + + $this->assertSame( 10, $content_filter ); + $this->assertFalse( $title_filter ); + } + + public function test_a_page_published_by_a_user_without_unfiltered_html_leaves_the_menu_title_alone() { + $menu_id = self::factory()->post->create( + array( + 'post_type' => 'wp_navigation', + 'post_status' => 'publish', + 'post_title' => 'Products & Services', + ) + ); + update_post_meta( $menu_id, self::META_KEY, true ); + $filter = $this->log_in_editor_without_unfiltered_html(); + + $this->publish_new_page( array( 'post_title' => 'Contact' ) ); + kses_remove_filters(); + remove_filter( 'map_meta_cap', $filter, 10 ); + + $this->assertSame( 'Products & Services', get_post( $menu_id )->post_title ); + $this->assertCount( 1, $this->get_menu_blocks( $menu_id ) ); + } + + public function test_the_new_link_label_is_filtered_when_the_publisher_cannot_post_unfiltered_html() { + $menu_id = $this->create_menu( '', true ); + $page_id = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_status' => 'draft', + 'post_title' => 'Offers', + ) + ); + // A title kses didn't filter, as when an administrator saved it. + $title = 'Offers'; + $GLOBALS['wpdb']->update( $GLOBALS['wpdb']->posts, array( 'post_title' => $title ), array( 'ID' => $page_id ) ); + clean_post_cache( $page_id ); + $filter = $this->log_in_editor_without_unfiltered_html(); + + wp_publish_post( $page_id ); + kses_remove_filters(); + remove_filter( 'map_meta_cap', $filter, 10 ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertCount( 1, $blocks ); + $this->assertStringNotContainsString( 'assertSame( wp_kses_post( $title ), $blocks[0]['attrs']['label'] ); + } + + public function test_a_page_published_with_no_current_user_is_added_with_its_title_intact() { + // A scheduled page publishes from cron, where there is no user and + // kses filters the menu content on save. + $menu_id = $this->create_menu( $this->link_with_markup(), true ); + $before = $this->get_menu_blocks( $menu_id ); + $this->assertStringStartsWith( 'publish_new_page( array( 'post_title' => 'Tom & Jerry\'s "Day"' ) ); + kses_remove_filters(); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertCount( 2, $blocks ); + $this->assertSame( $before[0], $blocks[0] ); + $this->assert_page_link_block( $blocks[1], $page_id ); + } + + /* + * Child pages. + */ + + public function test_a_child_page_turns_its_parent_link_into_a_submenu() { + $parent_id = $this->publish_new_page( array( 'post_title' => 'Parent' ) ); + $content = sprintf( + '', + $parent_id, + get_permalink( $parent_id ) + ); + $menu_id = $this->create_menu( $content, true ); + + $child_id = $this->publish_new_page( + array( + 'post_title' => 'Child', + 'post_parent' => $parent_id, + ) + ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertCount( 2, $blocks, 'The child is not added at the top level.' ); + $this->assertSame( 'Home', $blocks[0]['attrs']['label'] ); + + $parent = $blocks[1]; + $this->assertSame( 'core/navigation-submenu', $parent['blockName'], 'The parent link becomes a submenu.' ); + $this->assertSame( $parent_id, $parent['attrs']['id'] ); + $this->assertSame( 'Parent', $parent['attrs']['label'] ); + $this->assertSame( 'page', $parent['attrs']['type'] ); + $this->assertSame( 'post-type', $parent['attrs']['kind'] ); + $this->assertTrue( $parent['attrs']['opensInNewTab'], 'The parent link keeps its attributes.' ); + $this->assertSame( 'nofollow', $parent['attrs']['rel'], 'The parent link keeps its attributes.' ); + + $this->assertCount( 1, $parent['innerBlocks'] ); + $this->assert_page_link_block( $parent['innerBlocks'][0], $child_id ); + } + + public function test_a_child_page_is_appended_to_an_existing_parent_submenu() { + $parent_id = $this->publish_new_page( array( 'post_title' => 'Parent' ) ); + $content = sprintf( + '', + $parent_id, + get_permalink( $parent_id ) + ); + $menu_id = $this->create_menu( $content, true ); + + $child_id = $this->publish_new_page( + array( + 'post_title' => 'Child', + 'post_parent' => $parent_id, + ) + ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertCount( 1, $blocks ); + $this->assertSame( 'core/navigation-submenu', $blocks[0]['blockName'] ); + $this->assertCount( 2, $blocks[0]['innerBlocks'] ); + $this->assertSame( 'Existing', $blocks[0]['innerBlocks'][0]['attrs']['label'], 'Existing items are left in place.' ); + $this->assert_page_link_block( $blocks[0]['innerBlocks'][1], $child_id ); + } + + public function test_a_grandchild_page_nests_under_its_parent_inside_a_submenu() { + $grandparent_id = $this->publish_new_page( array( 'post_title' => 'Grandparent' ) ); + $parent_id = $this->publish_new_page( + array( + 'post_title' => 'Parent', + 'post_parent' => $grandparent_id, + ) + ); + $content = sprintf( + '', + $grandparent_id, + get_permalink( $grandparent_id ), + $parent_id, + get_permalink( $parent_id ) + ); + $menu_id = $this->create_menu( $content, true ); + + $child_id = $this->publish_new_page( + array( + 'post_title' => 'Child', + 'post_parent' => $parent_id, + ) + ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertCount( 1, $blocks ); + $this->assertCount( 1, $blocks[0]['innerBlocks'] ); + + $parent = $blocks[0]['innerBlocks'][0]; + $this->assertSame( 'core/navigation-submenu', $parent['blockName'] ); + $this->assertSame( $parent_id, $parent['attrs']['id'] ); + $this->assertCount( 1, $parent['innerBlocks'] ); + $this->assert_page_link_block( $parent['innerBlocks'][0], $child_id ); + } + + public function test_a_child_page_whose_parent_is_not_in_the_menu_is_skipped() { + $parent_id = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_status' => 'publish', + 'post_title' => 'Parent', + ) + ); + // A custom link to the parent's URL does not count: only a link to the page itself does. + $content = sprintf( + '', + get_permalink( $parent_id ) + ); + $menu_id = $this->create_menu( $content, true ); + + $this->publish_new_page( + array( + 'post_title' => 'Child', + 'post_parent' => $parent_id, + ) + ); + + $this->assertSame( $content, get_post( $menu_id )->post_content ); + } + + /* + * Where a page is added. + */ + + public function test_a_page_is_inserted_in_page_order_among_the_page_links() { + $about_id = $this->publish_new_page( + array( + 'post_title' => 'About', + 'menu_order' => 1, + ) + ); + $team_id = $this->publish_new_page( + array( + 'post_title' => 'Team', + 'menu_order' => 5, + ) + ); + $menu_id = $this->create_menu( + '' . + $this->page_link_markup( $about_id ) . + '' . + $this->page_link_markup( $team_id ), + true + ); + + $this->publish_new_page( + array( + 'post_title' => 'Pricing', + 'menu_order' => 3, + ) + ); + + $this->assertSame( + array( 'Home', 'About', 'Shop', 'Pricing', 'Team' ), + $this->get_labels( $this->get_menu_blocks( $menu_id ) ) + ); + } + + public function test_a_page_that_sorts_last_goes_after_the_last_page_link() { + $about_id = $this->publish_new_page( + array( + 'post_title' => 'About', + 'menu_order' => 1, + ) + ); + $menu_id = $this->create_menu( + $this->page_link_markup( $about_id ) . + '', + true + ); + + $this->publish_new_page( + array( + 'post_title' => 'Team', + 'menu_order' => 5, + ) + ); + + $this->assertSame( + array( 'About', 'Team', 'Contact' ), + $this->get_labels( $this->get_menu_blocks( $menu_id ) ) + ); + } + + public function test_pages_with_the_same_order_are_sorted_by_title() { + $alpha_id = $this->publish_new_page( array( 'post_title' => 'Alpha' ) ); + $charlie_id = $this->publish_new_page( array( 'post_title' => 'Charlie' ) ); + $menu_id = $this->create_menu( + $this->page_link_markup( $alpha_id ) . $this->page_link_markup( $charlie_id ), + true + ); + + $this->publish_new_page( array( 'post_title' => 'Bravo' ) ); + + $this->assertSame( + array( 'Alpha', 'Bravo', 'Charlie' ), + $this->get_labels( $this->get_menu_blocks( $menu_id ) ) + ); + } + + public function test_titles_with_accents_sort_as_the_page_list_sorts_them() { + $zebra_id = $this->publish_new_page( array( 'post_title' => 'Zebra' ) ); + $menu_id = $this->create_menu( $this->page_link_markup( $zebra_id ), true ); + + $this->publish_new_page( array( 'post_title' => 'Éclair' ) ); + + $this->assertSame( + array( 'Éclair', 'Zebra' ), + $this->get_labels( $this->get_menu_blocks( $menu_id ) ) + ); + } + + public function test_a_child_page_is_inserted_in_page_order_within_its_parent_submenu() { + $parent_id = $this->publish_new_page( array( 'post_title' => 'Parent' ) ); + $first_id = $this->publish_new_page( + array( + 'post_title' => 'First', + 'post_parent' => $parent_id, + 'menu_order' => 1, + ) + ); + $third_id = $this->publish_new_page( + array( + 'post_title' => 'Third', + 'post_parent' => $parent_id, + 'menu_order' => 3, + ) + ); + $menu_id = $this->create_menu( + sprintf( + '%s%s', + $parent_id, + get_permalink( $parent_id ), + $this->page_link_markup( $first_id ), + $this->page_link_markup( $third_id ) + ), + true + ); + + $this->publish_new_page( + array( + 'post_title' => 'Second', + 'post_parent' => $parent_id, + 'menu_order' => 2, + ) + ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertSame( + array( 'First', 'Second', 'Third' ), + $this->get_labels( $blocks[0]['innerBlocks'] ) + ); + } + + public function test_a_page_list_limited_to_one_parent_page_does_not_stop_other_pages() { + $services_id = $this->publish_new_page( array( 'post_title' => 'Services' ) ); + $menu_id = $this->create_menu( + sprintf( + '', + $services_id + ), + true + ); + + $page_id = $this->publish_new_page( array( 'post_title' => 'Contact' ) ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertCount( 3, $blocks ); + $this->assert_page_link_block( $blocks[2], $page_id ); + } + + public function test_a_page_shown_by_a_page_list_limited_to_its_ancestor_is_not_added() { + $services_id = $this->publish_new_page( array( 'post_title' => 'Services' ) ); + $consulting_id = $this->publish_new_page( + array( + 'post_title' => 'Consulting', + 'post_parent' => $services_id, + ) + ); + // The Page List shows every page under Services, and the menu also + // links to Services and Consulting, so without the Page List the new + // pages would be nested under those links. + $content = sprintf( + '%3$s', + $services_id, + get_permalink( $services_id ), + $this->page_link_markup( $consulting_id ) + ); + $menu_id = $this->create_menu( $content, true ); + + $this->publish_new_page( + array( + 'post_title' => 'Design', + 'post_parent' => $services_id, + ) + ); + $this->publish_new_page( + array( + 'post_title' => 'Strategy', + 'post_parent' => $consulting_id, + ) + ); + + $this->assertSame( $content, get_post( $menu_id )->post_content ); + } + + public function test_a_page_list_with_an_invalid_parent_page_shows_all_pages() { + // The block falls back to its default, 0, for a value that isn't an + // integer, and then shows every page. + $content = ''; + $menu_id = $this->create_menu( $content, true ); + + $this->publish_new_page(); + + $this->assertSame( $content, get_post( $menu_id )->post_content ); + } + + public function test_a_child_of_an_unpublished_page_is_not_left_to_the_page_list() { + // The Page List lists published pages under published parents, so it + // doesn't show a child of a private page. The menu links to the + // private page, so the child is nested under that link. + $parent_id = $this->publish_new_page( + array( + 'post_title' => 'Members', + 'post_status' => 'private', + ) + ); + wp_update_post( + array( + 'ID' => $parent_id, + 'post_status' => 'private', + ) + ); + $menu_id = $this->create_menu( + sprintf( + '', + $parent_id, + get_permalink( $parent_id ) + ), + true + ); + + $child_id = $this->publish_new_page( + array( + 'post_title' => 'Perks', + 'post_parent' => $parent_id, + ) + ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertSame( 'core/navigation-submenu', $blocks[0]['blockName'] ); + $this->assertCount( 1, $blocks[0]['innerBlocks'] ); + $this->assert_page_link_block( $blocks[0]['innerBlocks'][0], $child_id ); + } + + public function test_a_menu_with_a_page_list_is_untouched() { + $top_level = ''; + $nested = ''; + $top_id = $this->create_menu( $top_level, true ); + $nested_id = $this->create_menu( $nested, true ); + + $this->publish_new_page(); + + $this->assertSame( $top_level, get_post( $top_id )->post_content ); + $this->assertSame( $nested, get_post( $nested_id )->post_content ); + } +} diff --git a/routes/navigation-edit/auto-add-pages-toggle.tsx b/routes/navigation-edit/auto-add-pages-toggle.tsx new file mode 100644 index 00000000000000..8fda4ed8829ac0 --- /dev/null +++ b/routes/navigation-edit/auto-add-pages-toggle.tsx @@ -0,0 +1,69 @@ +import { store as coreStore } from '@wordpress/core-data'; +import { useDispatch, useSelect } from '@wordpress/data'; +import { __ } from '@wordpress/i18n'; +import { SwitchControl } from '@wordpress/ui'; + +const NAVIGATION_POST_TYPE = 'wp_navigation'; +const META_KEY = 'wp_navigation_auto_add_pages'; + +type NavigationMenuRecord = { + meta?: Record< string, unknown >; +}; + +/** + * The menu's "Auto add new pages" setting. A change is an edit to the menu record + * and is saved with the screen's other changes. It renders nothing, wrapper + * included, when the server has no such setting, as in a WordPress release + * without it. + * + * @param props + * @param props.id The `wp_navigation` post ID. + * @param props.className Class for the wrapper. + */ +export default function AutoAddPagesToggle( { + id, + className, +}: { + id: number; + className?: string; +} ) { + const { hasSetting, isEnabled } = useSelect( + ( select ) => { + const record = select( coreStore ).getEditedEntityRecord( + 'postType', + NAVIGATION_POST_TYPE, + id + ) as NavigationMenuRecord | undefined; + return { + // The REST API lists every registered meta key. + hasSetting: !! record?.meta && META_KEY in record.meta, + isEnabled: !! record?.meta?.[ META_KEY ], + }; + }, + [ id ] + ); + const { editEntityRecord } = useDispatch( coreStore ); + + const onCheckedChange = ( value: boolean ) => { + editEntityRecord( 'postType', NAVIGATION_POST_TYPE, id, { + meta: { [ META_KEY ]: value }, + } ); + }; + + if ( ! hasSetting ) { + return null; + } + + return ( +
+ +
+ ); +} diff --git a/routes/navigation-edit/package.json b/routes/navigation-edit/package.json index 9cc610428fd080..bf6990bbec841f 100644 --- a/routes/navigation-edit/package.json +++ b/routes/navigation-edit/package.json @@ -19,7 +19,8 @@ "@wordpress/icons": "file:../../packages/icons", "@wordpress/lazy-editor": "file:../../packages/lazy-editor", "@wordpress/route": "file:../../packages/route", - "@wordpress/routes-lock-unlock": "file:../lock-unlock" + "@wordpress/routes-lock-unlock": "file:../lock-unlock", + "@wordpress/ui": "file:../../packages/ui" }, "devDependencies": { "@types/react": "^19.3.0" diff --git a/routes/navigation-edit/stage.tsx b/routes/navigation-edit/stage.tsx index afca176ef4a011..3b462a3c36e567 100644 --- a/routes/navigation-edit/stage.tsx +++ b/routes/navigation-edit/stage.tsx @@ -1,10 +1,12 @@ import { useParams } from '@wordpress/route'; import { Page, Breadcrumbs } from '@wordpress/admin-ui'; +import { Stack } from '@wordpress/ui'; import { useSelect } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; import { __ } from '@wordpress/i18n'; import { decodeEntities } from '@wordpress/html-entities'; import NavigationMenuEditor from './editor'; +import AutoAddPagesToggle from './auto-add-pages-toggle'; import styles from './style.module.scss'; const NAVIGATION_POST_TYPE = 'wp_navigation'; @@ -53,7 +55,24 @@ function NavigationEditStage() { } >
- + { /* + * The setting is pinned to the bottom of the screen, below the + * list however long the list is. + */ } + +
+ +
+ +
); diff --git a/routes/navigation-edit/style.module.scss b/routes/navigation-edit/style.module.scss index e89d20496ffb87..7c7414ff197dae 100644 --- a/routes/navigation-edit/style.module.scss +++ b/routes/navigation-edit/style.module.scss @@ -2,6 +2,24 @@ flex-grow: 1; min-height: 0; overflow: auto; + display: flex; + flex-direction: column; background-color: var(--wpds-color-background-surface-neutral-strong); +} + +.layout { + flex-grow: 1; +} + +.menu { padding: var(--wpds-dimension-padding-lg) var(--wpds-dimension-padding-2xl); } + +// Same separator as the page header's bottom edge. +.footer { + position: sticky; + bottom: 0; + padding: var(--wpds-dimension-padding-lg) var(--wpds-dimension-padding-2xl); + border-block-start: var(--wpds-border-width-xs) solid var(--wpds-color-stroke-surface-neutral-weak); + background-color: var(--wpds-color-background-surface-neutral-strong); +} diff --git a/routes/navigation-edit/tsconfig.json b/routes/navigation-edit/tsconfig.json index 37074f64fb5707..6f6eff8a86b559 100644 --- a/routes/navigation-edit/tsconfig.json +++ b/routes/navigation-edit/tsconfig.json @@ -21,7 +21,8 @@ { "path": "../../packages/i18n/tsconfig.build.json" }, { "path": "../../packages/icons/tsconfig.build.json" }, { "path": "../../packages/lazy-editor/tsconfig.build.json" }, - { "path": "../../packages/route/tsconfig.build.json" } + { "path": "../../packages/route/tsconfig.build.json" }, + { "path": "../../packages/ui/tsconfig.build.json" } ], "include": [ "**/*.ts", "**/*.tsx" ], "exclude": [ "build", "node_modules" ] diff --git a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.ts b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.ts new file mode 100644 index 00000000000000..da0b1c435fb769 --- /dev/null +++ b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.ts @@ -0,0 +1,515 @@ +import type { Page } from '@playwright/test'; +import { + test, + expect, + type RequestUtils, +} from '@wordpress/e2e-test-utils-playwright'; + +const META_KEY = 'wp_navigation_auto_add_pages'; + +// `requestUtils.createNavigationMenu()` takes only a title and content. +function createAutoAddMenu( + requestUtils: RequestUtils, + menu: { title: string; content: string } +) { + return requestUtils.rest< { id: number } >( { + method: 'POST', + path: '/wp/v2/navigation', + data: { ...menu, status: 'publish', meta: { [ META_KEY ]: true } }, + } ); +} + +async function enableShowTemplate( page: Page ) { + await page + .getByRole( 'region', { name: 'Editor top bar' } ) + .getByRole( 'button', { name: 'View', exact: true } ) + .click(); + + const showTemplateButton = page.getByRole( 'menuitemcheckbox', { + name: 'Show template', + } ); + const isChecked = await showTemplateButton.getAttribute( 'aria-checked' ); + if ( isChecked !== 'true' ) { + await showTemplateButton.click(); + } else { + await page.keyboard.press( 'Escape' ); + } +} + +test.describe( 'Navigation block: Auto add new pages', () => { + test.beforeEach( async ( { requestUtils } ) => { + await Promise.all( [ + requestUtils.deleteAllPages(), + requestUtils.deleteAllMenus(), + ] ); + } ); + + test.afterAll( async ( { requestUtils } ) => { + await Promise.all( [ + requestUtils.deleteAllPages(), + requestUtils.deleteAllMenus(), + ] ); + } ); + + test( 'a navigation block in the editor shows the new link once the page is published', async ( { + admin, + editor, + requestUtils, + } ) => { + const menu = await createAutoAddMenu( requestUtils, { + title: 'Main menu', + content: + '', + } ); + + await admin.createNewPost( { + postType: 'page', + title: 'Auto added page', + } ); + await editor.insertBlock( { + name: 'core/navigation', + attributes: { ref: menu.id }, + } ); + + const navigationBlock = editor.canvas.getByRole( 'document', { + name: 'Block: Navigation', + } ); + await expect( navigationBlock ).toContainText( 'Home' ); + + await editor.publishPost(); + + // The server appended the link; the block must pick it up without a + // reload. + await expect( + navigationBlock.getByRole( 'document', { + name: 'Block: Page Link', + } ) + ).toContainText( 'Auto added page', { timeout: 10000 } ); + } ); + + test( 'a menu saved earlier in the session shows the new link, and saving it again keeps the link', async ( { + admin, + editor, + page, + requestUtils, + } ) => { + const menu = await createAutoAddMenu( requestUtils, { + title: 'Main menu', + content: + '', + } ); + + await admin.createNewPost( { + postType: 'page', + title: 'Auto added page', + } ); + await editor.insertBlock( { + name: 'core/navigation', + attributes: { ref: menu.id }, + } ); + const navigationBlock = editor.canvas.getByRole( 'document', { + name: 'Block: Navigation', + } ); + const homeLink = navigationBlock.getByRole( 'document', { + name: 'Block: Custom Link', + } ); + const topBar = page.getByRole( 'region', { name: 'Editor top bar' } ); + const getMenuContent = async () => { + const savedMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + return savedMenu.content.raw as string; + }; + const renameHomeAndSave = async ( suffix: string ) => { + // Select the Navigation block first, which lifts its overlay. + await editor.selectBlocks( navigationBlock ); + await homeLink.click(); + await page.keyboard.press( 'End' ); + await page.keyboard.type( suffix ); + await topBar + .getByRole( 'button', { name: 'Save', exact: true } ) + .click(); + await page + .getByRole( 'region', { name: 'Editor publish' } ) + .getByRole( 'button', { name: 'Save', exact: true } ) + .click(); + }; + + // Edit the menu and save it before the page is published. + await renameHomeAndSave( ' page' ); + await expect.poll( getMenuContent ).toContain( '"label":"Home page"' ); + // Saving leaves the panel open on the pre-publish checks. + await page + .getByRole( 'region', { name: 'Editor publish' } ) + .getByRole( 'button', { name: 'Cancel' } ) + .click(); + + await editor.publishPost(); + await expect + .poll( getMenuContent ) + .toContain( '"label":"Auto added page"' ); + + // The server appended the link; the block must pick it up without a + // reload, though the menu's blocks were edited earlier. + const pageLink = navigationBlock.getByRole( 'document', { + name: 'Block: Page Link', + } ); + await expect( pageLink ).toContainText( 'Auto added page', { + timeout: 10000, + } ); + + // Saving the menu again must keep the link the server added. + await page + .getByRole( 'region', { name: 'Editor publish' } ) + .getByRole( 'button', { name: 'Close panel' } ) + .click(); + await renameHomeAndSave( ' again' ); + await expect + .poll( getMenuContent ) + .toContain( '"label":"Home page again"' ); + expect( await getMenuContent() ).toContain( + '"label":"Auto added page"' + ); + } ); + + test( 'a child page is nested under the link to its parent', async ( { + admin, + editor, + requestUtils, + } ) => { + const parent = await requestUtils.rest< { id: number; link: string } >( + { + method: 'POST', + path: '/wp/v2/pages', + data: { title: 'Parent page', status: 'publish' }, + } + ); + const menu = await createAutoAddMenu( requestUtils, { + title: 'Main menu', + content: ``, + } ); + const child = await requestUtils.rest( { + method: 'POST', + path: '/wp/v2/pages', + data: { + title: 'Child page', + status: 'draft', + parent: parent.id, + }, + } ); + + await admin.editPost( child.id ); + await editor.insertBlock( { + name: 'core/navigation', + attributes: { ref: menu.id }, + } ); + + const navigationBlock = editor.canvas.getByRole( 'document', { + name: 'Block: Navigation', + } ); + await expect( + navigationBlock.getByRole( 'document', { + name: 'Block: Page Link', + } ) + ).toContainText( 'Parent page' ); + + await editor.publishPost(); + + // The server turned the parent link into a submenu holding the child; + // the block must pick it up without a reload. + const submenu = navigationBlock.getByRole( 'document', { + name: 'Block: Submenu', + } ); + await expect( submenu ).toContainText( 'Parent page', { + timeout: 10000, + } ); + + // The submenu only shows its items while it is being edited, so check + // the block tree for the child instead. + const menuBlocks = await editor.getBlocks( { + clientId: + ( await navigationBlock.getAttribute( 'data-block' ) ) ?? + undefined, + } ); + expect( menuBlocks ).toMatchObject( [ + { + name: 'core/navigation-submenu', + attributes: { label: 'Parent page', id: parent.id }, + innerBlocks: [ + { + name: 'core/navigation-link', + attributes: { label: 'Child page', id: child.id }, + innerBlocks: [], + }, + ], + }, + ] ); + } ); + + test( 'a page created from the navigation appender is not added twice', async ( { + admin, + editor, + page, + requestUtils, + } ) => { + const menu = await createAutoAddMenu( requestUtils, { + title: 'Main menu', + content: + '', + } ); + + await admin.createNewPost(); + await editor.insertBlock( { + name: 'core/navigation', + attributes: { ref: menu.id }, + } ); + + const navigationBlock = editor.canvas.getByRole( 'document', { + name: 'Block: Navigation', + } ); + await expect( navigationBlock ).toContainText( 'Home' ); + + // Create the page from the appender's link UI, published (the default). + await navigationBlock.getByLabel( 'Add page' ).first().click(); + await page + .getByRole( 'combobox', { name: 'Search or type URL' } ) + .fill( 'Created page' ); + await page.getByRole( 'button', { name: 'Create page' } ).click(); + await expect( + page.getByRole( 'textbox', { name: 'Title' } ) + ).toHaveValue( 'Created page' ); + await expect( + page.getByRole( 'checkbox', { name: 'Publish' } ) + ).toBeChecked(); + await page.getByRole( 'button', { name: 'Create page' } ).click(); + await expect( + page.getByRole( 'link', { + name: 'Created page (opens in a new tab)', + } ) + ).toBeVisible(); + await page.keyboard.press( 'Escape' ); + + const [ createdPage ] = await requestUtils.rest( { + path: '/wp/v2/pages', + params: { search: 'Created page', status: 'publish' }, + } ); + expect( createdPage ).toBeDefined(); + + // The menu on the server did not link to the page yet when it was + // published, so the server appended its own link. + const appendedMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + expect( appendedMenu.content.raw ).toContain( + `"id":${ createdPage.id }` + ); + + // Meanwhile the link UI inserted its own link, so the block holds a + // pending edit; the refetched menu must not add a second link. + const pageLinks = navigationBlock.getByRole( 'document', { + name: 'Block: Page Link', + } ); + await expect( pageLinks ).toHaveCount( 1 ); + await expect( pageLinks ).toContainText( 'Created page' ); + // Once the refetched menu, with the server-appended link, has reached + // the store, the block still shows one link. + await expect + .poll( () => + page.evaluate( + ( id ) => + window.wp.data + .select( 'core' ) + .getEntityRecord( 'postType', 'wp_navigation', id ) + ?.content?.raw ?? '', + menu.id + ) + ) + .toContain( `"id":${ createdPage.id }` ); + await expect( pageLinks ).toHaveCount( 1 ); + + const topBar = page.getByRole( 'region', { name: 'Editor top bar' } ); + await topBar + .getByRole( 'button', { name: 'Save', exact: true } ) + .click(); + await page + .getByRole( 'region', { name: 'Editor publish' } ) + .getByRole( 'button', { name: 'Save', exact: true } ) + .click(); + + // The Save button goes away once nothing is left to save. + await expect( + topBar.getByRole( 'button', { name: 'Save', exact: true } ) + ).toBeHidden(); + + // The saved menu links to the page once: the editor's link, not the + // editor's link plus the server's. + const savedMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + expect( savedMenu.content.raw ).toContain( '"label":"Created page"' ); + expect( + savedMenu.content.raw.match( + new RegExp( `"id":${ createdPage.id }\\b`, 'g' ) + ) + ).toHaveLength( 1 ); + } ); + + test( 'turning the setting off is saved with the post', async ( { + admin, + editor, + page, + requestUtils, + } ) => { + const menu = await createAutoAddMenu( requestUtils, { + title: 'Main menu', + content: + '', + } ); + + await admin.createNewPost(); + await editor.insertBlock( { + name: 'core/navigation', + attributes: { ref: menu.id }, + } ); + await editor.openDocumentSettingsSidebar(); + const settings = page.getByRole( 'region', { + name: 'Editor settings', + } ); + await settings.getByRole( 'tab', { name: 'List View' } ).click(); + + // The setting follows the menu's items and their appender, so it + // reads as part of the menu structure rather than as a block setting. + await expect( + settings.locator( + 'xpath=.//*[@role="treegrid"]/following::*[@role="switch"]' + ) + ).toHaveAccessibleName( 'Auto add new pages' ); + const toggle = settings.getByRole( 'switch', { + name: 'Auto add new pages', + } ); + await expect( toggle ).toHaveAccessibleDescription( + 'Adds pages to this navigation when they are published.' + ); + await expect( toggle ).toBeChecked(); + await toggle.click(); + await expect( toggle ).not.toBeChecked(); + + // The change is a pending edit to the menu, saved with everything + // else, so the top bar offers to save and the server is untouched. + const topBar = page.getByRole( 'region', { name: 'Editor top bar' } ); + await expect( + topBar.getByRole( 'button', { name: 'Save', exact: true } ) + ).toBeVisible(); + const pendingMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + expect( pendingMenu.meta[ META_KEY ] ).toBe( true ); + + await topBar + .getByRole( 'button', { name: 'Save', exact: true } ) + .click(); + await page + .getByRole( 'region', { name: 'Editor publish' } ) + .getByRole( 'button', { name: 'Save', exact: true } ) + .click(); + + await expect + .poll( async () => { + const savedMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + return savedMenu.meta[ META_KEY ]; + } ) + .toBe( false ); + + const savedMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + + await requestUtils.createPage( { title: 'Later', status: 'publish' } ); + const unchangedMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + expect( unchangedMenu.content.raw ).toBe( savedMenu.content.raw ); + } ); + + test.describe( 'with the template shown', () => { + test.beforeAll( async ( { requestUtils } ) => { + await requestUtils.activateTheme( 'emptytheme' ); + } ); + + test.afterEach( async ( { requestUtils } ) => { + await Promise.all( [ + requestUtils.deleteAllTemplates( 'wp_template' ), + requestUtils.deleteAllTemplates( 'wp_template_part' ), + requestUtils.resetPreferences(), + ] ); + } ); + + test.afterAll( async ( { requestUtils } ) => { + await requestUtils.activateTheme( 'twentytwentyone' ); + } ); + + test( 'a navigation block in the header template part shows the new link once the page is published', async ( { + admin, + editor, + page, + requestUtils, + } ) => { + const menu = await createAutoAddMenu( requestUtils, { + title: 'Main menu', + content: + '', + } ); + await requestUtils.createTemplate( 'wp_template_part', { + slug: 'header', + title: 'Header', + content: ``, + } ); + await requestUtils.createTemplate( 'wp_template', { + slug: 'singular', + title: 'Singular', + content: [ + '', + '', + ].join( '\n' ), + } ); + const draft = await requestUtils.createPage( { + title: 'Auto added page', + status: 'draft', + } ); + + await admin.editPost( draft.id ); + await enableShowTemplate( page ); + + const navigationBlock = editor.canvas + .getByRole( 'document', { name: 'Block: Header' } ) + .getByRole( 'document', { name: 'Block: Navigation' } ); + await expect( navigationBlock ).toContainText( 'Home' ); + + await editor.publishPost(); + + await expect( + navigationBlock.getByRole( 'document', { + name: 'Block: Page Link', + } ) + ).toContainText( 'Auto added page', { timeout: 10000 } ); + + // The preference save is debounced and outlives the page, so clear + // it in the session too, or a late flush re-enables Show template + // for later post editor suites under a block theme. + await page.evaluate( () => { + window.wp.data + .dispatch( 'core/preferences' ) + .set( 'core', 'renderingModes', undefined ); + } ); + } ); + } ); +} ); diff --git a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.ts b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.ts new file mode 100644 index 00000000000000..5def17f32e24fb --- /dev/null +++ b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.ts @@ -0,0 +1,297 @@ +import type { Locator, Page } from '@playwright/test'; +import { test, expect } from '@wordpress/e2e-test-utils-playwright'; + +// The screen under test is the extensible site editor's navigation menu +// screen, which lives at `admin.php?page=site-editor-v2`. +const isSiteEditorV2 = !! process.env.GUTENBERG_E2E_SITE_EDITOR_V2; + +const META_KEY = 'wp_navigation_auto_add_pages'; + +/** + * How far the bottom edge of an element is from the bottom of the viewport. + * + * @param page The page. + * @param locator The element. + */ +async function distanceFromBottom( page: Page, locator: Locator ) { + const box = await locator.boundingBox(); + const viewport = page.viewportSize(); + if ( ! box || ! viewport ) { + return Infinity; + } + return viewport.height - ( box.y + box.height ); +} + +test.describe( 'Navigation sidebar: Auto add new pages', () => { + test.skip( + isSiteEditorV2, + 'The extensible site editor has no navigation sidebar.' + ); + + test.beforeAll( async ( { requestUtils } ) => { + await requestUtils.activateTheme( 'emptytheme' ); + } ); + + test.beforeEach( async ( { requestUtils } ) => { + await Promise.all( [ + requestUtils.deleteAllPages(), + requestUtils.deleteAllMenus(), + ] ); + } ); + + test.afterAll( async ( { requestUtils } ) => { + await Promise.all( [ + requestUtils.deleteAllPages(), + requestUtils.deleteAllMenus(), + ] ); + await requestUtils.activateTheme( 'twentytwentyone' ); + } ); + + test( 'the setting is pinned to the bottom of the sidebar and saved with the menu', async ( { + admin, + page, + requestUtils, + } ) => { + const menu = await requestUtils.createNavigationMenu( { + title: 'Main menu', + content: + '', + } ); + + await admin.visitSiteEditor( { + postId: menu.id, + postType: 'wp_navigation', + } ); + + const sidebar = page.getByRole( 'region', { + name: 'Navigation', + } ); + await expect( + sidebar.getByRole( 'treegrid', { + name: 'Block navigation structure', + } ) + ).toBeVisible(); + + // The setting sits in the sidebar's footer, at the bottom of the + // screen above the save button, even though the menu is short. + const toggle = sidebar.locator( 'footer' ).getByRole( 'switch', { + name: 'Auto add new pages', + } ); + await expect( toggle ).toBeVisible(); + await expect + .poll( () => distanceFromBottom( page, toggle ) ) + .toBeLessThan( 200 ); + await expect( toggle ).toHaveAccessibleDescription( + 'Adds pages to this navigation when they are published.' + ); + await expect( toggle ).not.toBeChecked(); + await toggle.click(); + await expect( toggle ).toBeChecked(); + + await page.getByRole( 'button', { name: 'Review 1 change…' } ).click(); + await page + .getByRole( 'dialog', { name: 'Review changes' } ) + .getByRole( 'button', { name: 'Save', exact: true } ) + .click(); + + await expect + .poll( async () => { + const savedMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + return savedMenu.meta[ META_KEY ]; + } ) + .toBe( true ); + } ); + + test( 'publishing a page keeps the menu screen as it is, and shows the new link', async ( { + admin, + page, + requestUtils, + } ) => { + const menu = await requestUtils.rest< { id: number } >( { + method: 'POST', + path: '/wp/v2/navigation', + data: { + title: 'Main menu', + status: 'publish', + content: + '', + meta: { [ META_KEY ]: true }, + }, + } ); + + await admin.visitSiteEditor( { + postId: menu.id, + postType: 'wp_navigation', + } ); + const sidebar = page.getByRole( 'region', { + name: 'Navigation', + } ); + const tree = sidebar.getByRole( 'treegrid', { + name: 'Block navigation structure', + } ); + await expect( tree ).toContainText( 'Home' ); + const toggle = sidebar.locator( 'footer' ).getByRole( 'switch', { + name: 'Auto add new pages', + } ); + await toggle.focus(); + + // A page published from this editor, as the "Create page" option of + // the menu's link search does. + await page.evaluate( () => + window.wp.data + .dispatch( 'core' ) + .saveEntityRecord( 'postType', 'page', { + title: 'Published here', + status: 'publish', + } ) + ); + + await expect( tree ).toContainText( 'Published here' ); + // The screen wasn't swapped for a loading state while the menu was + // fetched again, so focus stays where it was. + await expect( toggle ).toBeFocused(); + } ); + + test( 'a duplicated menu keeps the setting', async ( { + admin, + page, + requestUtils, + } ) => { + const menu = await requestUtils.createNavigationMenu( { + title: 'Main menu', + content: + '', + } ); + await requestUtils.rest( { + method: 'POST', + path: `/wp/v2/navigation/${ menu.id }`, + data: { meta: { [ META_KEY ]: true } }, + } ); + + await admin.visitSiteEditor( { + postId: menu.id, + postType: 'wp_navigation', + } ); + await page + .getByRole( 'region', { name: 'Navigation' } ) + .getByRole( 'button', { name: 'Actions' } ) + .click(); + await page.getByRole( 'menuitem', { name: 'Duplicate' } ).click(); + await expect( + page + .getByRole( 'button', { name: 'Dismiss this notice' } ) + .filter( { hasText: 'Duplicated Navigation Menu' } ) + ).toBeVisible(); + + const menus = await requestUtils.rest( { + path: '/wp/v2/navigation', + params: { context: 'edit', search: 'Copy' }, + } ); + expect( menus ).toHaveLength( 1 ); + expect( menus[ 0 ].meta[ META_KEY ] ).toBe( true ); + } ); +} ); + +test.describe( 'Navigation menu screen: Auto add new pages', () => { + test.skip( + ! isSiteEditorV2, + 'Only the extensible site editor has a navigation menu screen.' + ); + + test.beforeAll( async ( { requestUtils } ) => { + await requestUtils.activateTheme( 'emptytheme' ); + } ); + + test.beforeEach( async ( { requestUtils } ) => { + await Promise.all( [ + requestUtils.deleteAllPages(), + requestUtils.deleteAllMenus(), + ] ); + } ); + + test.afterAll( async ( { requestUtils } ) => { + await Promise.all( [ + requestUtils.deleteAllPages(), + requestUtils.deleteAllMenus(), + ] ); + await requestUtils.activateTheme( 'twentytwentyone' ); + } ); + + test( 'the setting is saved with the menu', async ( { + admin, + page, + requestUtils, + } ) => { + const menu = await requestUtils.createNavigationMenu( { + title: 'Main menu', + content: + '', + } ); + + await admin.visitAdminPage( + 'admin.php', + `page=site-editor-v2&p=${ encodeURIComponent( + `/navigation/edit/${ menu.id }` + ) }` + ); + + // The setting sits at the bottom of the screen, below the short menu. + await expect( + page.locator( + 'xpath=//*[@role="treegrid"]/following::*[@role="switch"]' + ) + ).toHaveAccessibleName( 'Auto add new pages' ); + const toggle = page.getByRole( 'switch', { + name: 'Auto add new pages', + } ); + await expect + .poll( () => distanceFromBottom( page, toggle ) ) + .toBeLessThan( 200 ); + await expect( toggle ).toHaveAccessibleDescription( + 'Adds pages to this navigation when they are published.' + ); + await expect( toggle ).not.toBeChecked(); + await toggle.click(); + await expect( toggle ).toBeChecked(); + + // The change is a pending edit to the menu until it is saved. + const reviewButton = page.getByRole( 'button', { + name: 'Review 1 change…', + } ); + await expect( reviewButton ).toBeVisible(); + const pendingMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + expect( pendingMenu.meta[ META_KEY ] ).toBe( false ); + + await reviewButton.click(); + await page + .getByRole( 'dialog', { name: 'Review changes' } ) + .getByRole( 'button', { name: 'Save', exact: true } ) + .click(); + + await expect + .poll( async () => { + const savedMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + return savedMenu.meta[ META_KEY ]; + } ) + .toBe( true ); + + const about = await requestUtils.createPage( { + title: 'About', + status: 'publish', + } ); + const updatedMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + expect( updatedMenu.content.raw ).toContain( `"id":${ about.id }` ); + } ); +} );