From c63305293403e6c455e2668530947ba90ccb1006 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Sat, 10 Oct 2026 12:13:18 -0500 Subject: [PATCH 01/30] Navigation: Add an "Auto add pages" menu setting and drop the Page List fallback Register a boolean `wp_navigation_auto_add_pages` meta on Navigation Menus. While it is on, publishing a top-level page appends a link to the menu, the way classic menus do; existing items are never touched. The default menu a site creates for itself is now built from link blocks, one per published page, nested like the Page List block rendered them, with the setting on. The setting is a switch in the Navigation block's Settings tab and on the extensible site editor's navigation menu screen. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RKwLg37vPNWxb2pUbFB6mS --- .../navigation-auto-add-pages.php | 256 ++++++++++++ lib/load.php | 1 + package-lock.json | 3 +- packages/block-library/CHANGELOG.md | 4 + .../edit/auto-add-pages-control.tsx | 72 ++++ .../src/navigation/edit/index.jsx | 11 + phpunit/navigation-auto-add-pages-test.php | 384 ++++++++++++++++++ .../navigation-edit/auto-add-pages-toggle.tsx | 73 ++++ routes/navigation-edit/package.json | 3 +- routes/navigation-edit/stage.tsx | 4 + routes/navigation-edit/style.module.scss | 4 + routes/navigation-edit/tsconfig.json | 3 +- .../blocks/navigation-auto-add-pages.spec.js | 110 +++++ .../specs/editor/blocks/navigation.spec.js | 16 +- ...ollaboration-undo-navigation-block.spec.ts | 16 +- .../navigation-auto-add-pages.spec.js | 77 ++++ 16 files changed, 1021 insertions(+), 16 deletions(-) create mode 100644 lib/compat/wordpress-7.2/navigation-auto-add-pages.php create mode 100644 packages/block-library/src/navigation/edit/auto-add-pages-control.tsx create mode 100644 phpunit/navigation-auto-add-pages-test.php create mode 100644 routes/navigation-edit/auto-add-pages-toggle.tsx create mode 100644 test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js create mode 100644 test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js diff --git a/lib/compat/wordpress-7.2/navigation-auto-add-pages.php b/lib/compat/wordpress-7.2/navigation-auto-add-pages.php new file mode 100644 index 00000000000000..c27dd45e50044d --- /dev/null +++ b/lib/compat/wordpress-7.2/navigation-auto-add-pages.php @@ -0,0 +1,256 @@ + 'boolean', + 'description' => __( 'Whether newly published top-level 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. + * @return array A parsed block. + */ +function gutenberg_navigation_build_page_link_block( $page, $inner_blocks = array() ) { + return array( + 'blockName' => empty( $inner_blocks ) ? 'core/navigation-link' : 'core/navigation-submenu', + 'attrs' => array( + 'label' => '' !== $page->post_title ? $page->post_title : __( '(no title)', 'gutenberg' ), + '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 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 ) { + $is_link = in_array( $block['blockName'], array( 'core/navigation-link', 'core/navigation-submenu' ), true ); + if ( $is_link && isset( $block['attrs']['id'] ) && (int) $block['attrs']['id'] === (int) $page_id ) { + $kind = isset( $block['attrs']['kind'] ) ? $block['attrs']['kind'] : ''; + $type = isset( $block['attrs']['type'] ) ? $block['attrs']['type'] : ''; + if ( 'post-type' === $kind || 'page' === $type ) { + return true; + } + } + if ( ! empty( $block['innerBlocks'] ) && gutenberg_navigation_blocks_link_to_page( $block['innerBlocks'], $page_id ) ) { + return true; + } + } + + return false; +} + +/** + * Appends a link to a newly published top-level page to every Navigation Menu + * that has "Auto add pages" switched on. + * + * Mirrors `_wp_auto_add_pages_to_menu()` for classic menus: only the + * transition into `publish` counts, child pages are skipped, 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. + */ +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; + } + if ( ! empty( $post->post_parent ) ) { + 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, + ) + ); + + foreach ( $menus as $menu ) { + $blocks = parse_blocks( $menu->post_content ); + if ( gutenberg_navigation_blocks_link_to_page( $blocks, $post->ID ) ) { + continue; + } + $blocks[] = gutenberg_navigation_build_page_link_block( $post ); + + wp_update_post( + array( + 'ID' => $menu->ID, + 'post_content' => wp_slash( serialize_blocks( $blocks ) ), + ) + ); + } +} +add_action( 'transition_post_status', 'gutenberg_navigation_auto_add_page_on_publish', 10, 3 ); + +/** + * Builds link blocks for the published pages under a parent, recursively. + * + * @param int $parent_id Parent page ID, 0 for top-level pages. + * @param WP_Post[] $children Published pages grouped by `post_parent`. + * @return array[] Parsed blocks. + */ +function gutenberg_navigation_build_page_tree_blocks( $parent_id, $children ) { + $blocks = array(); + if ( empty( $children[ $parent_id ] ) ) { + return $blocks; + } + foreach ( $children[ $parent_id ] as $page ) { + $inner_blocks = gutenberg_navigation_build_page_tree_blocks( $page->ID, $children ); + $blocks[] = gutenberg_navigation_build_page_link_block( $page, $inner_blocks ); + } + return $blocks; +} + +/** + * Gets the link blocks for the site's published pages, nested like the Page + * List block renders them and in the same order. + * + * @return array[] Parsed blocks. + */ +function gutenberg_navigation_get_page_link_blocks() { + $pages = get_pages( + array( + 'sort_column' => 'menu_order,post_title', + 'order' => 'asc', + ) + ); + if ( empty( $pages ) ) { + return array(); + } + + $children = array(); + foreach ( $pages as $page ) { + $children[ $page->post_parent ][] = $page; + } + + return gutenberg_navigation_build_page_tree_blocks( 0, $children ); +} + +/** + * Creates the default fallback Navigation Menu from page links instead of a + * Page List block. + * + * `WP_Navigation_Fallback::get_fallback()` applies this filter before it + * looks for an existing menu, converts a classic menu, or creates its Page + * List default. When no menu exists and there is no classic menu to convert, + * the menu is created here with "Auto add pages" switched on, and `false` is + * returned so core does not create a second one: core then finds this menu as + * the most recently published one and returns it. + * + * In WordPress Core this would be a change to + * `WP_Navigation_Fallback::create_default_fallback()` instead. + * + * @param bool $should_create Whether core should create a fallback menu. + * @return bool Whether core should still create a fallback menu. + */ +function gutenberg_navigation_create_fallback_with_pages( $should_create ) { + if ( ! $should_create ) { + return $should_create; + } + + $existing = get_posts( + array( + 'post_type' => 'wp_navigation', + 'post_status' => 'publish', + 'posts_per_page' => 1, + 'fields' => 'ids', + 'no_found_rows' => true, + ) + ); + if ( ! empty( $existing ) ) { + return $should_create; + } + + // Core converts a classic menu before falling back to its default; leave that path to core. + $classic_menus = wp_get_nav_menus(); + if ( ! empty( $classic_menus ) && ! is_wp_error( $classic_menus ) ) { + return $should_create; + } + + $menu_id = wp_insert_post( + array( + 'post_content' => wp_slash( serialize_blocks( gutenberg_navigation_get_page_link_blocks() ) ), + 'post_title' => _x( 'Navigation', 'Title of a Navigation menu', 'gutenberg' ), + 'post_name' => 'navigation', + 'post_status' => 'publish', + 'post_type' => 'wp_navigation', + ), + true + ); + if ( is_wp_error( $menu_id ) || empty( $menu_id ) ) { + return $should_create; + } + + update_post_meta( $menu_id, 'wp_navigation_auto_add_pages', true ); + + return false; +} +add_filter( 'wp_navigation_should_create_fallback', 'gutenberg_navigation_create_fallback_with_pages' ); diff --git a/lib/load.php b/lib/load.php index cb4756231b3785..44e04164b8670e 100644 --- a/lib/load.php +++ b/lib/load.php @@ -151,6 +151,7 @@ function gutenberg_get_experiment_default( $name ) { require __DIR__ . '/compat/wordpress-7.2/kses.php'; require __DIR__ . '/compat/wordpress-7.2/media.php'; require __DIR__ . '/compat/wordpress-7.2/post.php'; +require __DIR__ . '/compat/wordpress-7.2/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 3028688713ab4d..0dee5fabd28e19 100644 --- a/package-lock.json +++ b/package-lock.json @@ -49173,7 +49173,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-library/CHANGELOG.md b/packages/block-library/CHANGELOG.md index 5e62fe224e5b27..99f6cb5e9ccb95 100644 --- a/packages/block-library/CHANGELOG.md +++ b/packages/block-library/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Enhancements + +- Navigation: Add an "Auto add pages" menu setting. While it is on, publishing a top-level page appends a link to the menu, as classic menus do. The default menu a site creates for itself now starts as one link per published page with the setting on, instead of a Page List block. + ### Bug Fixes - Template Part: Show the "Default based on area" HTML element as selected instead of the `Select` placeholder ([#85172](https://github.com/WordPress/gutenberg/pull/85172)). 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..56b532632c8fc0 --- /dev/null +++ b/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx @@ -0,0 +1,72 @@ +import { + __experimentalToolsPanel as ToolsPanel, + __experimentalToolsPanelItem as ToolsPanelItem, +} from '@wordpress/components'; +import { useEntityProp } from '@wordpress/core-data'; +import { __ } from '@wordpress/i18n'; +import { SwitchControl } from '@wordpress/ui'; + +const META_KEY = 'wp_navigation_auto_add_pages'; + +type NavigationMenuMeta = Record< string, unknown > & { + [ META_KEY ]?: boolean; +}; + +type Props = { + /** The `wp_navigation` post the block displays. */ + menuId: number; + dropdownMenuProps?: React.ComponentProps< + typeof ToolsPanel + >[ 'dropdownMenuProps' ]; +}; + +/** + * Settings that belong to the Navigation Menu rather than to the block, so + * they are read from and written to the `wp_navigation` entity and saved with + * it. + * + * @param props + * @param props.menuId + * @param props.dropdownMenuProps + */ +export default function AutoAddPagesControl( { + menuId, + dropdownMenuProps, +}: Props ) { + const [ meta, setMeta ] = useEntityProp( + 'postType', + 'wp_navigation', + 'meta', + menuId + ) as unknown as [ + NavigationMenuMeta | undefined, + ( meta: NavigationMenuMeta ) => void, + ]; + const isEnabled = !! meta?.[ META_KEY ]; + const setEnabled = ( value: boolean ) => + setMeta( { ...meta, [ META_KEY ]: value } ); + + return ( + setEnabled( false ) } + dropdownMenuProps={ dropdownMenuProps } + > + isEnabled } + label={ __( 'Auto add pages' ) } + onDeselect={ () => setEnabled( false ) } + isShownByDefault + > + + + + ); +} diff --git a/packages/block-library/src/navigation/edit/index.jsx b/packages/block-library/src/navigation/edit/index.jsx index 565eb2235d0af1..432141880eb352 100644 --- a/packages/block-library/src/navigation/edit/index.jsx +++ b/packages/block-library/src/navigation/edit/index.jsx @@ -58,6 +58,7 @@ import { useInnerBlocks } from './use-inner-blocks'; import { detectColors } from './utils'; import ManageMenusButton from './manage-menus-button'; import MenuInspectorControls from './menu-inspector-controls'; +import AutoAddPagesControl from './auto-add-pages-control'; import DeletedNavigationWarning from './deleted-navigation-warning'; import AccessibleDescription from './accessible-description'; import AccessibleMenuDescription from './accessible-menu-description'; @@ -791,6 +792,16 @@ function Navigation( { const stylingInspectorControls = ( <> + { isEntityAvailable && + hasResolvedCanUserUpdateNavigationMenu && + canUserUpdateNavigationMenu && ( + + + + ) } { hasSubmenus && ( 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(); + } + + 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' => $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; + } + + 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_child_pages_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.' ); + + $this->publish_new_page( + array( + 'post_title' => 'Child', + 'post_parent' => $parent_id, + ) + ); + $this->assertCount( 1, $this->get_menu_blocks( $menu_id ), 'A child page is not 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_published_page_can_be_edited_by_a_user_without_unfiltered_html() { + $menu_id = $this->create_menu( '', true ); + $author = self::factory()->user->create( array( 'role' => 'author' ) ); + wp_set_current_user( $author ); + kses_init(); + + $page_id = $this->publish_new_page( array( 'post_title' => 'Terms & "Conditions"' ) ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertCount( 1, $blocks ); + $this->assert_page_link_block( $blocks[0], $page_id ); + kses_remove_filters(); + } + + /* + * Fallback menu. + */ + + public function test_fallback_menu_is_built_from_page_links_with_the_setting_on() { + $about_id = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_title' => 'About', + 'menu_order' => 2, + ) + ); + $contact_id = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_title' => 'Contact', + 'menu_order' => 1, + ) + ); + $team_id = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_title' => 'Team', + 'post_parent' => $about_id, + ) + ); + self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_title' => 'Draft', + 'post_status' => 'draft', + ) + ); + + $fallback = WP_Navigation_Fallback::get_fallback(); + + $this->assertInstanceOf( WP_Post::class, $fallback ); + $this->assertSame( 'wp_navigation', $fallback->post_type ); + $this->assertTrue( (bool) get_post_meta( $fallback->ID, self::META_KEY, true ) ); + $this->assertStringNotContainsString( 'wp:page-list', $fallback->post_content ); + + $blocks = $this->get_menu_blocks( $fallback->ID ); + $this->assertCount( 2, $blocks, 'Only top-level published pages are top-level items.' ); + $this->assert_page_link_block( $blocks[0], $contact_id ); + + $about = $blocks[1]; + $this->assertSame( 'core/navigation-submenu', $about['blockName'], 'A page with children becomes a submenu.' ); + $this->assertSame( $about_id, $about['attrs']['id'] ); + $this->assertSame( 'About', $about['attrs']['label'] ); + $this->assertSame( 'page', $about['attrs']['type'] ); + $this->assertSame( 'post-type', $about['attrs']['kind'] ); + $this->assertCount( 1, $about['innerBlocks'] ); + $this->assert_page_link_block( $about['innerBlocks'][0], $team_id ); + } + + public function test_fallback_menu_with_no_pages_is_empty_with_the_setting_on() { + $fallback = WP_Navigation_Fallback::get_fallback(); + + $this->assertInstanceOf( WP_Post::class, $fallback ); + $this->assertSame( '', $fallback->post_content ); + $this->assertTrue( (bool) get_post_meta( $fallback->ID, self::META_KEY, true ) ); + } + + public function test_fallback_reuses_an_existing_menu_without_touching_its_setting() { + $menu_id = $this->create_menu( '' ); + self::factory()->post->create( array( 'post_type' => 'page' ) ); + + $fallback = WP_Navigation_Fallback::get_fallback(); + + $this->assertSame( $menu_id, $fallback->ID ); + $this->assertEmpty( get_post_meta( $menu_id, self::META_KEY, true ) ); + $this->assertCount( + 1, + get_posts( + array( + 'post_type' => 'wp_navigation', + 'post_status' => 'any', + 'posts_per_page' => -1, + ) + ) + ); + } + + public function test_fallback_still_converts_a_classic_menu_first() { + $menu_id = wp_create_nav_menu( 'Classic' ); + wp_update_nav_menu_item( + $menu_id, + 0, + array( + 'menu-item-title' => 'Classic Link', + 'menu-item-url' => 'https://example.com/classic', + 'menu-item-status' => 'publish', + ) + ); + self::factory()->post->create( array( 'post_type' => 'page' ) ); + + $fallback = WP_Navigation_Fallback::get_fallback(); + + $this->assertStringContainsString( 'Classic Link', $fallback->post_content ); + $this->assertEmpty( get_post_meta( $fallback->ID, self::META_KEY, true ) ); + wp_delete_nav_menu( $menu_id ); + } + + public function test_fallback_rest_route_returns_the_page_link_menu() { + wp_set_current_user( self::$admin_id ); + $page_id = self::factory()->post->create( array( 'post_type' => 'page' ) ); + + $request = new WP_REST_Request( 'GET', '/wp-block-editor/v1/navigation-fallback' ); + $response = rest_get_server()->dispatch( $request ); + + $this->assertSame( 200, $response->get_status() ); + $menu_id = $response->get_data()['id']; + $this->assertTrue( (bool) get_post_meta( $menu_id, self::META_KEY, true ) ); + $this->assert_page_link_block( $this->get_menu_blocks( $menu_id )[0], $page_id ); + } +} 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..15ba471b1849a4 --- /dev/null +++ b/routes/navigation-edit/auto-add-pages-toggle.tsx @@ -0,0 +1,73 @@ +import { store as coreStore } from '@wordpress/core-data'; +import { useDispatch, useSelect } from '@wordpress/data'; +import { useState } from '@wordpress/element'; +import { __ } from '@wordpress/i18n'; +import { Notice, Stack, 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 pages" setting. This screen has no save button, so a + * change is saved as soon as it is made, and only the setting is sent. + * + * @param props + * @param props.id The `wp_navigation` post ID. + */ +export default function AutoAddPagesToggle( { id }: { id: number } ) { + const isEnabled = useSelect( + ( select ) => { + const record = select( coreStore ).getEditedEntityRecord( + 'postType', + NAVIGATION_POST_TYPE, + id + ) as NavigationMenuRecord | undefined; + return !! record?.meta?.[ META_KEY ]; + }, + [ id ] + ); + const [ isSaving, setIsSaving ] = useState( false ); + const [ hasError, setHasError ] = useState( false ); + const { saveEntityRecord } = useDispatch( coreStore ); + + const onCheckedChange = async ( value: boolean ) => { + setIsSaving( true ); + setHasError( false ); + try { + await saveEntityRecord( + 'postType', + NAVIGATION_POST_TYPE, + { id, meta: { [ META_KEY ]: value } }, + { throwOnError: true } + ); + } catch { + setHasError( true ); + } + setIsSaving( false ); + }; + + return ( + + + { hasError && ( + + + { __( 'The setting could not be saved. Try again.' ) } + + + ) } + + ); +} 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..0ca6429e9f8900 100644 --- a/routes/navigation-edit/stage.tsx +++ b/routes/navigation-edit/stage.tsx @@ -5,6 +5,7 @@ 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,6 +54,9 @@ function NavigationEditStage() { } >
+
+ +
diff --git a/routes/navigation-edit/style.module.scss b/routes/navigation-edit/style.module.scss index e89d20496ffb87..332b416028ee2c 100644 --- a/routes/navigation-edit/style.module.scss +++ b/routes/navigation-edit/style.module.scss @@ -5,3 +5,7 @@ background-color: var(--wpds-color-background-surface-neutral-strong); padding: var(--wpds-dimension-padding-lg) var(--wpds-dimension-padding-2xl); } + +.settings { + margin-bottom: var(--wpds-dimension-padding-lg); +} diff --git a/routes/navigation-edit/tsconfig.json b/routes/navigation-edit/tsconfig.json index 93336ef3214932..d822c8870236c4 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" }, - { "path": "../../packages/route" } + { "path": "../../packages/route" }, + { "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.js b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js new file mode 100644 index 00000000000000..edadacf135c639 --- /dev/null +++ b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js @@ -0,0 +1,110 @@ +const { test, expect } = require( '@wordpress/e2e-test-utils-playwright' ); + +const META_KEY = 'wp_navigation_auto_add_pages'; + +test.describe( 'Navigation block: Auto add pages', () => { + test.beforeEach( async ( { requestUtils } ) => { + await Promise.all( [ + requestUtils.deleteAllPages(), + requestUtils.deleteAllMenus(), + ] ); + } ); + + test.afterAll( async ( { requestUtils } ) => { + await Promise.all( [ + requestUtils.deleteAllPages(), + requestUtils.deleteAllMenus(), + ] ); + } ); + + test( 'the default menu links to the published pages and picks up new ones', async ( { + admin, + editor, + requestUtils, + } ) => { + await requestUtils.createPage( { title: 'About', status: 'publish' } ); + + await admin.createNewPost(); + await editor.insertBlock( { name: 'core/navigation' } ); + + const navigationBlock = editor.canvas.getByRole( 'document', { + name: 'Block: Navigation', + } ); + await expect( + navigationBlock.getByRole( 'document', { + name: 'Block: Page Link', + } ) + ).toContainText( 'About', { + // Wait for the menu and the fallback request to resolve. + timeout: 10000, + } ); + await expect( + navigationBlock.getByRole( 'document', { + name: 'Block: Page List', + } ) + ).toBeHidden(); + + const [ menu ] = await requestUtils.getNavigationMenus( { + status: 'publish', + } ); + expect( menu.meta[ META_KEY ] ).toBe( true ); + + const contact = await requestUtils.createPage( { + title: 'Contact', + status: 'publish', + } ); + const updatedMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + expect( updatedMenu.content.raw ).toContain( `"id":${ contact.id }` ); + } ); + + test( 'the setting can be turned off from the block settings', async ( { + admin, + editor, + page, + requestUtils, + } ) => { + const menu = await requestUtils.createNavigationMenu( { + title: 'Main menu', + content: + '', + meta: { [ META_KEY ]: true }, + } ); + + 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: 'Settings' } ).click(); + + const toggle = settings.getByRole( 'switch', { + name: 'Auto add pages', + } ); + await expect( toggle ).toBeChecked(); + await toggle.click(); + await expect( toggle ).not.toBeChecked(); + + // Saving the post also saves the menu. + await editor.publishPost(); + + const savedMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + expect( savedMenu.meta[ META_KEY ] ).toBe( false ); + + 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 ); + } ); +} ); diff --git a/test/e2e/specs/editor/blocks/navigation.spec.js b/test/e2e/specs/editor/blocks/navigation.spec.js index 80fc7936126c44..47448eddaada0f 100644 --- a/test/e2e/specs/editor/blocks/navigation.spec.js +++ b/test/e2e/specs/editor/blocks/navigation.spec.js @@ -20,19 +20,25 @@ test.describe( 'Navigation block', () => { ] ); } ); - test( 'default to a list of pages if there are no menus', async ( { + test( 'default to links to the published pages if there are no menus', async ( { admin, editor, + requestUtils, } ) => { + await requestUtils.createPage( { + title: 'About', + status: 'publish', + } ); + await admin.createNewPost(); await editor.insertBlock( { name: 'core/navigation' } ); - const pageListBlock = editor.canvas.getByRole( 'document', { - name: 'Block: Page List', + const pageLinkBlock = editor.canvas.getByRole( 'document', { + name: 'Block: Page Link', } ); - await expect( pageListBlock ).toBeVisible( { - // Wait for the Nav and Page List block API requests to resolve. + await expect( pageLinkBlock ).toContainText( 'About', { + // Wait for the Nav block and fallback API requests to resolve. // Note: avoid waiting on network requests as these are not perceivable // to the user. // See: https://github.com/WordPress/gutenberg/pull/45070#issuecomment-1373712007. diff --git a/test/e2e/specs/editor/collaboration/collaboration-undo-navigation-block.spec.ts b/test/e2e/specs/editor/collaboration/collaboration-undo-navigation-block.spec.ts index 9cd921388ea484..ad1607dbe13fde 100644 --- a/test/e2e/specs/editor/collaboration/collaboration-undo-navigation-block.spec.ts +++ b/test/e2e/specs/editor/collaboration/collaboration-undo-navigation-block.spec.ts @@ -11,8 +11,8 @@ import { type UserCredentials } from './fixtures/collaboration-utils'; * paragraph, inserts a navigation block via the slash inserter, and types * another paragraph. The navigation block is inserted without a `ref`, so * it requests the navigation fallback, which creates a wp_navigation - * entity containing a page-list block and assigns its id as the block's - * `ref`. This all happens while the collaboration session is live. + * entity containing a link block per page and assigns its id as the + * block's `ref`. This all happens while the collaboration session is live. * 2. User B joins the post afterwards and hydrates from the CRDT document. * 3. User B appends a single character to the second paragraph. * 4. User B pauses a couple of seconds (like a user noticing a typo), then @@ -85,8 +85,8 @@ test.describe( 'Collaboration - Undo with a navigation block', () => { } await requestUtils.deleteAllPages(); - // Ensure the navigation fallback menu's page-list has real - // items, so the navigation subtree is non-trivial. + // Ensure the navigation fallback menu has real items, so the + // navigation subtree is non-trivial. for ( const title of [ 'Alpha Page', 'Beta Page', 'Gamma Page' ] ) { await requestUtils.rest( { method: 'POST', @@ -172,7 +172,7 @@ test.describe( 'Collaboration - Undo with a navigation block', () => { // Wait for the navigation fallback to resolve on User A's // client: the block gets a `ref` to the created wp_navigation - // entity and renders its controlled page-list inner blocks. + // entity and renders its controlled page link inner blocks. await expect( async () => { const blocks = await editor.getBlocks(); const navigation = blocks.find( @@ -181,7 +181,7 @@ test.describe( 'Collaboration - Undo with a navigation block', () => { expect( navigation?.attributes?.ref ).toBeTruthy(); } ).toPass( { timeout: 20000 } ); await expect( - editor.canvas.locator( '.wp-block-pages-list__item' ).first() + editor.canvas.locator( '.wp-block-navigation-link' ).first() ).toBeVisible( { timeout: 20000 } ); // Deselect the navigation block so User A sits idle without @@ -198,13 +198,13 @@ test.describe( 'Collaboration - Undo with a navigation block', () => { await installNavEditCounter( page2 ); // Wait for User B to render the document, including the - // navigation block's controlled page-list subtree. + // navigation block's controlled page link subtree. await expect( async () => { const blocks = await editor2.getBlocks(); expect( JSON.stringify( blocks ) ).toContain( UNDO_TARGET ); } ).toPass( { timeout: 20000 } ); await expect( - editor2.canvas.locator( '.wp-block-pages-list__item' ).first() + editor2.canvas.locator( '.wp-block-navigation-link' ).first() ).toBeVisible( { timeout: 20000 } ); // User B appends a single character to the second paragraph. diff --git a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js new file mode 100644 index 00000000000000..70fc2e31edee7b --- /dev/null +++ b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js @@ -0,0 +1,77 @@ +const { test, expect } = require( '@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'; + +test.describe( 'Navigation menu screen: Auto add 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 as soon as it is changed', 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 }` + ) }` + ); + + const toggle = page.getByRole( 'switch', { name: 'Auto add pages' } ); + await expect( toggle ).not.toBeChecked(); + await toggle.click(); + await expect( toggle ).toBeChecked(); + + 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 }` ); + } ); +} ); From a578102fa6dfd82600907c770e2a4a41f75bf561 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Sat, 10 Oct 2026 12:14:05 -0500 Subject: [PATCH 02/30] Block Library: Link the changelog entry to the pull request Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RKwLg37vPNWxb2pUbFB6mS --- packages/block-library/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/block-library/CHANGELOG.md b/packages/block-library/CHANGELOG.md index 99f6cb5e9ccb95..769e3582f954a8 100644 --- a/packages/block-library/CHANGELOG.md +++ b/packages/block-library/CHANGELOG.md @@ -4,7 +4,7 @@ ### Enhancements -- Navigation: Add an "Auto add pages" menu setting. While it is on, publishing a top-level page appends a link to the menu, as classic menus do. The default menu a site creates for itself now starts as one link per published page with the setting on, instead of a Page List block. +- Navigation: Add an "Auto add pages" menu setting. While it is on, publishing a top-level page appends a link to the menu, as classic menus do. The default menu a site creates for itself now starts as one link per published page with the setting on, instead of a Page List block ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). ### Bug Fixes From 81307435384a92942a11fbd93bdde93ef60fb581 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Sat, 10 Oct 2026 12:32:18 -0500 Subject: [PATCH 03/30] Core Data: Refresh loaded Navigation Menus when a page is published The server appends a link to every menu with "Auto add pages" on, but the editor keeps its copy of the menu until a reload. Invalidate the loaded `wp_navigation` records when the page publish is received, the way saving a template invalidates the site record, so a Navigation block on the screen refetches and shows the new link. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RKwLg37vPNWxb2pUbFB6mS --- packages/core-data/CHANGELOG.md | 1 + packages/core-data/src/resolvers.js | 44 ++++++++++++------- .../blocks/navigation-auto-add-pages.spec.js | 37 ++++++++++++++++ 3 files changed, 67 insertions(+), 15 deletions(-) diff --git a/packages/core-data/CHANGELOG.md b/packages/core-data/CHANGELOG.md index 83fe7ffe56c69d..31a8ab8174887f 100644 --- a/packages/core-data/CHANGELOG.md +++ b/packages/core-data/CHANGELOG.md @@ -21,6 +21,7 @@ ### Enhancements +- Invalidate the loaded `wp_navigation` records when a page publish is received, so a Navigation block picks up the link that "Auto add pages" appended on the server without a reload ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). - Add the root-level `edit_root` field to the `Attachment` entity type — the edit root attachment's id, or `0` when the attachment was not created by editing another one; embeddable via the `wp:edit-root` link, exposed in the `edit` context ([#81803](https://github.com/WordPress/gutenberg/pull/81803)). - `Icon`: add the `keywords` field exposed by the icons REST endpoint ([#82367](https://github.com/WordPress/gutenberg/pull/82367)). - `__experimentalFetchLinkSuggestions`: add a `preferTypes` option to rank matches from one or more search types above the usual order ([#83408](https://github.com/WordPress/gutenberg/pull/83408)). diff --git a/packages/core-data/src/resolvers.js b/packages/core-data/src/resolvers.js index 066e2d4972b7db..a0e67da9c83e27 100644 --- a/packages/core-data/src/resolvers.js +++ b/packages/core-data/src/resolvers.js @@ -242,22 +242,36 @@ 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, kind, name ) => { - 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/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js index edadacf135c639..9069782fbce13d 100644 --- a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js @@ -60,6 +60,43 @@ test.describe( 'Navigation block: Auto add pages', () => { expect( updatedMenu.content.raw ).toContain( `"id":${ contact.id }` ); } ); + test( 'a navigation block in the editor shows the new link once the page is published', async ( { + admin, + editor, + requestUtils, + } ) => { + const menu = await requestUtils.createNavigationMenu( { + title: 'Main menu', + content: + '', + meta: { [ META_KEY ]: true }, + } ); + + 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( 'the setting can be turned off from the block settings', async ( { admin, editor, From 1502b6b5e7bffad523e0b53f774537fbaadec92e Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Sat, 10 Oct 2026 12:46:41 -0500 Subject: [PATCH 04/30] Extensible Site Editor: Save the "Auto add pages" setting from the Save button The navigation menu screen already saves the menu's items through the global Save button, so the setting becomes a pending edit to the same record instead of saving on its own. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RKwLg37vPNWxb2pUbFB6mS --- .../navigation-edit/auto-add-pages-toggle.tsx | 79 ++++++------------- .../navigation-auto-add-pages.spec.js | 28 ++++--- 2 files changed, 42 insertions(+), 65 deletions(-) diff --git a/routes/navigation-edit/auto-add-pages-toggle.tsx b/routes/navigation-edit/auto-add-pages-toggle.tsx index 15ba471b1849a4..3b27e711e13826 100644 --- a/routes/navigation-edit/auto-add-pages-toggle.tsx +++ b/routes/navigation-edit/auto-add-pages-toggle.tsx @@ -1,73 +1,42 @@ -import { store as coreStore } from '@wordpress/core-data'; -import { useDispatch, useSelect } from '@wordpress/data'; -import { useState } from '@wordpress/element'; +import { useEntityProp } from '@wordpress/core-data'; import { __ } from '@wordpress/i18n'; -import { Notice, Stack, SwitchControl } from '@wordpress/ui'; +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 >; +type NavigationMenuMeta = Record< string, unknown > & { + [ META_KEY ]?: boolean; }; /** - * The menu's "Auto add pages" setting. This screen has no save button, so a - * change is saved as soon as it is made, and only the setting is sent. + * The menu's "Auto add pages" setting. Like the menu's items, a change is an + * edit to the `wp_navigation` record and is saved from the Save button. * * @param props * @param props.id The `wp_navigation` post ID. */ export default function AutoAddPagesToggle( { id }: { id: number } ) { - const isEnabled = useSelect( - ( select ) => { - const record = select( coreStore ).getEditedEntityRecord( - 'postType', - NAVIGATION_POST_TYPE, - id - ) as NavigationMenuRecord | undefined; - return !! record?.meta?.[ META_KEY ]; - }, - [ id ] - ); - const [ isSaving, setIsSaving ] = useState( false ); - const [ hasError, setHasError ] = useState( false ); - const { saveEntityRecord } = useDispatch( coreStore ); - - const onCheckedChange = async ( value: boolean ) => { - setIsSaving( true ); - setHasError( false ); - try { - await saveEntityRecord( - 'postType', - NAVIGATION_POST_TYPE, - { id, meta: { [ META_KEY ]: value } }, - { throwOnError: true } - ); - } catch { - setHasError( true ); - } - setIsSaving( false ); - }; + const [ meta, setMeta ] = useEntityProp( + 'postType', + NAVIGATION_POST_TYPE, + 'meta', + id + ) as unknown as [ + NavigationMenuMeta | undefined, + ( meta: NavigationMenuMeta ) => void, + ]; return ( - - - { hasError && ( - - - { __( 'The setting could not be saved. Try again.' ) } - - + + checked={ !! meta?.[ META_KEY ] } + onCheckedChange={ ( value: boolean ) => + setMeta( { ...meta, [ META_KEY ]: value } ) + } + /> ); } diff --git a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js index 70fc2e31edee7b..a2352bd07fd472 100644 --- a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js @@ -31,7 +31,7 @@ test.describe( 'Navigation menu screen: Auto add pages', () => { await requestUtils.activateTheme( 'twentytwentyone' ); } ); - test( 'the setting is saved as soon as it is changed', async ( { + test( 'the setting is saved from the Save button with the rest of the menu', async ( { admin, page, requestUtils, @@ -54,15 +54,23 @@ test.describe( 'Navigation menu screen: Auto add pages', () => { await toggle.click(); await expect( toggle ).toBeChecked(); - 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 ); + // The change is one of the menu's pending edits, saved like its items. + await page + .getByRole( 'button', { name: /^Review \d+ changes?…$/ } ) + .click(); + await page + .getByRole( 'dialog', { name: 'Review changes' } ) + .getByRole( 'button', { name: 'Save', exact: true } ) + .click(); + await expect( + page.getByRole( 'button', { name: 'Saved', exact: true } ) + ).toBeVisible(); + + const savedMenu = await requestUtils.rest( { + path: `/wp/v2/navigation/${ menu.id }`, + params: { context: 'edit' }, + } ); + expect( savedMenu.meta[ META_KEY ] ).toBe( true ); const about = await requestUtils.createPage( { title: 'About', From ee3b21c70893bf298a2b0db33fe785522b1cc95e Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Sat, 10 Oct 2026 12:58:22 -0500 Subject: [PATCH 05/30] Navigation: Save the "Auto add pages" setting as soon as it changes The setting is saved on its own in both the block inspector and the extensible site editor's navigation screen, so it never appears as a pending change in a save flow. Only the setting is sent; the menu's items are left to the editor's own save. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RKwLg37vPNWxb2pUbFB6mS --- .../edit/auto-add-pages-control.tsx | 86 +++++++++++++------ .../navigation-edit/auto-add-pages-toggle.tsx | 79 +++++++++++------ .../blocks/navigation-auto-add-pages.spec.js | 18 +++- .../navigation-auto-add-pages.spec.js | 28 +++--- 4 files changed, 140 insertions(+), 71 deletions(-) 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 index 56b532632c8fc0..e5813f844c8fae 100644 --- a/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx +++ b/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx @@ -2,14 +2,16 @@ import { __experimentalToolsPanel as ToolsPanel, __experimentalToolsPanelItem as ToolsPanelItem, } from '@wordpress/components'; -import { useEntityProp } from '@wordpress/core-data'; +import { store as coreStore } from '@wordpress/core-data'; +import { useDispatch, useSelect } from '@wordpress/data'; +import { useState } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; -import { SwitchControl } from '@wordpress/ui'; +import { Notice, Stack, SwitchControl } from '@wordpress/ui'; const META_KEY = 'wp_navigation_auto_add_pages'; -type NavigationMenuMeta = Record< string, unknown > & { - [ META_KEY ]?: boolean; +type NavigationMenuRecord = { + meta?: Record< string, unknown >; }; type Props = { @@ -21,9 +23,11 @@ type Props = { }; /** - * Settings that belong to the Navigation Menu rather than to the block, so - * they are read from and written to the `wp_navigation` entity and saved with - * it. + * The menu's "Auto add pages" setting. + * + * It belongs to the Navigation Menu rather than to the block, and it is saved + * the moment it changes, on its own, so it never shows up as a pending change + * in the editor's save flow. * * @param props * @param props.menuId @@ -33,18 +37,36 @@ export default function AutoAddPagesControl( { menuId, dropdownMenuProps, }: Props ) { - const [ meta, setMeta ] = useEntityProp( - 'postType', - 'wp_navigation', - 'meta', - menuId - ) as unknown as [ - NavigationMenuMeta | undefined, - ( meta: NavigationMenuMeta ) => void, - ]; - const isEnabled = !! meta?.[ META_KEY ]; - const setEnabled = ( value: boolean ) => - setMeta( { ...meta, [ META_KEY ]: value } ); + const isEnabled = useSelect( + ( select ) => { + const record = select( coreStore ).getEntityRecord( + 'postType', + 'wp_navigation', + menuId + ) as NavigationMenuRecord | undefined; + return !! record?.meta?.[ META_KEY ]; + }, + [ menuId ] + ); + const [ isSaving, setIsSaving ] = useState( false ); + const [ hasError, setHasError ] = useState( false ); + const { saveEntityRecord } = useDispatch( coreStore ); + + const setEnabled = async ( value: boolean ) => { + setIsSaving( true ); + setHasError( false ); + try { + await saveEntityRecord( + 'postType', + 'wp_navigation', + { id: menuId, meta: { [ META_KEY ]: value } }, + { throwOnError: true } + ); + } catch { + setHasError( true ); + } + setIsSaving( false ); + }; return ( setEnabled( false ) } isShownByDefault > - + + { hasError && ( + + + { __( + 'The setting could not be saved. Try again.' + ) } + + ) } - checked={ isEnabled } - onCheckedChange={ setEnabled } - /> +
); diff --git a/routes/navigation-edit/auto-add-pages-toggle.tsx b/routes/navigation-edit/auto-add-pages-toggle.tsx index 3b27e711e13826..15ba471b1849a4 100644 --- a/routes/navigation-edit/auto-add-pages-toggle.tsx +++ b/routes/navigation-edit/auto-add-pages-toggle.tsx @@ -1,42 +1,73 @@ -import { useEntityProp } from '@wordpress/core-data'; +import { store as coreStore } from '@wordpress/core-data'; +import { useDispatch, useSelect } from '@wordpress/data'; +import { useState } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; -import { SwitchControl } from '@wordpress/ui'; +import { Notice, Stack, SwitchControl } from '@wordpress/ui'; const NAVIGATION_POST_TYPE = 'wp_navigation'; const META_KEY = 'wp_navigation_auto_add_pages'; -type NavigationMenuMeta = Record< string, unknown > & { - [ META_KEY ]?: boolean; +type NavigationMenuRecord = { + meta?: Record< string, unknown >; }; /** - * The menu's "Auto add pages" setting. Like the menu's items, a change is an - * edit to the `wp_navigation` record and is saved from the Save button. + * The menu's "Auto add pages" setting. This screen has no save button, so a + * change is saved as soon as it is made, and only the setting is sent. * * @param props * @param props.id The `wp_navigation` post ID. */ export default function AutoAddPagesToggle( { id }: { id: number } ) { - const [ meta, setMeta ] = useEntityProp( - 'postType', - NAVIGATION_POST_TYPE, - 'meta', - id - ) as unknown as [ - NavigationMenuMeta | undefined, - ( meta: NavigationMenuMeta ) => void, - ]; + const isEnabled = useSelect( + ( select ) => { + const record = select( coreStore ).getEditedEntityRecord( + 'postType', + NAVIGATION_POST_TYPE, + id + ) as NavigationMenuRecord | undefined; + return !! record?.meta?.[ META_KEY ]; + }, + [ id ] + ); + const [ isSaving, setIsSaving ] = useState( false ); + const [ hasError, setHasError ] = useState( false ); + const { saveEntityRecord } = useDispatch( coreStore ); + + const onCheckedChange = async ( value: boolean ) => { + setIsSaving( true ); + setHasError( false ); + try { + await saveEntityRecord( + 'postType', + NAVIGATION_POST_TYPE, + { id, meta: { [ META_KEY ]: value } }, + { throwOnError: true } + ); + } catch { + setHasError( true ); + } + setIsSaving( false ); + }; return ( - + + { hasError && ( + + + { __( 'The setting could not be saved. Try again.' ) } + + ) } - checked={ !! meta?.[ META_KEY ] } - onCheckedChange={ ( value: boolean ) => - setMeta( { ...meta, [ META_KEY ]: value } ) - } - /> + ); } diff --git a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js index 9069782fbce13d..6a903051f0692e 100644 --- a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js @@ -128,14 +128,26 @@ test.describe( 'Navigation block: Auto add pages', () => { await toggle.click(); await expect( toggle ).not.toBeChecked(); - // Saving the post also saves the menu. - await editor.publishPost(); + // The setting saves on its own, without the post being saved. + 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 ); + await expect( + page + .getByRole( 'region', { name: 'Editor top bar' } ) + .getByRole( 'button', { name: 'Publish', exact: true } ) + ).toBeVisible(); const savedMenu = await requestUtils.rest( { path: `/wp/v2/navigation/${ menu.id }`, params: { context: 'edit' }, } ); - expect( savedMenu.meta[ META_KEY ] ).toBe( false ); await requestUtils.createPage( { title: 'Later', status: 'publish' } ); const unchangedMenu = await requestUtils.rest( { diff --git a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js index a2352bd07fd472..70fc2e31edee7b 100644 --- a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js @@ -31,7 +31,7 @@ test.describe( 'Navigation menu screen: Auto add pages', () => { await requestUtils.activateTheme( 'twentytwentyone' ); } ); - test( 'the setting is saved from the Save button with the rest of the menu', async ( { + test( 'the setting is saved as soon as it is changed', async ( { admin, page, requestUtils, @@ -54,23 +54,15 @@ test.describe( 'Navigation menu screen: Auto add pages', () => { await toggle.click(); await expect( toggle ).toBeChecked(); - // The change is one of the menu's pending edits, saved like its items. - await page - .getByRole( 'button', { name: /^Review \d+ changes?…$/ } ) - .click(); - await page - .getByRole( 'dialog', { name: 'Review changes' } ) - .getByRole( 'button', { name: 'Save', exact: true } ) - .click(); - await expect( - page.getByRole( 'button', { name: 'Saved', exact: true } ) - ).toBeVisible(); - - const savedMenu = await requestUtils.rest( { - path: `/wp/v2/navigation/${ menu.id }`, - params: { context: 'edit' }, - } ); - expect( savedMenu.meta[ META_KEY ] ).toBe( true ); + 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', From 72ca92c2b7a781f62d00a05ab46506f2b266334a Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Wed, 14 Oct 2026 09:30:38 -0500 Subject: [PATCH 06/30] Block Editor: Keep controlled inner blocks references stable across a root reset When the root blocks are reset, the reducer preserves each controlled block's sub-tree but wrapped it in a new tree entry, so every nested controller saw a changed block list and reported it as an edit it did not make. Publishing a page refetches the template and resets the root blocks, and the Navigation block inside the header template part could report its stale children before it had applied the menu content refetched from the server, hiding the appended link until a reload. Reuse the previous entry when the preserved sub-tree is unchanged, and cover the "Show template" case in the auto-add e2e spec. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RKwLg37vPNWxb2pUbFB6mS --- packages/block-editor/CHANGELOG.md | 1 + packages/block-editor/src/store/reducer.ts | 26 +++++- .../block-editor/src/store/test/reducer.ts | 72 +++++++++++++++ .../blocks/navigation-auto-add-pages.spec.js | 91 +++++++++++++++++++ 4 files changed, 187 insertions(+), 3 deletions(-) diff --git a/packages/block-editor/CHANGELOG.md b/packages/block-editor/CHANGELOG.md index 5af0646907b4bf..f8057ef0424f32 100644 --- a/packages/block-editor/CHANGELOG.md +++ b/packages/block-editor/CHANGELOG.md @@ -4,6 +4,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)). - Position, Text shadow: Show the "Default" option as selected instead of the `Select` placeholder ([#85172](https://github.com/WordPress/gutenberg/pull/85172)). ## 19.0.0 (2026-10-20) diff --git a/packages/block-editor/src/store/reducer.ts b/packages/block-editor/src/store/reducer.ts index ea36b64c2ad9ef..b64986e55bf5de 100644 --- a/packages/block-editor/src/store/reducer.ts +++ b/packages/block-editor/src/store/reducer.ts @@ -652,14 +652,34 @@ const withBlockReset = if ( ! controlledOrder?.length ) { continue; } - 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 ) { existingEntry.innerBlocks = innerBlocks; } - 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 2ba9d486cb94df..7447d95d936656 100644 --- a/packages/block-editor/src/store/test/reducer.ts +++ b/packages/block-editor/src/store/test/reducer.ts @@ -2684,6 +2684,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 forget controlledInnerBlocks during full RESET_BLOCKS', () => { const templateBlock = partial< Block >( { clientId: 'template', diff --git a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js index 6a903051f0692e..b79504d6d80c88 100644 --- a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js @@ -2,6 +2,23 @@ const { test, expect } = require( '@wordpress/e2e-test-utils-playwright' ); const META_KEY = 'wp_navigation_auto_add_pages'; +async function enableShowTemplate( 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 pages', () => { test.beforeEach( async ( { requestUtils } ) => { await Promise.all( [ @@ -156,4 +173,78 @@ test.describe( 'Navigation block: Auto add pages', () => { } ); 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 requestUtils.createNavigationMenu( { + title: 'Main menu', + content: + '', + meta: { [ META_KEY ]: true }, + } ); + 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 ); + } ); + } ); + } ); } ); From af50ef064acd9edd515a153d04aa8812beaf56fe Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Wed, 14 Oct 2026 13:36:21 -0500 Subject: [PATCH 07/30] Navigation: Save the "Auto add pages" setting through the editor's save flow The setting is an edit to the menu record, so it now goes through `editEntityRecord` and is saved with the editor's other changes, like any other menu edit. The self-saving handler, its saving state and error notice are removed from both the block control and the extensible site editor toggle. The extensible site editor screen uses a Stack with a gap to space the toggle from the menu editor instead of a one-off margin rule. The two e2e tests that asserted the setting saved on its own now assert that the Save or Review changes button appears and that saving stores the setting. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RKwLg37vPNWxb2pUbFB6mS --- .../edit/auto-add-pages-control.tsx | 59 ++++++------------- .../navigation-edit/auto-add-pages-toggle.tsx | 53 +++++------------ routes/navigation-edit/stage.tsx | 7 ++- routes/navigation-edit/style.module.scss | 4 -- .../blocks/navigation-auto-add-pages.spec.js | 28 ++++++--- .../navigation-auto-add-pages.spec.js | 19 +++++- 6 files changed, 75 insertions(+), 95 deletions(-) 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 index e5813f844c8fae..c38be7de3309eb 100644 --- a/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx +++ b/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx @@ -4,9 +4,8 @@ import { } from '@wordpress/components'; import { store as coreStore } from '@wordpress/core-data'; import { useDispatch, useSelect } from '@wordpress/data'; -import { useState } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; -import { Notice, Stack, SwitchControl } from '@wordpress/ui'; +import { SwitchControl } from '@wordpress/ui'; const META_KEY = 'wp_navigation_auto_add_pages'; @@ -25,9 +24,9 @@ type Props = { /** * The menu's "Auto add pages" setting. * - * It belongs to the Navigation Menu rather than to the block, and it is saved - * the moment it changes, on its own, so it never shows up as a pending change - * in the editor's save flow. + * 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. * * @param props * @param props.menuId @@ -39,7 +38,7 @@ export default function AutoAddPagesControl( { }: Props ) { const isEnabled = useSelect( ( select ) => { - const record = select( coreStore ).getEntityRecord( + const record = select( coreStore ).getEditedEntityRecord( 'postType', 'wp_navigation', menuId @@ -48,24 +47,12 @@ export default function AutoAddPagesControl( { }, [ menuId ] ); - const [ isSaving, setIsSaving ] = useState( false ); - const [ hasError, setHasError ] = useState( false ); - const { saveEntityRecord } = useDispatch( coreStore ); + const { editEntityRecord } = useDispatch( coreStore ); - const setEnabled = async ( value: boolean ) => { - setIsSaving( true ); - setHasError( false ); - try { - await saveEntityRecord( - 'postType', - 'wp_navigation', - { id: menuId, meta: { [ META_KEY ]: value } }, - { throwOnError: true } - ); - } catch { - setHasError( true ); - } - setIsSaving( false ); + const setEnabled = ( value: boolean ) => { + editEntityRecord( 'postType', 'wp_navigation', menuId, { + meta: { [ META_KEY ]: value }, + } ); }; return ( @@ -80,26 +67,14 @@ export default function AutoAddPagesControl( { onDeselect={ () => setEnabled( false ) } isShownByDefault > - - - { hasError && ( - - - { __( - 'The setting could not be saved. Try again.' - ) } - - + + checked={ isEnabled } + onCheckedChange={ setEnabled } + /> ); diff --git a/routes/navigation-edit/auto-add-pages-toggle.tsx b/routes/navigation-edit/auto-add-pages-toggle.tsx index 15ba471b1849a4..f8ac07aad06eb5 100644 --- a/routes/navigation-edit/auto-add-pages-toggle.tsx +++ b/routes/navigation-edit/auto-add-pages-toggle.tsx @@ -1,8 +1,7 @@ import { store as coreStore } from '@wordpress/core-data'; import { useDispatch, useSelect } from '@wordpress/data'; -import { useState } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; -import { Notice, Stack, SwitchControl } from '@wordpress/ui'; +import { SwitchControl } from '@wordpress/ui'; const NAVIGATION_POST_TYPE = 'wp_navigation'; const META_KEY = 'wp_navigation_auto_add_pages'; @@ -12,8 +11,8 @@ type NavigationMenuRecord = { }; /** - * The menu's "Auto add pages" setting. This screen has no save button, so a - * change is saved as soon as it is made, and only the setting is sent. + * The menu's "Auto add pages" setting. A change is an edit to the menu record + * and is saved with the screen's other changes. * * @param props * @param props.id The `wp_navigation` post ID. @@ -30,44 +29,22 @@ export default function AutoAddPagesToggle( { id }: { id: number } ) { }, [ id ] ); - const [ isSaving, setIsSaving ] = useState( false ); - const [ hasError, setHasError ] = useState( false ); - const { saveEntityRecord } = useDispatch( coreStore ); + const { editEntityRecord } = useDispatch( coreStore ); - const onCheckedChange = async ( value: boolean ) => { - setIsSaving( true ); - setHasError( false ); - try { - await saveEntityRecord( - 'postType', - NAVIGATION_POST_TYPE, - { id, meta: { [ META_KEY ]: value } }, - { throwOnError: true } - ); - } catch { - setHasError( true ); - } - setIsSaving( false ); + const onCheckedChange = ( value: boolean ) => { + editEntityRecord( 'postType', NAVIGATION_POST_TYPE, id, { + meta: { [ META_KEY ]: value }, + } ); }; return ( - - - { hasError && ( - - - { __( 'The setting could not be saved. Try again.' ) } - - + + checked={ isEnabled } + onCheckedChange={ onCheckedChange } + /> ); } diff --git a/routes/navigation-edit/stage.tsx b/routes/navigation-edit/stage.tsx index 0ca6429e9f8900..97a8032173cacd 100644 --- a/routes/navigation-edit/stage.tsx +++ b/routes/navigation-edit/stage.tsx @@ -1,5 +1,6 @@ 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'; @@ -54,10 +55,10 @@ function NavigationEditStage() { } >
-
+ -
- + +
); diff --git a/routes/navigation-edit/style.module.scss b/routes/navigation-edit/style.module.scss index 332b416028ee2c..e89d20496ffb87 100644 --- a/routes/navigation-edit/style.module.scss +++ b/routes/navigation-edit/style.module.scss @@ -5,7 +5,3 @@ background-color: var(--wpds-color-background-surface-neutral-strong); padding: var(--wpds-dimension-padding-lg) var(--wpds-dimension-padding-2xl); } - -.settings { - margin-bottom: var(--wpds-dimension-padding-lg); -} diff --git a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js index b79504d6d80c88..02584e46bcec17 100644 --- a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js @@ -114,7 +114,7 @@ test.describe( 'Navigation block: Auto add pages', () => { ).toContainText( 'Auto added page', { timeout: 10000 } ); } ); - test( 'the setting can be turned off from the block settings', async ( { + test( 'turning the setting off is saved with the post', async ( { admin, editor, page, @@ -145,7 +145,26 @@ test.describe( 'Navigation block: Auto add pages', () => { await toggle.click(); await expect( toggle ).not.toBeChecked(); - // The setting saves on its own, without the post being saved. + // 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( { @@ -155,11 +174,6 @@ test.describe( 'Navigation block: Auto add pages', () => { return savedMenu.meta[ META_KEY ]; } ) .toBe( false ); - await expect( - page - .getByRole( 'region', { name: 'Editor top bar' } ) - .getByRole( 'button', { name: 'Publish', exact: true } ) - ).toBeVisible(); const savedMenu = await requestUtils.rest( { path: `/wp/v2/navigation/${ menu.id }`, diff --git a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js index 70fc2e31edee7b..454bffaabd9b9f 100644 --- a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js @@ -31,7 +31,7 @@ test.describe( 'Navigation menu screen: Auto add pages', () => { await requestUtils.activateTheme( 'twentytwentyone' ); } ); - test( 'the setting is saved as soon as it is changed', async ( { + test( 'the setting is saved with the menu', async ( { admin, page, requestUtils, @@ -54,6 +54,23 @@ test.describe( 'Navigation menu screen: Auto add pages', () => { 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( { From b3a1096b1d1b452ee9c4458e191c6c30646223f3 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 20 Oct 2026 12:22:09 -0500 Subject: [PATCH 08/30] Navigation: Nest an auto-added child page under its parent's link The "Auto add pages" hook skipped child pages, as classic menus do. It now adds a child page under the link to its parent when the menu has one: a Navigation Link for the parent becomes a Navigation Submenu with the same attributes, and an existing submenu gets the child appended. A menu with no link to the parent is left alone, so no orphan links are added. The page-link check is split out so the same match rule (page ID with the post-type kind or page type) finds the parent block. The toggle descriptions and the meta description no longer say "top-level". PHPUnit covers the link-to-submenu conversion, appending to an existing submenu, a grandchild, and a parent that is only linked by URL. The e2e spec publishes a child page and checks that the navigation block shows the parent as a submenu holding the child without a reload. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0199oMWAas4xDSnjTYeDtPxL --- .../navigation-auto-add-pages.php | 89 +++++++++--- packages/block-library/CHANGELOG.md | 2 +- .../edit/auto-add-pages-control.tsx | 2 +- phpunit/navigation-auto-add-pages-test.php | 131 ++++++++++++++++-- .../navigation-edit/auto-add-pages-toggle.tsx | 2 +- .../blocks/navigation-auto-add-pages.spec.js | 70 ++++++++++ 6 files changed, 264 insertions(+), 32 deletions(-) diff --git a/lib/compat/wordpress-7.2/navigation-auto-add-pages.php b/lib/compat/wordpress-7.2/navigation-auto-add-pages.php index c27dd45e50044d..70b1e11f3019bc 100644 --- a/lib/compat/wordpress-7.2/navigation-auto-add-pages.php +++ b/lib/compat/wordpress-7.2/navigation-auto-add-pages.php @@ -5,9 +5,11 @@ * Replaces the Page List block as the default content of a Navigation Menu. * The fallback menu a site creates for itself starts as individual link * blocks, one per published page, with the setting switched on. While it is - * on, publishing a new top-level page appends a link for it to the menu, the - * way classic menus do with their "Automatically add new top-level pages" - * option. Existing items are never reordered, renamed or removed. + * on, publishing a new page adds a link for it to the menu, the way classic + * menus do with their "Automatically add new top-level pages" option. A + * top-level page is appended to the menu; a child page is nested under its + * parent's link when the menu has one, which turns that link into a submenu. + * Existing items are never reordered, renamed or removed. * * @package gutenberg */ @@ -30,7 +32,7 @@ function gutenberg_register_navigation_auto_add_pages_meta() { 'wp_navigation_auto_add_pages', array( 'type' => 'boolean', - 'description' => __( 'Whether newly published top-level pages are added to the menu.', 'gutenberg' ), + 'description' => __( 'Whether newly published pages are added to the menu.', 'gutenberg' ), 'single' => true, 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', @@ -76,6 +78,25 @@ function gutenberg_navigation_build_page_link_block( $page, $inner_blocks = arra ); } +/** + * 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'], array( 'core/navigation-link', 'core/navigation-submenu' ), true ) ) { + return false; + } + if ( ! isset( $block['attrs']['id'] ) || (int) $block['attrs']['id'] !== (int) $page_id ) { + return false; + } + $kind = isset( $block['attrs']['kind'] ) ? $block['attrs']['kind'] : ''; + $type = isset( $block['attrs']['type'] ) ? $block['attrs']['type'] : ''; + return 'post-type' === $kind || 'page' === $type; +} + /** * Checks whether any block in a tree links to the given page. * @@ -85,13 +106,8 @@ function gutenberg_navigation_build_page_link_block( $page, $inner_blocks = arra */ function gutenberg_navigation_blocks_link_to_page( $blocks, $page_id ) { foreach ( $blocks as $block ) { - $is_link = in_array( $block['blockName'], array( 'core/navigation-link', 'core/navigation-submenu' ), true ); - if ( $is_link && isset( $block['attrs']['id'] ) && (int) $block['attrs']['id'] === (int) $page_id ) { - $kind = isset( $block['attrs']['kind'] ) ? $block['attrs']['kind'] : ''; - $type = isset( $block['attrs']['type'] ) ? $block['attrs']['type'] : ''; - if ( 'post-type' === $kind || 'page' === $type ) { - return true; - } + if ( gutenberg_navigation_block_links_to_page( $block, $page_id ) ) { + return true; } if ( ! empty( $block['innerBlocks'] ) && gutenberg_navigation_blocks_link_to_page( $block['innerBlocks'], $page_id ) ) { return true; @@ -102,12 +118,42 @@ function gutenberg_navigation_blocks_link_to_page( $blocks, $page_id ) { } /** - * Appends a link to a newly published top-level page to every Navigation Menu - * that has "Auto add pages" switched on. + * Nests a block under the first block in a tree that links to the given page. + * + * A Navigation Link for the page becomes a Navigation Submenu with the same + * attributes, so the link keeps working as before and gains a submenu. + * + * @param array[] $blocks Parsed blocks, modified in place. + * @param int $parent_id Page ID the parent block links to. + * @param array $new_block Parsed block to nest under the parent. + * @return bool Whether a parent block was found. + */ +function gutenberg_navigation_nest_block_under_page( &$blocks, $parent_id, $new_block ) { + foreach ( $blocks as &$block ) { + if ( gutenberg_navigation_block_links_to_page( $block, $parent_id ) ) { + $block['blockName'] = 'core/navigation-submenu'; + $block['innerBlocks'][] = $new_block; + $block['innerHTML'] = ''; + $block['innerContent'] = array_fill( 0, count( $block['innerBlocks'] ), null ); + return true; + } + if ( ! empty( $block['innerBlocks'] ) && gutenberg_navigation_nest_block_under_page( $block['innerBlocks'], $parent_id, $new_block ) ) { + return true; + } + } + + return false; +} + +/** + * Adds a link to a newly published page to every Navigation Menu that has + * "Auto add pages" switched on. * - * Mirrors `_wp_auto_add_pages_to_menu()` for classic menus: only the - * transition into `publish` counts, child pages are skipped, and a page the - * menu already links to is not added again. + * A top-level page is appended to the menu. 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. 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. @@ -117,9 +163,6 @@ function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status if ( 'publish' !== $new_status || 'publish' === $old_status || 'page' !== $post->post_type ) { return; } - if ( ! empty( $post->post_parent ) ) { - return; - } $menus = get_posts( array( @@ -138,7 +181,13 @@ function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status if ( gutenberg_navigation_blocks_link_to_page( $blocks, $post->ID ) ) { continue; } - $blocks[] = gutenberg_navigation_build_page_link_block( $post ); + + $link = gutenberg_navigation_build_page_link_block( $post ); + if ( empty( $post->post_parent ) ) { + $blocks[] = $link; + } elseif ( ! gutenberg_navigation_nest_block_under_page( $blocks, $post->post_parent, $link ) ) { + continue; + } wp_update_post( array( diff --git a/packages/block-library/CHANGELOG.md b/packages/block-library/CHANGELOG.md index 769e3582f954a8..4d56be7a60333b 100644 --- a/packages/block-library/CHANGELOG.md +++ b/packages/block-library/CHANGELOG.md @@ -4,7 +4,7 @@ ### Enhancements -- Navigation: Add an "Auto add pages" menu setting. While it is on, publishing a top-level page appends a link to the menu, as classic menus do. The default menu a site creates for itself now starts as one link per published page with the setting on, instead of a Page List block ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). +- Navigation: Add an "Auto add 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 appended, and a child page is nested under the link to its parent, which becomes a submenu. The default menu a site creates for itself now starts as one link per published page with the setting on, instead of a Page List block ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). ### 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 index c38be7de3309eb..0fd914b2c71f93 100644 --- a/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx +++ b/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx @@ -70,7 +70,7 @@ export default function AutoAddPagesControl( { assertSame( $content, get_post( $menu_id )->post_content ); } - public function test_child_pages_other_post_types_and_republished_pages_are_ignored() { + 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.' ); - $this->publish_new_page( - array( - 'post_title' => 'Child', - 'post_parent' => $parent_id, - ) - ); - $this->assertCount( 1, $this->get_menu_blocks( $menu_id ), 'A child page is not 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.' ); @@ -266,6 +258,127 @@ public function test_a_published_page_can_be_edited_by_a_user_without_unfiltered kses_remove_filters(); } + /* + * 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 ); + } + /* * Fallback menu. */ diff --git a/routes/navigation-edit/auto-add-pages-toggle.tsx b/routes/navigation-edit/auto-add-pages-toggle.tsx index f8ac07aad06eb5..d6ac3de659d386 100644 --- a/routes/navigation-edit/auto-add-pages-toggle.tsx +++ b/routes/navigation-edit/auto-add-pages-toggle.tsx @@ -41,7 +41,7 @@ export default function AutoAddPagesToggle( { id }: { id: number } ) { { ).toContainText( 'Auto added page', { timeout: 10000 } ); } ); + test( 'a child page is nested under the link to its parent', async ( { + admin, + editor, + requestUtils, + } ) => { + const parent = await requestUtils.createPage( { + title: 'Parent page', + status: 'publish', + } ); + const menu = await requestUtils.createNavigationMenu( { + title: 'Main menu', + content: ``, + meta: { [ META_KEY ]: true }, + } ); + 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' ), + } ); + 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( 'turning the setting off is saved with the post', async ( { admin, editor, From 72d407617e926beecdbe7dee96cbd8167b4f08c8 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Wed, 21 Oct 2026 15:17:24 -0500 Subject: [PATCH 09/30] Navigation: Test that a page created from the appender is added once Creating a published page from the Navigation block's link UI fires the auto-add hook before the editor has saved its own link. The hook appends a link on the server, and the editor's pending block edit shadows that copy and overwrites it on save, so the menu ends up with a single link. Add an e2e test that documents this flow and asserts the saved menu links to the new page exactly once. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0199oMWAas4xDSnjTYeDtPxL --- .../blocks/navigation-auto-add-pages.spec.js | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js index 5ab0a7b07847ec..b159a1513be5c2 100644 --- a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js @@ -184,6 +184,117 @@ test.describe( 'Navigation block: Auto add pages', () => { ] ); } ); + test( 'a page created from the navigation appender is not added twice', async ( { + admin, + editor, + page, + requestUtils, + } ) => { + const menu = await requestUtils.createNavigationMenu( { + title: 'Main menu', + content: + '', + meta: { [ META_KEY ]: true }, + } ); + + 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, From 717fc45cb0b041daa762583eee424fa243142088 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Mon, 26 Oct 2026 15:42:27 -0500 Subject: [PATCH 10/30] Navigation: Test that auto-add keeps a page title intact with no current user A scheduled page publishes from cron with no user, so kses filters the menu content on save. Cover that path alongside the existing author test. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0199oMWAas4xDSnjTYeDtPxL --- phpunit/navigation-auto-add-pages-test.php | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/phpunit/navigation-auto-add-pages-test.php b/phpunit/navigation-auto-add-pages-test.php index f32b4f05163ce7..d6ad7aaad9bc25 100644 --- a/phpunit/navigation-auto-add-pages-test.php +++ b/phpunit/navigation-auto-add-pages-test.php @@ -258,6 +258,21 @@ public function test_a_published_page_can_be_edited_by_a_user_without_unfiltered kses_remove_filters(); } + 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( '', true ); + wp_set_current_user( 0 ); + kses_init(); + + $page_id = $this->publish_new_page( array( 'post_title' => 'Tom & Jerry\'s "Day"' ) ); + + $blocks = $this->get_menu_blocks( $menu_id ); + $this->assertCount( 1, $blocks ); + $this->assert_page_link_block( $blocks[0], $page_id ); + kses_remove_filters(); + } + /* * Child pages. */ From 567ddae136eb27c62c2aa82e2ed46fb12bc41ef4 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Mon, 26 Oct 2026 15:47:57 -0500 Subject: [PATCH 11/30] Navigation: Document how a cron save re-encodes existing link labels With no current user, kses filters the menu content on save and entity-encodes string attributes such as labels. The no-user test now covers an existing link next to the auto-added one, and the test helper slashes fixture content the way wp_insert_post expects. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0199oMWAas4xDSnjTYeDtPxL --- phpunit/navigation-auto-add-pages-test.php | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/phpunit/navigation-auto-add-pages-test.php b/phpunit/navigation-auto-add-pages-test.php index d6ad7aaad9bc25..a6bfe80e4ceb44 100644 --- a/phpunit/navigation-auto-add-pages-test.php +++ b/phpunit/navigation-auto-add-pages-test.php @@ -59,7 +59,7 @@ private function create_menu( $content, $auto_add = null ) { 'post_type' => 'wp_navigation', 'post_status' => 'publish', 'post_title' => 'Menu', - 'post_content' => $content, + 'post_content' => wp_slash( $content ), ) ); if ( null !== $auto_add ) { @@ -261,15 +261,22 @@ public function test_a_published_page_can_be_edited_by_a_user_without_unfiltered 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( '', true ); + $menu_id = $this->create_menu( + '', + true + ); wp_set_current_user( 0 ); kses_init(); $page_id = $this->publish_new_page( array( 'post_title' => 'Tom & Jerry\'s "Day"' ) ); $blocks = $this->get_menu_blocks( $menu_id ); - $this->assertCount( 1, $blocks ); - $this->assert_page_link_block( $blocks[0], $page_id ); + $this->assertCount( 2, $blocks ); + // kses re-encodes block attributes on a save without `unfiltered_html`: + // the existing link keeps its structure and its label is entity-encoded, + // as it would be for any post saved by a user without that capability. + $this->assertSame( 'Tom & Jerry\'s', $blocks[0]['attrs']['label'] ); + $this->assert_page_link_block( $blocks[1], $page_id ); kses_remove_filters(); } From 0134ed299176de36d7f822ec5c93b48d35e2739b Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Mon, 26 Oct 2026 15:56:43 -0500 Subject: [PATCH 12/30] Navigation: Assert existing links survive a no-user auto-add save unchanged The no-user test compared an existing label against the entity-encoded form kses produces, which pins kses behavior the feature does not own. Compare the existing link block before and after the save instead. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0199oMWAas4xDSnjTYeDtPxL --- phpunit/navigation-auto-add-pages-test.php | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/phpunit/navigation-auto-add-pages-test.php b/phpunit/navigation-auto-add-pages-test.php index a6bfe80e4ceb44..bc40212e262053 100644 --- a/phpunit/navigation-auto-add-pages-test.php +++ b/phpunit/navigation-auto-add-pages-test.php @@ -262,9 +262,10 @@ public function test_a_page_published_with_no_current_user_is_added_with_its_tit // A scheduled page publishes from cron, where there is no user and // kses filters the menu content on save. $menu_id = $this->create_menu( - '', + '', true ); + $before = $this->get_menu_blocks( $menu_id ); wp_set_current_user( 0 ); kses_init(); @@ -272,10 +273,7 @@ public function test_a_page_published_with_no_current_user_is_added_with_its_tit $blocks = $this->get_menu_blocks( $menu_id ); $this->assertCount( 2, $blocks ); - // kses re-encodes block attributes on a save without `unfiltered_html`: - // the existing link keeps its structure and its label is entity-encoded, - // as it would be for any post saved by a user without that capability. - $this->assertSame( 'Tom & Jerry\'s', $blocks[0]['attrs']['label'] ); + $this->assertSame( $before[0], $blocks[0] ); $this->assert_page_link_block( $blocks[1], $page_id ); kses_remove_filters(); } From 4ff671e61e6a8c662abbde5517949fd254998029 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 27 Oct 2026 13:29:06 -0500 Subject: [PATCH 13/30] Navigation: Show the "Auto add pages" setting below the menu's list of links The setting belongs to the menu's content, not to the block, so it follows the List View of the menu's links in every place that list is shown: the block inspector's List View tab, the site editor's navigation sidebar, and the extensible site editor's navigation menu screen. It leaves the block's Settings tab, and the control guards itself with the user's permission to update the menu. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0199oMWAas4xDSnjTYeDtPxL --- .../edit/auto-add-pages-control.tsx | 62 ++++++------- .../src/navigation/edit/index.jsx | 11 --- .../edit/menu-inspector-controls.jsx | 4 + .../block-library/src/navigation/editor.scss | 5 ++ packages/block-library/src/private-apis.js | 2 + .../navigation-menu-editor.jsx | 4 + routes/navigation-edit/stage.tsx | 2 +- .../blocks/navigation-auto-add-pages.spec.js | 9 +- .../navigation-auto-add-pages.spec.js | 87 +++++++++++++++++++ 9 files changed, 137 insertions(+), 49 deletions(-) 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 index 0fd914b2c71f93..96495b6323e09b 100644 --- a/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx +++ b/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx @@ -1,7 +1,3 @@ -import { - __experimentalToolsPanel as ToolsPanel, - __experimentalToolsPanelItem as ToolsPanelItem, -} from '@wordpress/components'; import { store as coreStore } from '@wordpress/core-data'; import { useDispatch, useSelect } from '@wordpress/data'; import { __ } from '@wordpress/i18n'; @@ -16,9 +12,6 @@ type NavigationMenuRecord = { type Props = { /** The `wp_navigation` post the block displays. */ menuId: number; - dropdownMenuProps?: React.ComponentProps< - typeof ToolsPanel - >[ 'dropdownMenuProps' ]; }; /** @@ -26,29 +19,37 @@ type Props = { * * 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. + * edits. It renders nothing for a user who cannot update the menu. * * @param props * @param props.menuId - * @param props.dropdownMenuProps */ -export default function AutoAddPagesControl( { - menuId, - dropdownMenuProps, -}: Props ) { - const isEnabled = useSelect( +export default function AutoAddPagesControl( { menuId }: Props ) { + const { canUpdate, isEnabled } = useSelect( ( select ) => { - const record = select( coreStore ).getEditedEntityRecord( + const { canUser, getEditedEntityRecord } = select( coreStore ); + const record = getEditedEntityRecord( 'postType', 'wp_navigation', menuId ) as NavigationMenuRecord | undefined; - return !! record?.meta?.[ META_KEY ]; + return { + canUpdate: !! canUser( 'update', { + kind: 'postType', + name: 'wp_navigation', + id: menuId, + } ), + isEnabled: !! record?.meta?.[ META_KEY ], + }; }, [ menuId ] ); const { editEntityRecord } = useDispatch( coreStore ); + if ( ! canUpdate ) { + return null; + } + const setEnabled = ( value: boolean ) => { editEntityRecord( 'postType', 'wp_navigation', menuId, { meta: { [ META_KEY ]: value }, @@ -56,26 +57,15 @@ export default function AutoAddPagesControl( { }; return ( - setEnabled( false ) } - dropdownMenuProps={ dropdownMenuProps } - > - isEnabled } +
+ setEnabled( false ) } - isShownByDefault - > - - - + description={ __( + 'Add a link to each new page when it is published. A child page is added under the link to its parent.' + ) } + checked={ isEnabled } + onCheckedChange={ setEnabled } + /> +
); } diff --git a/packages/block-library/src/navigation/edit/index.jsx b/packages/block-library/src/navigation/edit/index.jsx index 432141880eb352..565eb2235d0af1 100644 --- a/packages/block-library/src/navigation/edit/index.jsx +++ b/packages/block-library/src/navigation/edit/index.jsx @@ -58,7 +58,6 @@ import { useInnerBlocks } from './use-inner-blocks'; import { detectColors } from './utils'; import ManageMenusButton from './manage-menus-button'; import MenuInspectorControls from './menu-inspector-controls'; -import AutoAddPagesControl from './auto-add-pages-control'; import DeletedNavigationWarning from './deleted-navigation-warning'; import AccessibleDescription from './accessible-description'; import AccessibleMenuDescription from './accessible-menu-description'; @@ -792,16 +791,6 @@ function Navigation( { const stylingInspectorControls = ( <> - { isEntityAvailable && - hasResolvedCanUserUpdateNavigationMenu && - canUserUpdateNavigationMenu && ( - - - - ) } { hasSubmenus && ( + { navigationMenu && ( + + ) } ); }; diff --git a/packages/block-library/src/navigation/editor.scss b/packages/block-library/src/navigation/editor.scss index db1d32328530c7..f92c19a1b5cfa5 100644 --- a/packages/block-library/src/navigation/editor.scss +++ b/packages/block-library/src/navigation/editor.scss @@ -644,6 +644,11 @@ 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. +.wp-block-navigation__auto-add-pages { + margin: $grid-unit-15 0 0 24px; +} + .editor-sidebar__panel .wp-block-navigation__submenu-header { margin-top: 0; margin-bottom: 0; diff --git a/packages/block-library/src/private-apis.js b/packages/block-library/src/private-apis.js index a4c22d41be633b..242d15632657e5 100644 --- a/packages/block-library/src/private-apis.js +++ b/packages/block-library/src/private-apis.js @@ -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 { lock } from './lock-unlock'; /** @@ -9,4 +10,5 @@ export const privateApis = {}; lock( privateApis, { NAVIGATION_OVERLAY_TEMPLATE_PART_AREA, NavigationLinkUI, + AutoAddPagesControl, } ); diff --git a/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/navigation-menu-editor.jsx b/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/navigation-menu-editor.jsx index 1cfa9ff2fc3275..61b92ad27ccd23 100644 --- a/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/navigation-menu-editor.jsx +++ b/packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/navigation-menu-editor.jsx @@ -3,10 +3,13 @@ import { useSelect } from '@wordpress/data'; import { BlockEditorProvider } from '@wordpress/block-editor'; import { createBlock } from '@wordpress/blocks'; import { __experimentalFetchLinkSuggestions as fetchLinkSuggestions } from '@wordpress/core-data'; +import { privateApis as blockLibraryPrivateApis } from '@wordpress/block-library'; import { unlock } from '../../lock-unlock'; import { store as editSiteStore } from '../../store'; import NavigationMenuContent from '../sidebar-navigation-screen-navigation-menus/navigation-menu-content'; +const { AutoAddPagesControl } = unlock( blockLibraryPrivateApis ); + const noop = () => {}; export default function NavigationMenuEditor( { navigationMenuId } ) { @@ -54,6 +57,7 @@ export default function NavigationMenuEditor( { navigationMenuId } ) { >
+
); diff --git a/routes/navigation-edit/stage.tsx b/routes/navigation-edit/stage.tsx index 97a8032173cacd..6c2cf1cd2e0330 100644 --- a/routes/navigation-edit/stage.tsx +++ b/routes/navigation-edit/stage.tsx @@ -56,8 +56,8 @@ function NavigationEditStage() { >
- +
diff --git a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js index b159a1513be5c2..263a089306c092 100644 --- a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js @@ -317,8 +317,15 @@ test.describe( 'Navigation block: Auto add pages', () => { const settings = page.getByRole( 'region', { name: 'Editor settings', } ); - await settings.getByRole( 'tab', { name: 'Settings' } ).click(); + 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 pages' ); const toggle = settings.getByRole( 'switch', { name: 'Auto add pages', } ); diff --git a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js index 454bffaabd9b9f..8b73064b2b357d 100644 --- a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js @@ -6,6 +6,87 @@ const isSiteEditorV2 = !! process.env.GUTENBERG_E2E_SITE_EDITOR_V2; const META_KEY = 'wp_navigation_auto_add_pages'; +test.describe( 'Navigation sidebar: Auto add 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 shown after the list 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 follows the menu's items and their appender. + await expect( + sidebar.locator( + 'xpath=.//*[@role="treegrid"]/following::*[@role="switch"]' + ) + ).toHaveAccessibleName( 'Auto add pages' ); + const toggle = sidebar.getByRole( 'switch', { + name: 'Auto add pages', + } ); + 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.describe( 'Navigation menu screen: Auto add pages', () => { test.skip( ! isSiteEditorV2, @@ -49,6 +130,12 @@ test.describe( 'Navigation menu screen: Auto add pages', () => { ) }` ); + // The setting follows the menu's items and their appender. + await expect( + page.locator( + 'xpath=//*[@role="treegrid"]/following::*[@role="switch"]' + ) + ).toHaveAccessibleName( 'Auto add pages' ); const toggle = page.getByRole( 'switch', { name: 'Auto add pages' } ); await expect( toggle ).not.toBeChecked(); await toggle.click(); From ffd4580e65b59a85c5bc147652bf51ec2e73401d Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 27 Oct 2026 14:00:37 -0500 Subject: [PATCH 14/30] Navigation: Shorten the "Auto add pages" description and set the control apart The description now reads "Automatically adds newly published pages to this navigation." The control sits below a line, with more room above and below it, so it reads as a setting of the menu rather than as another item in its list. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0199oMWAas4xDSnjTYeDtPxL --- .../src/navigation/edit/auto-add-pages-control.tsx | 2 +- packages/block-library/src/navigation/editor.scss | 6 ++++-- routes/navigation-edit/auto-add-pages-toggle.tsx | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) 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 index 96495b6323e09b..62af71aae6c1be 100644 --- a/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx +++ b/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx @@ -61,7 +61,7 @@ export default function AutoAddPagesControl( { menuId }: Props ) { Date: Tue, 27 Oct 2026 15:11:15 -0500 Subject: [PATCH 15/30] Core Data: Move the changelog entry under Unreleased Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0199oMWAas4xDSnjTYeDtPxL --- packages/core-data/CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/core-data/CHANGELOG.md b/packages/core-data/CHANGELOG.md index 928db1a1b40017..7743e7b154c198 100644 --- a/packages/core-data/CHANGELOG.md +++ b/packages/core-data/CHANGELOG.md @@ -2,6 +2,10 @@ ## 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 pages" appended on the server without a reload ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). + ### Internal - Convert the footnotes and private actions to TypeScript and type check the JavaScript ([#85078](https://github.com/WordPress/gutenberg/pull/85078)). @@ -36,7 +40,6 @@ ### Enhancements -- Invalidate the loaded `wp_navigation` records when a page publish is received, so a Navigation block picks up the link that "Auto add pages" appended on the server without a reload ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). - Add the root-level `edit_root` field to the `Attachment` entity type — the edit root attachment's id, or `0` when the attachment was not created by editing another one; embeddable via the `wp:edit-root` link, exposed in the `edit` context ([#81803](https://github.com/WordPress/gutenberg/pull/81803)). - `Icon`: add the `keywords` field exposed by the icons REST endpoint ([#82367](https://github.com/WordPress/gutenberg/pull/82367)). - `__experimentalFetchLinkSuggestions`: add a `preferTypes` option to rank matches from one or more search types above the usual order ([#83408](https://github.com/WordPress/gutenberg/pull/83408)). From f6bc656c33fe2c69dea43c071caa87afecfebc98 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Wed, 28 Oct 2026 11:25:34 -0500 Subject: [PATCH 16/30] Navigation: Rename the setting to "Auto add new pages" The label names what the switch does to future pages, and the help text now says when they are added instead of repeating the label. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01S1u1vfDfpUYw8PAkEUWnB7 --- .../navigation-auto-add-pages.php | 6 +++--- packages/block-library/CHANGELOG.md | 2 +- .../edit/auto-add-pages-control.tsx | 6 +++--- packages/core-data/CHANGELOG.md | 2 +- phpunit/navigation-auto-add-pages-test.php | 2 +- .../navigation-edit/auto-add-pages-toggle.tsx | 6 +++--- .../blocks/navigation-auto-add-pages.spec.js | 9 ++++++--- .../navigation-auto-add-pages.spec.js | 20 +++++++++++++------ 8 files changed, 32 insertions(+), 21 deletions(-) diff --git a/lib/compat/wordpress-7.2/navigation-auto-add-pages.php b/lib/compat/wordpress-7.2/navigation-auto-add-pages.php index 70b1e11f3019bc..212056c8f98c3c 100644 --- a/lib/compat/wordpress-7.2/navigation-auto-add-pages.php +++ b/lib/compat/wordpress-7.2/navigation-auto-add-pages.php @@ -1,6 +1,6 @@ { +test.describe( 'Navigation block: Auto add new pages', () => { test.beforeEach( async ( { requestUtils } ) => { await Promise.all( [ requestUtils.deleteAllPages(), @@ -325,10 +325,13 @@ test.describe( 'Navigation block: Auto add pages', () => { settings.locator( 'xpath=.//*[@role="treegrid"]/following::*[@role="switch"]' ) - ).toHaveAccessibleName( 'Auto add pages' ); + ).toHaveAccessibleName( 'Auto add new pages' ); const toggle = settings.getByRole( 'switch', { - name: 'Auto add pages', + 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(); diff --git a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js index 8b73064b2b357d..fe412f97b69f49 100644 --- a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js @@ -6,7 +6,7 @@ const isSiteEditorV2 = !! process.env.GUTENBERG_E2E_SITE_EDITOR_V2; const META_KEY = 'wp_navigation_auto_add_pages'; -test.describe( 'Navigation sidebar: Auto add pages', () => { +test.describe( 'Navigation sidebar: Auto add new pages', () => { test.skip( isSiteEditorV2, 'The extensible site editor has no navigation sidebar.' @@ -61,10 +61,13 @@ test.describe( 'Navigation sidebar: Auto add pages', () => { sidebar.locator( 'xpath=.//*[@role="treegrid"]/following::*[@role="switch"]' ) - ).toHaveAccessibleName( 'Auto add pages' ); + ).toHaveAccessibleName( 'Auto add new pages' ); const toggle = sidebar.getByRole( 'switch', { - name: 'Auto add pages', + name: 'Auto add new pages', } ); + 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(); @@ -87,7 +90,7 @@ test.describe( 'Navigation sidebar: Auto add pages', () => { } ); } ); -test.describe( 'Navigation menu screen: Auto add pages', () => { +test.describe( 'Navigation menu screen: Auto add new pages', () => { test.skip( ! isSiteEditorV2, 'Only the extensible site editor has a navigation menu screen.' @@ -135,8 +138,13 @@ test.describe( 'Navigation menu screen: Auto add pages', () => { page.locator( 'xpath=//*[@role="treegrid"]/following::*[@role="switch"]' ) - ).toHaveAccessibleName( 'Auto add pages' ); - const toggle = page.getByRole( 'switch', { name: 'Auto add pages' } ); + ).toHaveAccessibleName( 'Auto add new pages' ); + const toggle = page.getByRole( 'switch', { + name: 'Auto add new pages', + } ); + 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(); From dceab898afe211750ba33635799b15184bc6c3c5 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Thu, 29 Oct 2026 10:47:55 -0500 Subject: [PATCH 17/30] Navigation: Add new pages in page order and respect fallback opt-outs A newly published page now goes in among its sibling page links in page order (menu order, then title), as the Page List block sorts pages, instead of at the end. A menu with a Page List block is left alone, since the Page List already shows the page. The default menu callback now runs last on `wp_navigation_should_create_fallback`, so a theme or plugin returning false stops it from creating the menu. The help text now says the setting applies only to pages published from now on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01S1u1vfDfpUYw8PAkEUWnB7 --- .../navigation-auto-add-pages.php | 96 ++++++++-- .../edit/auto-add-pages-control.tsx | 2 +- phpunit/navigation-auto-add-pages-test.php | 166 ++++++++++++++++++ .../navigation-edit/auto-add-pages-toggle.tsx | 2 +- .../blocks/navigation-auto-add-pages.spec.js | 2 +- .../navigation-auto-add-pages.spec.js | 4 +- 6 files changed, 248 insertions(+), 24 deletions(-) diff --git a/lib/compat/wordpress-7.2/navigation-auto-add-pages.php b/lib/compat/wordpress-7.2/navigation-auto-add-pages.php index 212056c8f98c3c..4ea29f86d1fd78 100644 --- a/lib/compat/wordpress-7.2/navigation-auto-add-pages.php +++ b/lib/compat/wordpress-7.2/navigation-auto-add-pages.php @@ -118,26 +118,82 @@ function gutenberg_navigation_blocks_link_to_page( $blocks, $page_id ) { } /** - * Nests a block under the first block in a tree that links to the given page. + * Checks whether any block in a tree is a Page List block. + * + * @param array[] $blocks Parsed blocks. + * @return bool Whether the tree has a Page List block. + */ +function gutenberg_navigation_blocks_have_page_list( $blocks ) { + foreach ( $blocks as $block ) { + if ( 'core/page-list' === $block['blockName'] ) { + return true; + } + if ( ! empty( $block['innerBlocks'] ) && gutenberg_navigation_blocks_have_page_list( $block['innerBlocks'] ) ) { + 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. + */ +function gutenberg_navigation_insert_page_link( &$blocks, $page, $link ) { + $before = null; + $after = null; + foreach ( $blocks as $index => $block ) { + $sibling = isset( $block['attrs']['id'] ) && gutenberg_navigation_block_links_to_page( $block, $block['attrs']['id'] ) + ? get_post( $block['attrs']['id'] ) + : null; + if ( ! $sibling || 'page' !== $sibling->post_type ) { + continue; + } + $order = $sibling->menu_order <=> $page->menu_order; + if ( 0 === $order ) { + $order = strcasecmp( $sibling->post_title, $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, so the link keeps working as before and gains a submenu. * - * @param array[] $blocks Parsed blocks, modified in place. - * @param int $parent_id Page ID the parent block links to. - * @param array $new_block Parsed block to nest under the parent. + * @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, $parent_id, $new_block ) { +function gutenberg_navigation_nest_block_under_page( &$blocks, $page, $link ) { foreach ( $blocks as &$block ) { - if ( gutenberg_navigation_block_links_to_page( $block, $parent_id ) ) { - $block['blockName'] = 'core/navigation-submenu'; - $block['innerBlocks'][] = $new_block; - $block['innerHTML'] = ''; - $block['innerContent'] = array_fill( 0, count( $block['innerBlocks'] ), null ); + if ( gutenberg_navigation_block_links_to_page( $block, $page->post_parent ) ) { + $block['blockName'] = 'core/navigation-submenu'; + gutenberg_navigation_insert_page_link( $block['innerBlocks'], $page, $link ); + $block['innerHTML'] = ''; + $block['innerContent'] = array_fill( 0, count( $block['innerBlocks'] ), null ); return true; } - if ( ! empty( $block['innerBlocks'] ) && gutenberg_navigation_nest_block_under_page( $block['innerBlocks'], $parent_id, $new_block ) ) { + if ( ! empty( $block['innerBlocks'] ) && gutenberg_navigation_nest_block_under_page( $block['innerBlocks'], $page, $link ) ) { return true; } } @@ -149,9 +205,10 @@ function gutenberg_navigation_nest_block_under_page( &$blocks, $parent_id, $new_ * 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 appended to the menu. 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. Like `_wp_auto_add_pages_to_menu()` for classic + * 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, which + * 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. * @@ -178,14 +235,14 @@ function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status foreach ( $menus as $menu ) { $blocks = parse_blocks( $menu->post_content ); - if ( gutenberg_navigation_blocks_link_to_page( $blocks, $post->ID ) ) { + if ( gutenberg_navigation_blocks_have_page_list( $blocks ) || gutenberg_navigation_blocks_link_to_page( $blocks, $post->ID ) ) { continue; } $link = gutenberg_navigation_build_page_link_block( $post ); if ( empty( $post->post_parent ) ) { - $blocks[] = $link; - } elseif ( ! gutenberg_navigation_nest_block_under_page( $blocks, $post->post_parent, $link ) ) { + gutenberg_navigation_insert_page_link( $blocks, $post, $link ); + } elseif ( ! gutenberg_navigation_nest_block_under_page( $blocks, $post, $link ) ) { continue; } @@ -252,7 +309,8 @@ function gutenberg_navigation_get_page_link_blocks() { * List default. When no menu exists and there is no classic menu to convert, * the menu is created here with "Auto add new pages" switched on, and `false` is * returned so core does not create a second one: core then finds this menu as - * the most recently published one and returns it. + * the most recently published one and returns it. It runs last so that a + * theme or plugin returning `false` stops it from creating the menu. * * In WordPress Core this would be a change to * `WP_Navigation_Fallback::create_default_fallback()` instead. @@ -302,4 +360,4 @@ function gutenberg_navigation_create_fallback_with_pages( $should_create ) { return false; } -add_filter( 'wp_navigation_should_create_fallback', 'gutenberg_navigation_create_fallback_with_pages' ); +add_filter( 'wp_navigation_should_create_fallback', 'gutenberg_navigation_create_fallback_with_pages', PHP_INT_MAX ); 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 index abf44c387628f1..8f083d0100e8b7 100644 --- a/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx +++ b/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx @@ -61,7 +61,7 @@ export default function AutoAddPagesControl( { menuId }: Props ) { ', + 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'] ); @@ -403,6 +421,136 @@ public function test_a_child_page_whose_parent_is_not_in_the_menu_is_skipped() { * Fallback menu. */ + 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_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_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 ); + } + public function test_fallback_menu_is_built_from_page_links_with_the_setting_on() { $about_id = self::factory()->post->create( array( @@ -502,6 +650,24 @@ public function test_fallback_still_converts_a_classic_menu_first() { wp_delete_nav_menu( $menu_id ); } + public function test_fallback_is_not_created_when_a_theme_opts_out() { + self::factory()->post->create( array( 'post_type' => 'page' ) ); + // Added after the plugin's callback, as a theme's `functions.php` would. + add_filter( 'wp_navigation_should_create_fallback', '__return_false' ); + + $this->assertNull( WP_Navigation_Fallback::get_fallback() ); + $this->assertCount( + 0, + get_posts( + array( + 'post_type' => 'wp_navigation', + 'post_status' => 'any', + 'posts_per_page' => -1, + ) + ) + ); + } + public function test_fallback_rest_route_returns_the_page_link_menu() { wp_set_current_user( self::$admin_id ); $page_id = self::factory()->post->create( array( 'post_type' => 'page' ) ); diff --git a/routes/navigation-edit/auto-add-pages-toggle.tsx b/routes/navigation-edit/auto-add-pages-toggle.tsx index 054969b83d01ab..d571d13e2e2fab 100644 --- a/routes/navigation-edit/auto-add-pages-toggle.tsx +++ b/routes/navigation-edit/auto-add-pages-toggle.tsx @@ -41,7 +41,7 @@ export default function AutoAddPagesToggle( { id }: { id: number } ) { { name: 'Auto add new pages', } ); await expect( toggle ).toHaveAccessibleDescription( - 'Adds pages to this navigation when they are published.' + 'Pages published from now on are added to this menu. Existing pages are not.' ); await expect( toggle ).toBeChecked(); await toggle.click(); diff --git a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js index fe412f97b69f49..328477bc5c78e7 100644 --- a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js @@ -66,7 +66,7 @@ test.describe( 'Navigation sidebar: Auto add new pages', () => { name: 'Auto add new pages', } ); await expect( toggle ).toHaveAccessibleDescription( - 'Adds pages to this navigation when they are published.' + 'Pages published from now on are added to this menu. Existing pages are not.' ); await expect( toggle ).not.toBeChecked(); await toggle.click(); @@ -143,7 +143,7 @@ test.describe( 'Navigation menu screen: Auto add new pages', () => { name: 'Auto add new pages', } ); await expect( toggle ).toHaveAccessibleDescription( - 'Adds pages to this navigation when they are published.' + 'Pages published from now on are added to this menu. Existing pages are not.' ); await expect( toggle ).not.toBeChecked(); await toggle.click(); From 35484857b258f2a3f60dc1fd919ace40794001f2 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 13:11:02 -0600 Subject: [PATCH 18/30] Navigation: Keep the Page List as the default menu Add the "Auto add new pages" setting without deciding what the default menu should be. The menu a site creates for itself is a Page List block again, as on trunk. The fallback filter, the page tree builders only it used and their tests are removed, and the default menu tests are back to trunk's. Co-Authored-By: Claude Opus 5.5 --- .../navigation-auto-add-pages.php | 119 +--------------- packages/block-library/CHANGELOG.md | 2 +- phpunit/navigation-auto-add-pages-test.php | 133 +----------------- .../blocks/navigation-auto-add-pages.spec.js | 43 ------ .../specs/editor/blocks/navigation.spec.js | 16 +-- ...ollaboration-undo-navigation-block.spec.ts | 16 +-- 6 files changed, 20 insertions(+), 309 deletions(-) diff --git a/lib/compat/wordpress-7.2/navigation-auto-add-pages.php b/lib/compat/wordpress-7.2/navigation-auto-add-pages.php index 4ea29f86d1fd78..d5c43a188ce8f6 100644 --- a/lib/compat/wordpress-7.2/navigation-auto-add-pages.php +++ b/lib/compat/wordpress-7.2/navigation-auto-add-pages.php @@ -2,14 +2,11 @@ /** * Navigation menus: the "Auto add new pages" setting. * - * Replaces the Page List block as the default content of a Navigation Menu. - * The fallback menu a site creates for itself starts as individual link - * blocks, one per published page, with the setting switched on. While it is - * on, publishing a new page adds a link for it to the menu, the way classic - * menus do with their "Automatically add new top-level pages" option. A - * top-level page is appended to the menu; a child page is nested under its - * parent's link when the menu has one, which turns that link into a submenu. - * Existing items are never reordered, renamed or removed. + * While the setting is on, publishing a new page adds a link for it to the + * menu, the way classic menus do with their "Automatically add new top-level + * pages" option. A top-level page is appended to the menu; a child page is + * nested under its parent's link when the menu has one, which turns that link + * into a submenu. Existing items are never reordered, renamed or removed. * * @package gutenberg */ @@ -255,109 +252,3 @@ function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status } } add_action( 'transition_post_status', 'gutenberg_navigation_auto_add_page_on_publish', 10, 3 ); - -/** - * Builds link blocks for the published pages under a parent, recursively. - * - * @param int $parent_id Parent page ID, 0 for top-level pages. - * @param WP_Post[] $children Published pages grouped by `post_parent`. - * @return array[] Parsed blocks. - */ -function gutenberg_navigation_build_page_tree_blocks( $parent_id, $children ) { - $blocks = array(); - if ( empty( $children[ $parent_id ] ) ) { - return $blocks; - } - foreach ( $children[ $parent_id ] as $page ) { - $inner_blocks = gutenberg_navigation_build_page_tree_blocks( $page->ID, $children ); - $blocks[] = gutenberg_navigation_build_page_link_block( $page, $inner_blocks ); - } - return $blocks; -} - -/** - * Gets the link blocks for the site's published pages, nested like the Page - * List block renders them and in the same order. - * - * @return array[] Parsed blocks. - */ -function gutenberg_navigation_get_page_link_blocks() { - $pages = get_pages( - array( - 'sort_column' => 'menu_order,post_title', - 'order' => 'asc', - ) - ); - if ( empty( $pages ) ) { - return array(); - } - - $children = array(); - foreach ( $pages as $page ) { - $children[ $page->post_parent ][] = $page; - } - - return gutenberg_navigation_build_page_tree_blocks( 0, $children ); -} - -/** - * Creates the default fallback Navigation Menu from page links instead of a - * Page List block. - * - * `WP_Navigation_Fallback::get_fallback()` applies this filter before it - * looks for an existing menu, converts a classic menu, or creates its Page - * List default. When no menu exists and there is no classic menu to convert, - * the menu is created here with "Auto add new pages" switched on, and `false` is - * returned so core does not create a second one: core then finds this menu as - * the most recently published one and returns it. It runs last so that a - * theme or plugin returning `false` stops it from creating the menu. - * - * In WordPress Core this would be a change to - * `WP_Navigation_Fallback::create_default_fallback()` instead. - * - * @param bool $should_create Whether core should create a fallback menu. - * @return bool Whether core should still create a fallback menu. - */ -function gutenberg_navigation_create_fallback_with_pages( $should_create ) { - if ( ! $should_create ) { - return $should_create; - } - - $existing = get_posts( - array( - 'post_type' => 'wp_navigation', - 'post_status' => 'publish', - 'posts_per_page' => 1, - 'fields' => 'ids', - 'no_found_rows' => true, - ) - ); - if ( ! empty( $existing ) ) { - return $should_create; - } - - // Core converts a classic menu before falling back to its default; leave that path to core. - $classic_menus = wp_get_nav_menus(); - if ( ! empty( $classic_menus ) && ! is_wp_error( $classic_menus ) ) { - return $should_create; - } - - $menu_id = wp_insert_post( - array( - 'post_content' => wp_slash( serialize_blocks( gutenberg_navigation_get_page_link_blocks() ) ), - 'post_title' => _x( 'Navigation', 'Title of a Navigation menu', 'gutenberg' ), - 'post_name' => 'navigation', - 'post_status' => 'publish', - 'post_type' => 'wp_navigation', - ), - true - ); - if ( is_wp_error( $menu_id ) || empty( $menu_id ) ) { - return $should_create; - } - - update_post_meta( $menu_id, 'wp_navigation_auto_add_pages', true ); - - return false; -} -add_filter( 'wp_navigation_should_create_fallback', 'gutenberg_navigation_create_fallback_with_pages', PHP_INT_MAX ); diff --git a/packages/block-library/CHANGELOG.md b/packages/block-library/CHANGELOG.md index ae10a89fa9d72d..7b6aa425adfc82 100644 --- a/packages/block-library/CHANGELOG.md +++ b/packages/block-library/CHANGELOG.md @@ -4,7 +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 appended, and a child page is nested under the link to its parent, which becomes a submenu. The default menu a site creates for itself now starts as one link per published page with the setting on, instead of a Page List block ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). +- 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 appended, and a child page is nested under the link to its parent, which becomes a submenu ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). - Button: Add content controls (Text, Link to, Open in new tab, View) in the sidebar when the block is inside a Navigation block, and in the List View popover in a content-only section, so a Button in a menu edits like a Navigation Link ([#84854](https://github.com/WordPress/gutenberg/pull/84854)). ### Bug Fixes diff --git a/phpunit/navigation-auto-add-pages-test.php b/phpunit/navigation-auto-add-pages-test.php index 2f2a4ad1e86e45..d50099640dac39 100644 --- a/phpunit/navigation-auto-add-pages-test.php +++ b/phpunit/navigation-auto-add-pages-test.php @@ -8,7 +8,6 @@ /** * @covers ::gutenberg_register_navigation_auto_add_pages_meta * @covers ::gutenberg_navigation_auto_add_page_on_publish - * @covers ::gutenberg_navigation_create_fallback_with_pages */ class Gutenberg_Navigation_Auto_Add_Pages_Test extends WP_Test_REST_TestCase { const META_KEY = 'wp_navigation_auto_add_pages'; @@ -418,7 +417,7 @@ public function test_a_child_page_whose_parent_is_not_in_the_menu_is_skipped() { } /* - * Fallback menu. + * Where a page is added. */ public function test_a_page_is_inserted_in_page_order_among_the_page_links() { @@ -550,134 +549,4 @@ public function test_a_menu_with_a_page_list_is_untouched() { $this->assertSame( $top_level, get_post( $top_id )->post_content ); $this->assertSame( $nested, get_post( $nested_id )->post_content ); } - - public function test_fallback_menu_is_built_from_page_links_with_the_setting_on() { - $about_id = self::factory()->post->create( - array( - 'post_type' => 'page', - 'post_title' => 'About', - 'menu_order' => 2, - ) - ); - $contact_id = self::factory()->post->create( - array( - 'post_type' => 'page', - 'post_title' => 'Contact', - 'menu_order' => 1, - ) - ); - $team_id = self::factory()->post->create( - array( - 'post_type' => 'page', - 'post_title' => 'Team', - 'post_parent' => $about_id, - ) - ); - self::factory()->post->create( - array( - 'post_type' => 'page', - 'post_title' => 'Draft', - 'post_status' => 'draft', - ) - ); - - $fallback = WP_Navigation_Fallback::get_fallback(); - - $this->assertInstanceOf( WP_Post::class, $fallback ); - $this->assertSame( 'wp_navigation', $fallback->post_type ); - $this->assertTrue( (bool) get_post_meta( $fallback->ID, self::META_KEY, true ) ); - $this->assertStringNotContainsString( 'wp:page-list', $fallback->post_content ); - - $blocks = $this->get_menu_blocks( $fallback->ID ); - $this->assertCount( 2, $blocks, 'Only top-level published pages are top-level items.' ); - $this->assert_page_link_block( $blocks[0], $contact_id ); - - $about = $blocks[1]; - $this->assertSame( 'core/navigation-submenu', $about['blockName'], 'A page with children becomes a submenu.' ); - $this->assertSame( $about_id, $about['attrs']['id'] ); - $this->assertSame( 'About', $about['attrs']['label'] ); - $this->assertSame( 'page', $about['attrs']['type'] ); - $this->assertSame( 'post-type', $about['attrs']['kind'] ); - $this->assertCount( 1, $about['innerBlocks'] ); - $this->assert_page_link_block( $about['innerBlocks'][0], $team_id ); - } - - public function test_fallback_menu_with_no_pages_is_empty_with_the_setting_on() { - $fallback = WP_Navigation_Fallback::get_fallback(); - - $this->assertInstanceOf( WP_Post::class, $fallback ); - $this->assertSame( '', $fallback->post_content ); - $this->assertTrue( (bool) get_post_meta( $fallback->ID, self::META_KEY, true ) ); - } - - public function test_fallback_reuses_an_existing_menu_without_touching_its_setting() { - $menu_id = $this->create_menu( '' ); - self::factory()->post->create( array( 'post_type' => 'page' ) ); - - $fallback = WP_Navigation_Fallback::get_fallback(); - - $this->assertSame( $menu_id, $fallback->ID ); - $this->assertEmpty( get_post_meta( $menu_id, self::META_KEY, true ) ); - $this->assertCount( - 1, - get_posts( - array( - 'post_type' => 'wp_navigation', - 'post_status' => 'any', - 'posts_per_page' => -1, - ) - ) - ); - } - - public function test_fallback_still_converts_a_classic_menu_first() { - $menu_id = wp_create_nav_menu( 'Classic' ); - wp_update_nav_menu_item( - $menu_id, - 0, - array( - 'menu-item-title' => 'Classic Link', - 'menu-item-url' => 'https://example.com/classic', - 'menu-item-status' => 'publish', - ) - ); - self::factory()->post->create( array( 'post_type' => 'page' ) ); - - $fallback = WP_Navigation_Fallback::get_fallback(); - - $this->assertStringContainsString( 'Classic Link', $fallback->post_content ); - $this->assertEmpty( get_post_meta( $fallback->ID, self::META_KEY, true ) ); - wp_delete_nav_menu( $menu_id ); - } - - public function test_fallback_is_not_created_when_a_theme_opts_out() { - self::factory()->post->create( array( 'post_type' => 'page' ) ); - // Added after the plugin's callback, as a theme's `functions.php` would. - add_filter( 'wp_navigation_should_create_fallback', '__return_false' ); - - $this->assertNull( WP_Navigation_Fallback::get_fallback() ); - $this->assertCount( - 0, - get_posts( - array( - 'post_type' => 'wp_navigation', - 'post_status' => 'any', - 'posts_per_page' => -1, - ) - ) - ); - } - - public function test_fallback_rest_route_returns_the_page_link_menu() { - wp_set_current_user( self::$admin_id ); - $page_id = self::factory()->post->create( array( 'post_type' => 'page' ) ); - - $request = new WP_REST_Request( 'GET', '/wp-block-editor/v1/navigation-fallback' ); - $response = rest_get_server()->dispatch( $request ); - - $this->assertSame( 200, $response->get_status() ); - $menu_id = $response->get_data()['id']; - $this->assertTrue( (bool) get_post_meta( $menu_id, self::META_KEY, true ) ); - $this->assert_page_link_block( $this->get_menu_blocks( $menu_id )[0], $page_id ); - } } diff --git a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js index 43f784ed0295f3..a4792561a621d5 100644 --- a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js @@ -34,49 +34,6 @@ test.describe( 'Navigation block: Auto add new pages', () => { ] ); } ); - test( 'the default menu links to the published pages and picks up new ones', async ( { - admin, - editor, - requestUtils, - } ) => { - await requestUtils.createPage( { title: 'About', status: 'publish' } ); - - await admin.createNewPost(); - await editor.insertBlock( { name: 'core/navigation' } ); - - const navigationBlock = editor.canvas.getByRole( 'document', { - name: 'Block: Navigation', - } ); - await expect( - navigationBlock.getByRole( 'document', { - name: 'Block: Page Link', - } ) - ).toContainText( 'About', { - // Wait for the menu and the fallback request to resolve. - timeout: 10000, - } ); - await expect( - navigationBlock.getByRole( 'document', { - name: 'Block: Page List', - } ) - ).toBeHidden(); - - const [ menu ] = await requestUtils.getNavigationMenus( { - status: 'publish', - } ); - expect( menu.meta[ META_KEY ] ).toBe( true ); - - const contact = await requestUtils.createPage( { - title: 'Contact', - status: 'publish', - } ); - const updatedMenu = await requestUtils.rest( { - path: `/wp/v2/navigation/${ menu.id }`, - params: { context: 'edit' }, - } ); - expect( updatedMenu.content.raw ).toContain( `"id":${ contact.id }` ); - } ); - test( 'a navigation block in the editor shows the new link once the page is published', async ( { admin, editor, diff --git a/test/e2e/specs/editor/blocks/navigation.spec.js b/test/e2e/specs/editor/blocks/navigation.spec.js index 67ac82270d5bde..78970d0992c997 100644 --- a/test/e2e/specs/editor/blocks/navigation.spec.js +++ b/test/e2e/specs/editor/blocks/navigation.spec.js @@ -20,25 +20,19 @@ test.describe( 'Navigation block', () => { ] ); } ); - test( 'default to links to the published pages if there are no menus', async ( { + test( 'default to a list of pages if there are no menus', async ( { admin, editor, - requestUtils, } ) => { - await requestUtils.createPage( { - title: 'About', - status: 'publish', - } ); - await admin.createNewPost(); await editor.insertBlock( { name: 'core/navigation' } ); - const pageLinkBlock = editor.canvas.getByRole( 'document', { - name: 'Block: Page Link', + const pageListBlock = editor.canvas.getByRole( 'document', { + name: 'Block: Page List', } ); - await expect( pageLinkBlock ).toContainText( 'About', { - // Wait for the Nav block and fallback API requests to resolve. + await expect( pageListBlock ).toBeVisible( { + // Wait for the Nav and Page List block API requests to resolve. // Note: avoid waiting on network requests as these are not perceivable // to the user. // See: https://github.com/WordPress/gutenberg/pull/45070#issuecomment-1373712007. diff --git a/test/e2e/specs/editor/collaboration/collaboration-undo-navigation-block.spec.ts b/test/e2e/specs/editor/collaboration/collaboration-undo-navigation-block.spec.ts index ad1607dbe13fde..9cd921388ea484 100644 --- a/test/e2e/specs/editor/collaboration/collaboration-undo-navigation-block.spec.ts +++ b/test/e2e/specs/editor/collaboration/collaboration-undo-navigation-block.spec.ts @@ -11,8 +11,8 @@ import { type UserCredentials } from './fixtures/collaboration-utils'; * paragraph, inserts a navigation block via the slash inserter, and types * another paragraph. The navigation block is inserted without a `ref`, so * it requests the navigation fallback, which creates a wp_navigation - * entity containing a link block per page and assigns its id as the - * block's `ref`. This all happens while the collaboration session is live. + * entity containing a page-list block and assigns its id as the block's + * `ref`. This all happens while the collaboration session is live. * 2. User B joins the post afterwards and hydrates from the CRDT document. * 3. User B appends a single character to the second paragraph. * 4. User B pauses a couple of seconds (like a user noticing a typo), then @@ -85,8 +85,8 @@ test.describe( 'Collaboration - Undo with a navigation block', () => { } await requestUtils.deleteAllPages(); - // Ensure the navigation fallback menu has real items, so the - // navigation subtree is non-trivial. + // Ensure the navigation fallback menu's page-list has real + // items, so the navigation subtree is non-trivial. for ( const title of [ 'Alpha Page', 'Beta Page', 'Gamma Page' ] ) { await requestUtils.rest( { method: 'POST', @@ -172,7 +172,7 @@ test.describe( 'Collaboration - Undo with a navigation block', () => { // Wait for the navigation fallback to resolve on User A's // client: the block gets a `ref` to the created wp_navigation - // entity and renders its controlled page link inner blocks. + // entity and renders its controlled page-list inner blocks. await expect( async () => { const blocks = await editor.getBlocks(); const navigation = blocks.find( @@ -181,7 +181,7 @@ test.describe( 'Collaboration - Undo with a navigation block', () => { expect( navigation?.attributes?.ref ).toBeTruthy(); } ).toPass( { timeout: 20000 } ); await expect( - editor.canvas.locator( '.wp-block-navigation-link' ).first() + editor.canvas.locator( '.wp-block-pages-list__item' ).first() ).toBeVisible( { timeout: 20000 } ); // Deselect the navigation block so User A sits idle without @@ -198,13 +198,13 @@ test.describe( 'Collaboration - Undo with a navigation block', () => { await installNavEditCounter( page2 ); // Wait for User B to render the document, including the - // navigation block's controlled page link subtree. + // navigation block's controlled page-list subtree. await expect( async () => { const blocks = await editor2.getBlocks(); expect( JSON.stringify( blocks ) ).toContain( UNDO_TARGET ); } ).toPass( { timeout: 20000 } ); await expect( - editor2.canvas.locator( '.wp-block-navigation-link' ).first() + editor2.canvas.locator( '.wp-block-pages-list__item' ).first() ).toBeVisible( { timeout: 20000 } ); // User B appends a single character to the second paragraph. From 22441b7629e7621cdc09e32da05a895724d3d5dc Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 14:13:34 -0600 Subject: [PATCH 19/30] Navigation: Don't say a new top-level page is appended It goes in among the menu's page links in page order, so the file comment and the changelog now only say it is added. Co-Authored-By: Claude Opus 5.5 --- lib/compat/wordpress-7.2/navigation-auto-add-pages.php | 2 +- packages/block-library/CHANGELOG.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/compat/wordpress-7.2/navigation-auto-add-pages.php b/lib/compat/wordpress-7.2/navigation-auto-add-pages.php index d5c43a188ce8f6..800b6b01830577 100644 --- a/lib/compat/wordpress-7.2/navigation-auto-add-pages.php +++ b/lib/compat/wordpress-7.2/navigation-auto-add-pages.php @@ -4,7 +4,7 @@ * * While the setting is on, publishing a new page adds a link for it to the * menu, the way classic menus do with their "Automatically add new top-level - * pages" option. A top-level page is appended to the menu; a child page is + * pages" option. A top-level page is added to the menu; a child page is * nested under its parent's link when the menu has one, which turns that link * into a submenu. Existing items are never reordered, renamed or removed. * diff --git a/packages/block-library/CHANGELOG.md b/packages/block-library/CHANGELOG.md index 7b6aa425adfc82..43a52da072fd40 100644 --- a/packages/block-library/CHANGELOG.md +++ b/packages/block-library/CHANGELOG.md @@ -4,7 +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 appended, and a child page is nested under the link to its parent, which becomes a submenu ([#84508](https://github.com/WordPress/gutenberg/pull/84508)). +- 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)). - Button: Add content controls (Text, Link to, Open in new tab, View) in the sidebar when the block is inside a Navigation block, and in the List View popover in a content-only section, so a Button in a menu edits like a Navigation Link ([#84854](https://github.com/WordPress/gutenberg/pull/84854)). ### Bug Fixes From f2c120bdd5812713c9b717e572fc6096de654f49 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 14:23:17 -0600 Subject: [PATCH 20/30] Navigation: Keep "Auto add new pages" when duplicating a menu The site editor's Duplicate action copied only the title and content, so the copy of a menu with the setting on had it off. Co-Authored-By: Claude Opus 5.5 --- .../use-navigation-menu-handlers.js | 4 ++ .../navigation-auto-add-pages.spec.js | 39 +++++++++++++++++++ 2 files changed, 43 insertions(+) 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/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js index 328477bc5c78e7..a28270d4988ba9 100644 --- a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js @@ -88,6 +88,45 @@ test.describe( 'Navigation sidebar: Auto add new pages', () => { } ) .toBe( true ); } ); + + 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', () => { From 3aabb12e02463386f6d28a3f96f7ae23ba78c798 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 14:38:51 -0600 Subject: [PATCH 21/30] Navigation: Write the "Auto add new pages" e2e tests in TypeScript Trunk now requires new files in the e2e tests to be TypeScript (#84829). Menus with the setting on are created through the REST API, since `createNavigationMenu()` takes only a title and content. Co-Authored-By: Claude Opus 5.5 --- ...c.js => navigation-auto-add-pages.spec.ts} | 51 ++++++++++++------- ...c.js => navigation-auto-add-pages.spec.ts} | 2 +- 2 files changed, 35 insertions(+), 18 deletions(-) rename test/e2e/specs/editor/blocks/{navigation-auto-add-pages.spec.js => navigation-auto-add-pages.spec.ts} (91%) rename test/e2e/specs/site-editor/{navigation-auto-add-pages.spec.js => navigation-auto-add-pages.spec.ts} (98%) diff --git a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.ts similarity index 91% rename from test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js rename to test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.ts index a4792561a621d5..fd416719b5aea6 100644 --- a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.ts @@ -1,8 +1,25 @@ -const { test, expect } = require( '@wordpress/e2e-test-utils-playwright' ); +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'; -async function enableShowTemplate( page ) { +// `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 } ) @@ -39,11 +56,10 @@ test.describe( 'Navigation block: Auto add new pages', () => { editor, requestUtils, } ) => { - const menu = await requestUtils.createNavigationMenu( { + const menu = await createAutoAddMenu( requestUtils, { title: 'Main menu', content: '', - meta: { [ META_KEY ]: true }, } ); await admin.createNewPost( { @@ -76,14 +92,16 @@ test.describe( 'Navigation block: Auto add new pages', () => { editor, requestUtils, } ) => { - const parent = await requestUtils.createPage( { - title: 'Parent page', - status: 'publish', - } ); - const menu = await requestUtils.createNavigationMenu( { + 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: ``, - meta: { [ META_KEY ]: true }, } ); const child = await requestUtils.rest( { method: 'POST', @@ -124,7 +142,9 @@ test.describe( 'Navigation block: Auto add new pages', () => { // 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' ), + clientId: + ( await navigationBlock.getAttribute( 'data-block' ) ) ?? + undefined, } ); expect( menuBlocks ).toMatchObject( [ { @@ -147,11 +167,10 @@ test.describe( 'Navigation block: Auto add new pages', () => { page, requestUtils, } ) => { - const menu = await requestUtils.createNavigationMenu( { + const menu = await createAutoAddMenu( requestUtils, { title: 'Main menu', content: '', - meta: { [ META_KEY ]: true }, } ); await admin.createNewPost(); @@ -258,11 +277,10 @@ test.describe( 'Navigation block: Auto add new pages', () => { page, requestUtils, } ) => { - const menu = await requestUtils.createNavigationMenu( { + const menu = await createAutoAddMenu( requestUtils, { title: 'Main menu', content: '', - meta: { [ META_KEY ]: true }, } ); await admin.createNewPost(); @@ -359,11 +377,10 @@ test.describe( 'Navigation block: Auto add new pages', () => { page, requestUtils, } ) => { - const menu = await requestUtils.createNavigationMenu( { + const menu = await createAutoAddMenu( requestUtils, { title: 'Main menu', content: '', - meta: { [ META_KEY ]: true }, } ); await requestUtils.createTemplate( 'wp_template_part', { slug: 'header', diff --git a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.ts similarity index 98% rename from test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js rename to test/e2e/specs/site-editor/navigation-auto-add-pages.spec.ts index a28270d4988ba9..882994f491f1e1 100644 --- a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.js +++ b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.ts @@ -1,4 +1,4 @@ -const { test, expect } = require( '@wordpress/e2e-test-utils-playwright' ); +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`. From 68345dd58d7d82fd8fdc2e3c813cb66b8de36329 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 13:18:12 -0600 Subject: [PATCH 22/30] Navigation: Move the "Auto add new pages" PHP to the WordPress 7.3 compat folder WordPress 7.2 has branched, so new features now target 7.3. Co-Authored-By: Claude Opus 5.5 --- .../navigation-auto-add-pages.php | 0 lib/load.php | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename lib/compat/{wordpress-7.2 => wordpress-7.3}/navigation-auto-add-pages.php (100%) diff --git a/lib/compat/wordpress-7.2/navigation-auto-add-pages.php b/lib/compat/wordpress-7.3/navigation-auto-add-pages.php similarity index 100% rename from lib/compat/wordpress-7.2/navigation-auto-add-pages.php rename to lib/compat/wordpress-7.3/navigation-auto-add-pages.php diff --git a/lib/load.php b/lib/load.php index bc3315b7d656b1..06b8a8229e6724 100644 --- a/lib/load.php +++ b/lib/load.php @@ -156,10 +156,10 @@ function gutenberg_get_experiment_default( $name ) { require __DIR__ . '/compat/wordpress-7.2/kses.php'; require __DIR__ . '/compat/wordpress-7.2/media.php'; require __DIR__ . '/compat/wordpress-7.2/post.php'; -require __DIR__ . '/compat/wordpress-7.2/navigation-auto-add-pages.php'; // 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'; From 65dbee52784abf37811f3639d10adee94b66769e Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 14:06:15 -0600 Subject: [PATCH 23/30] Core Data: Put the changelog's Enhancements before Deprecations Co-Authored-By: Claude Opus 5.5 --- packages/core-data/CHANGELOG.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/core-data/CHANGELOG.md b/packages/core-data/CHANGELOG.md index 943b94d4397e4d..b6f0a87b57788a 100644 --- a/packages/core-data/CHANGELOG.md +++ b/packages/core-data/CHANGELOG.md @@ -2,14 +2,14 @@ ## Unreleased -### Deprecations - -- `useResourcePermissions`: Deprecate the `status`, `isResolving` and `hasResolved` return values; use the `canUser` selector with `useSelect` instead ([#87457](https://github.com/WordPress/gutenberg/pull/87457)). - ### 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)). +### Deprecations + +- `useResourcePermissions`: Deprecate the `status`, `isResolving` and `hasResolved` return values; use the `canUser` selector with `useSelect` instead ([#87457](https://github.com/WordPress/gutenberg/pull/87457)). + ### Bug Fixes - Footnotes: Skip items in the `footnotes` post meta that aren't footnotes, such as `null`, instead of throwing, which stopped the post from saving ([#86715](https://github.com/WordPress/gutenberg/pull/86715)). From a7bb3c6b50380d33546bf7c48a18ca555865a8b1 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 14:14:22 -0600 Subject: [PATCH 24/30] Navigation: Type the "Auto add new pages" PHP for strict PHPStan The WordPress 7.3 compat folder is analyzed at PHPStan's strict level. Give the block arrays value types, read nested block fields only when they are arrays, and state the void returns. A link whose page ID isn't numeric is skipped, as before. Co-Authored-By: Claude Opus 5.5 --- .../navigation-auto-add-pages.php | 83 ++++++++++++------- 1 file changed, 55 insertions(+), 28 deletions(-) diff --git a/lib/compat/wordpress-7.3/navigation-auto-add-pages.php b/lib/compat/wordpress-7.3/navigation-auto-add-pages.php index 800b6b01830577..a654df6b3a8030 100644 --- a/lib/compat/wordpress-7.3/navigation-auto-add-pages.php +++ b/lib/compat/wordpress-7.3/navigation-auto-add-pages.php @@ -16,6 +16,8 @@ * * The posts REST controller only exposes `meta` for post types that support * custom fields, so that support is added to `wp_navigation` as well. + * + * @return void */ function gutenberg_register_navigation_auto_add_pages_meta() { if ( registered_meta_key_exists( 'post', 'wp_navigation_auto_add_pages', 'wp_navigation' ) ) { @@ -47,9 +49,9 @@ function gutenberg_register_navigation_auto_add_pages_meta() { * 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. - * @return array A parsed block. + * @param WP_Post $page The page to link to. + * @param array $inner_blocks Optional. Parsed blocks nested under the link. + * @return array A parsed block. */ function gutenberg_navigation_build_page_link_block( $page, $inner_blocks = array() ) { return array( @@ -78,35 +80,39 @@ function gutenberg_navigation_build_page_link_block( $page, $inner_blocks = arra /** * 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. + * @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'], array( 'core/navigation-link', 'core/navigation-submenu' ), true ) ) { + if ( ! in_array( $block['blockName'] ?? null, array( 'core/navigation-link', 'core/navigation-submenu' ), true ) ) { return false; } - if ( ! isset( $block['attrs']['id'] ) || (int) $block['attrs']['id'] !== (int) $page_id ) { + $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( $block['attrs']['kind'] ) ? $block['attrs']['kind'] : ''; - $type = isset( $block['attrs']['type'] ) ? $block['attrs']['type'] : ''; + $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. + * @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'] ) && gutenberg_navigation_blocks_link_to_page( $block['innerBlocks'], $page_id ) ) { + if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) && gutenberg_navigation_blocks_link_to_page( $block['innerBlocks'], $page_id ) ) { return true; } } @@ -117,15 +123,18 @@ function gutenberg_navigation_blocks_link_to_page( $blocks, $page_id ) { /** * Checks whether any block in a tree is a Page List block. * - * @param array[] $blocks Parsed blocks. + * @param array $blocks Parsed blocks. * @return bool Whether the tree has a Page List block. */ function gutenberg_navigation_blocks_have_page_list( $blocks ) { foreach ( $blocks as $block ) { - if ( 'core/page-list' === $block['blockName'] ) { + if ( ! is_array( $block ) ) { + continue; + } + if ( 'core/page-list' === ( $block['blockName'] ?? null ) ) { return true; } - if ( ! empty( $block['innerBlocks'] ) && gutenberg_navigation_blocks_have_page_list( $block['innerBlocks'] ) ) { + if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) && gutenberg_navigation_blocks_have_page_list( $block['innerBlocks'] ) ) { return true; } } @@ -141,16 +150,22 @@ function gutenberg_navigation_blocks_have_page_list( $blocks ) { * 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. + * @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 ( $blocks as $index => $block ) { - $sibling = isset( $block['attrs']['id'] ) && gutenberg_navigation_block_links_to_page( $block, $block['attrs']['id'] ) - ? get_post( $block['attrs']['id'] ) + 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; @@ -176,21 +191,27 @@ function gutenberg_navigation_insert_page_link( &$blocks, $page, $link ) { * A Navigation Link for the page becomes a Navigation Submenu with the same * attributes, so the link keeps working as before and gains a submenu. * - * @param array[] $blocks Parsed blocks, modified in place. - * @param WP_Post $page The child page. - * @param array $link Parsed block linking to the page. + * @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 ) ) { - $block['blockName'] = 'core/navigation-submenu'; - gutenberg_navigation_insert_page_link( $block['innerBlocks'], $page, $link ); + 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( $block['innerBlocks'] ), null ); + $block['innerContent'] = array_fill( 0, count( $inner_blocks ), null ); return true; } - if ( ! empty( $block['innerBlocks'] ) && gutenberg_navigation_nest_block_under_page( $block['innerBlocks'], $page, $link ) ) { + if ( ! empty( $inner_blocks ) && gutenberg_navigation_nest_block_under_page( $inner_blocks, $page, $link ) ) { + $block['innerBlocks'] = $inner_blocks; return true; } } @@ -212,6 +233,7 @@ function gutenberg_navigation_nest_block_under_page( &$blocks, $page, $link ) { * @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 ) { @@ -243,6 +265,11 @@ function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status continue; } + /** + * The parsed blocks, with the link added. + * + * @var array, innerBlocks: array>, innerHTML: string, innerContent: array}> $blocks + */ wp_update_post( array( 'ID' => $menu->ID, From 28aaeddcbeddfbde9c4f2cf1068847f349ff4578 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 15:09:46 -0600 Subject: [PATCH 25/30] Navigation: Pin the "Auto add new pages" setting to the bottom of the site editor screens In the site editor's navigation sidebar, the setting is now the screen's footer, which sticks to the bottom of the sidebar. In the extensible site editor, it sits at the bottom of the menu screen and stays there while the list scrolls. Co-Authored-By: Claude Opus 5.5 --- .../edit/auto-add-pages-control.tsx | 13 ++++++- .../navigation-menu-editor.jsx | 4 -- .../single-navigation-menu.jsx | 12 ++++++ .../index.jsx | 2 + routes/navigation-edit/stage.tsx | 19 ++++++++-- routes/navigation-edit/style.module.scss | 18 +++++++++ .../navigation-auto-add-pages.spec.ts | 37 ++++++++++++++----- 7 files changed, 87 insertions(+), 18 deletions(-) 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 index 8f083d0100e8b7..b8d5818765a5a5 100644 --- a/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx +++ b/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx @@ -12,6 +12,11 @@ type NavigationMenuRecord = { 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; }; /** @@ -23,8 +28,12 @@ type Props = { * * @param props * @param props.menuId + * @param props.className */ -export default function AutoAddPagesControl( { menuId }: Props ) { +export default function AutoAddPagesControl( { + menuId, + className = 'wp-block-navigation__auto-add-pages', +}: Props ) { const { canUpdate, isEnabled } = useSelect( ( select ) => { const { canUser, getEditedEntityRecord } = select( coreStore ); @@ -57,7 +66,7 @@ export default function AutoAddPagesControl( { menuId }: Props ) { }; return ( -
+
{}; export default function NavigationMenuEditor( { navigationMenuId } ) { @@ -57,7 +54,6 @@ export default function NavigationMenuEditor( { navigationMenuId } ) { >
-
); 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..d4edc42ceee12b 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,14 @@ 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 ); + export default function SingleNavigationMenu( { navigationMenu, backPath, @@ -36,6 +40,14 @@ export default function SingleNavigationMenu( { description={ __( 'Navigation Menus are a curated collection of blocks that allow visitors to get around your site.' ) } + footer={ + navigationMenu?.id && ( + + ) + } > 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/routes/navigation-edit/stage.tsx b/routes/navigation-edit/stage.tsx index 6c2cf1cd2e0330..d0ab056e3e4893 100644 --- a/routes/navigation-edit/stage.tsx +++ b/routes/navigation-edit/stage.tsx @@ -55,9 +55,22 @@ 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/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.ts b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.ts index 882994f491f1e1..a220bea34d9743 100644 --- a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.ts +++ b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.ts @@ -1,3 +1,4 @@ +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 @@ -6,6 +7,21 @@ 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, @@ -31,7 +47,7 @@ test.describe( 'Navigation sidebar: Auto add new pages', () => { await requestUtils.activateTheme( 'twentytwentyone' ); } ); - test( 'the setting is shown after the list and saved with the menu', async ( { + test( 'the setting is pinned to the bottom of the sidebar and saved with the menu', async ( { admin, page, requestUtils, @@ -56,15 +72,15 @@ test.describe( 'Navigation sidebar: Auto add new pages', () => { } ) ).toBeVisible(); - // The setting follows the menu's items and their appender. - await expect( - sidebar.locator( - 'xpath=.//*[@role="treegrid"]/following::*[@role="switch"]' - ) - ).toHaveAccessibleName( 'Auto add new pages' ); - const toggle = sidebar.getByRole( 'switch', { + // 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( 'Pages published from now on are added to this menu. Existing pages are not.' ); @@ -172,7 +188,7 @@ test.describe( 'Navigation menu screen: Auto add new pages', () => { ) }` ); - // The setting follows the menu's items and their appender. + // The setting sits at the bottom of the screen, below the short menu. await expect( page.locator( 'xpath=//*[@role="treegrid"]/following::*[@role="switch"]' @@ -181,6 +197,9 @@ test.describe( 'Navigation menu screen: 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( 'Pages published from now on are added to this menu. Existing pages are not.' ); From 70ae5311d1de0c647575bff30d915eb475de7858 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Wed, 2 Dec 2026 14:36:01 -0600 Subject: [PATCH 26/30] Navigation: Keep auto-added links in edited menus, with markup, and beside scoped Page Lists - core-data: when a refetch brings content that changed on the server and the record has no unsaved changes, drop the blocks kept as a transient edit since its last save. A menu edited and saved earlier in the session now shows the link a page publish added, and its next save keeps it. - Save the menu with kses off and filter only the new link's label when the publisher can't post unfiltered HTML, so a page publish no longer strips the menu's existing markup or encodes its URLs. - Skip a menu only when one of its Page Lists shows the new page. A Page List limited to one parent page no longer stops other pages from being added. Co-Authored-By: Claude Opus 5.5 --- .../navigation-auto-add-pages.php | 62 +++++-- packages/core-data/CHANGELOG.md | 1 + packages/core-data/src/resolvers.ts | 35 ++++ .../src/test/resolvers.jsdom.test.ts | 106 ++++++++++++ phpunit/navigation-auto-add-pages-test.php | 151 ++++++++++++++++-- .../blocks/navigation-auto-add-pages.spec.ts | 86 ++++++++++ 6 files changed, 416 insertions(+), 25 deletions(-) diff --git a/lib/compat/wordpress-7.3/navigation-auto-add-pages.php b/lib/compat/wordpress-7.3/navigation-auto-add-pages.php index a654df6b3a8030..545dc4305464ff 100644 --- a/lib/compat/wordpress-7.3/navigation-auto-add-pages.php +++ b/lib/compat/wordpress-7.3/navigation-auto-add-pages.php @@ -51,13 +51,17 @@ function gutenberg_register_navigation_auto_add_pages_meta() { * * @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() ) { +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' => '' !== $page->post_title ? $page->post_title : __( '(no title)', 'gutenberg' ), + 'label' => $filter_label ? wp_kses_post( $label ) : $label, 'type' => 'page', 'id' => (int) $page->ID, 'url' => get_permalink( $page ), @@ -121,20 +125,29 @@ function gutenberg_navigation_blocks_link_to_page( $blocks, $page_id ) { } /** - * Checks whether any block in a tree is a Page List block. + * 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. - * @return bool Whether the tree has a Page List block. + * @param WP_Post $page The page. + * @return bool Whether a Page List block in the tree shows the page. */ -function gutenberg_navigation_blocks_have_page_list( $blocks ) { +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 ) ) { - return true; + $attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array(); + // Read as the Page List block reads it when it renders. + $parent_page_id = isset( $attrs['parentPageID'] ) && is_scalar( $attrs['parentPageID'] ) ? (int) $attrs['parentPageID'] : 0; + if ( 0 === $parent_page_id || in_array( $parent_page_id, get_post_ancestors( $page ), true ) ) { + return true; + } } - if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) && gutenberg_navigation_blocks_have_page_list( $block['innerBlocks'] ) ) { + if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) && gutenberg_navigation_page_list_shows_page( $block['innerBlocks'], $page ) ) { return true; } } @@ -225,7 +238,7 @@ function gutenberg_navigation_nest_block_under_page( &$blocks, $page, $link ) { * * 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, which + * 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. @@ -252,13 +265,16 @@ function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status ) ); + // Whether kses filters content saved by the current user. + $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_blocks_have_page_list( $blocks ) || gutenberg_navigation_blocks_link_to_page( $blocks, $post->ID ) ) { + 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 ); + $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 ) ) { @@ -270,12 +286,26 @@ function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status * * @var array, innerBlocks: array>, innerHTML: string, innerContent: array}> $blocks */ - wp_update_post( - array( - 'ID' => $menu->ID, - 'post_content' => wp_slash( 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). + if ( $filters_content ) { + kses_remove_filters(); + } + try { + wp_update_post( + array( + 'ID' => $menu->ID, + 'post_content' => wp_slash( serialize_blocks( $blocks ) ), + ) + ); + } finally { + if ( $filters_content ) { + kses_init_filters(); + } + } } } add_action( 'transition_post_status', 'gutenberg_navigation_auto_add_page_on_publish', 10, 3 ); diff --git a/packages/core-data/CHANGELOG.md b/packages/core-data/CHANGELOG.md index 18ff569e14b654..37094cfd0a9bb4 100644 --- a/packages/core-data/CHANGELOG.md +++ b/packages/core-data/CHANGELOG.md @@ -5,6 +5,7 @@ ### 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)). ## 9.3.0 (2026-12-02) diff --git a/packages/core-data/src/resolvers.ts b/packages/core-data/src/resolvers.ts index d858896a9d436a..69f6e66486fa85 100644 --- a/packages/core-data/src/resolvers.ts +++ b/packages/core-data/src/resolvers.ts @@ -263,7 +263,42 @@ 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 when nothing is unsaved and the editor parses the + // new content. + const fetchedContent = ( + record.content as { raw?: unknown } | undefined + )?.raw; + const shouldDropTransientEdits = + ! query && + !! entityConfig.transientEdits && + typeof fetchedContent === 'string' && + select.getEntityRecordEdits( kind, name, key )?.blocks !== + undefined && + ! select.hasEditsForEntityRecord( kind, name, key ) && + ( + select.getRawEntityRecord( kind, name, key ) as + { content?: unknown } | undefined + )?.content !== fetchedContent; + 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 ); diff --git a/packages/core-data/src/test/resolvers.jsdom.test.ts b/packages/core-data/src/test/resolvers.jsdom.test.ts index 8d14fa8b822e41..834fe7b8206aa5 100644 --- a/packages/core-data/src/test/resolvers.jsdom.test.ts +++ b/packages/core-data/src/test/resolvers.jsdom.test.ts @@ -427,6 +427,112 @@ describe( 'getEntityRecord', () => { expect( syncManager.load ).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 }, + }; + + async function refetch( { + storedContent, + fetchedContent, + hasUnsavedChanges, + }: { + storedContent: string; + fetchedContent: string; + hasUnsavedChanges: boolean; + } ) { + apiFetchMock.mockImplementation( () => ( { + json: () => + Promise.resolve( { + id: 1, + content: { raw: fetchedContent }, + } ), + } ) ); + const select = { + getRawEntityRecord: vi.fn( () => ( { + id: 1, + content: storedContent, + } ) ), + getEntityRecordEdits: vi.fn( () => ( { + blocks: [ { name: 'core/navigation-link' } ], + 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( { + storedContent: '', + fetchedContent: + '', + hasUnsavedChanges: false, + } ); + + 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( { + storedContent: '', + fetchedContent: + '', + hasUnsavedChanges: true, + } ); + + expect( dispatch ).not.toHaveBeenCalledWith( dropEditsAction ); + } ); + + it( 'keeps the blocks when the content is unchanged', async () => { + await refetch( { + storedContent: '', + fetchedContent: '', + hasUnsavedChanges: false, + } ); + + expect( dispatch ).not.toHaveBeenCalledWith( dropEditsAction ); + } ); + } ); } ); describe( 'getEntityRecords', () => { diff --git a/phpunit/navigation-auto-add-pages-test.php b/phpunit/navigation-auto-add-pages-test.php index d50099640dac39..69df133fbfb85b 100644 --- a/phpunit/navigation-auto-add-pages-test.php +++ b/phpunit/navigation-auto-add-pages-test.php @@ -29,6 +29,9 @@ 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() { @@ -94,6 +97,44 @@ private function publish_new_page( $args = array() ) { 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( '', @@ -261,38 +302,78 @@ public function test_every_menu_with_the_setting_on_receives_the_link() { $this->assert_page_link_block( $this->get_menu_blocks( $second_id )[0], $page_id ); } - public function test_a_published_page_can_be_edited_by_a_user_without_unfiltered_html() { + public function test_a_page_published_by_a_user_without_unfiltered_html_is_added() { $menu_id = $this->create_menu( '', true ); - $author = self::factory()->user->create( array( 'role' => 'author' ) ); - wp_set_current_user( $author ); - kses_init(); + $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_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( - '', - true - ); + $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 ); - kses_remove_filters(); } /* @@ -538,6 +619,58 @@ public function test_a_child_page_is_inserted_in_page_order_within_its_parent_su ); } + 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_menu_with_a_page_list_is_untouched() { $top_level = ''; $nested = ''; 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 index fd416719b5aea6..c6498694511483 100644 --- a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.ts +++ b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.ts @@ -87,6 +87,92 @@ test.describe( 'Navigation block: Auto add new pages', () => { ).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, From 10af3d9a78c4e5c23494f4fb6be73037331d080e Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Wed, 2 Dec 2026 15:26:39 -0600 Subject: [PATCH 27/30] Navigation: Address review round 1 on auto add new pages - core-data: drop a refetched record's transient blocks only when they still serialize to the saved content, so typing that continued in the same attribute after a save isn't lost. - Lift only the `content_save_pre` kses filter, at its own priority, for the menu save, instead of removing and re-adding every kses filter, so a site's other kses settings stay as they were. - Read a Page List's `parentPageID` as the block validates it, and count a page as listed only when its parent pages up to the Page List's are published, as the Page List renders them. - Correct the docblock on nesting: with submenus set to open on click, the parent's item opens the submenu, as in a Page List. Co-Authored-By: Claude Opus 5.5 --- .../navigation-auto-add-pages.php | 51 +++++++++++--- packages/core-data/src/resolvers.ts | 26 ++++--- .../src/test/resolvers.jsdom.test.ts | 68 ++++++++++++++----- phpunit/navigation-auto-add-pages-test.php | 65 ++++++++++++++++++ 4 files changed, 175 insertions(+), 35 deletions(-) diff --git a/lib/compat/wordpress-7.3/navigation-auto-add-pages.php b/lib/compat/wordpress-7.3/navigation-auto-add-pages.php index 545dc4305464ff..f6cfbb4ec49500 100644 --- a/lib/compat/wordpress-7.3/navigation-auto-add-pages.php +++ b/lib/compat/wordpress-7.3/navigation-auto-add-pages.php @@ -124,6 +124,29 @@ function gutenberg_navigation_blocks_link_to_page( $blocks, $page_id ) { 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. * @@ -141,9 +164,10 @@ function gutenberg_navigation_page_list_shows_page( $blocks, $page ) { } if ( 'core/page-list' === ( $block['blockName'] ?? null ) ) { $attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array(); - // Read as the Page List block reads it when it renders. - $parent_page_id = isset( $attrs['parentPageID'] ) && is_scalar( $attrs['parentPageID'] ) ? (int) $attrs['parentPageID'] : 0; - if ( 0 === $parent_page_id || in_array( $parent_page_id, get_post_ancestors( $page ), true ) ) { + // 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; } } @@ -202,7 +226,9 @@ function gutenberg_navigation_insert_page_link( &$blocks, $page, $link ) { * 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, so the link keeps working as before and gains a submenu. + * 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. @@ -265,8 +291,10 @@ function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status ) ); - // Whether kses filters content saved by the current user. - $filters_content = false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' ); + // Whether, and at which priority, kses filters content the current user + // saves. + $kses_priority = has_filter( 'content_save_pre', 'wp_filter_post_kses' ); + $filters_content = false !== $kses_priority; foreach ( $menus as $menu ) { $blocks = parse_blocks( $menu->post_content ); @@ -290,9 +318,10 @@ function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status // 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). - if ( $filters_content ) { - kses_remove_filters(); + // user, so only it is filtered (above), and the content filter is + // lifted for this save alone. + if ( false !== $kses_priority ) { + remove_filter( 'content_save_pre', 'wp_filter_post_kses', $kses_priority ); } try { wp_update_post( @@ -302,8 +331,8 @@ function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status ) ); } finally { - if ( $filters_content ) { - kses_init_filters(); + if ( false !== $kses_priority ) { + add_filter( 'content_save_pre', 'wp_filter_post_kses', $kses_priority ); } } } diff --git a/packages/core-data/src/resolvers.ts b/packages/core-data/src/resolvers.ts index 69f6e66486fa85..34173b8242dd52 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 { @@ -267,22 +268,31 @@ export const getEntityRecord = // 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 when nothing is unsaved and the editor parses the - // new content. + // 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. const fetchedContent = ( record.content as { raw?: unknown } | undefined )?.raw; + const getSavedContent = () => + ( + select.getRawEntityRecord( kind, name, key ) as + { content?: unknown } | undefined + )?.content; + const getTransientBlocks = () => + select.getEntityRecordEdits( kind, name, key )?.blocks as + Block[] | undefined; const shouldDropTransientEdits = ! query && !! entityConfig.transientEdits && typeof fetchedContent === 'string' && - select.getEntityRecordEdits( kind, name, key )?.blocks !== - undefined && + Array.isArray( getTransientBlocks() ) && ! select.hasEditsForEntityRecord( kind, name, key ) && - ( - select.getRawEntityRecord( kind, name, key ) as - { content?: unknown } | undefined - )?.content !== fetchedContent; + typeof getSavedContent() === 'string' && + getSavedContent() !== fetchedContent && + __unstableSerializeAndClean( getTransientBlocks()! ) === + getSavedContent(); registry.batch( () => { if ( shouldDropTransientEdits ) { diff --git a/packages/core-data/src/test/resolvers.jsdom.test.ts b/packages/core-data/src/test/resolvers.jsdom.test.ts index 834fe7b8206aa5..cdec9afe02cc5b 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 { @@ -446,15 +459,33 @@ describe( 'getEntityRecord', () => { 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, + storedContent = SAVED_CONTENT, fetchedContent, - hasUnsavedChanges, + hasUnsavedChanges = false, + label = 'Home', }: { - storedContent: string; + storedContent?: string; fetchedContent: string; - hasUnsavedChanges: boolean; + hasUnsavedChanges?: boolean; + // The label in the blocks held as an edit. + label?: string; } ) { apiFetchMock.mockImplementation( () => ( { json: () => @@ -469,7 +500,7 @@ describe( 'getEntityRecord', () => { content: storedContent, } ) ), getEntityRecordEdits: vi.fn( () => ( { - blocks: [ { name: 'core/navigation-link' } ], + blocks: [ createBlock( 'test/link', { label } ) ], selection: {}, } ) ), hasEditsForEntityRecord: vi.fn( () => hasUnsavedChanges ), @@ -493,10 +524,7 @@ describe( 'getEntityRecord', () => { it( 'drops the blocks when the content changed on the server and nothing is unsaved', async () => { await refetch( { - storedContent: '', - fetchedContent: - '', - hasUnsavedChanges: false, + fetchedContent: SAVED_CONTENT + SAVED_CONTENT, } ); expect( dispatch ).toHaveBeenCalledWith( dropEditsAction ); @@ -514,20 +542,28 @@ describe( 'getEntityRecord', () => { it( 'keeps the blocks when there are unsaved changes', async () => { await refetch( { - storedContent: '', - fetchedContent: - '', + 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 the content is unchanged', async () => { await refetch( { - storedContent: '', - fetchedContent: '', - hasUnsavedChanges: false, + fetchedContent: SAVED_CONTENT, } ); expect( dispatch ).not.toHaveBeenCalledWith( dropEditsAction ); diff --git a/phpunit/navigation-auto-add-pages-test.php b/phpunit/navigation-auto-add-pages-test.php index 69df133fbfb85b..c3f834910d79cc 100644 --- a/phpunit/navigation-auto-add-pages-test.php +++ b/phpunit/navigation-auto-add-pages-test.php @@ -333,6 +333,22 @@ public function test_a_page_published_by_a_user_without_unfiltered_html_leaves_t $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_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( @@ -671,6 +687,55 @@ public function test_a_page_shown_by_a_page_list_limited_to_its_ancestor_is_not_ $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 = ''; From d39b39b8a86734e15a57b287ba410832d226b70d Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Wed, 2 Dec 2026 15:53:04 -0600 Subject: [PATCH 28/30] Navigation: Address review round 2 on auto add new pages - core-data: don't drop a refetched record's transient blocks when a save changed its stored content while the request was out, since the response is then older than what was saved. - Lift every kses filter on the post fields for the menu save, at their own priorities, so the menu's title isn't filtered again either. - Sort titles by the new link ignoring accents as well as case, closer to the database collation the Page List sorts by. Co-Authored-By: Claude Opus 5.5 --- .../navigation-auto-add-pages.php | 42 +++++++++++++------ packages/core-data/src/resolvers.ts | 23 +++++++--- .../src/test/resolvers.jsdom.test.ts | 40 ++++++++++++++---- phpunit/navigation-auto-add-pages-test.php | 31 ++++++++++++++ 4 files changed, 110 insertions(+), 26 deletions(-) diff --git a/lib/compat/wordpress-7.3/navigation-auto-add-pages.php b/lib/compat/wordpress-7.3/navigation-auto-add-pages.php index f6cfbb4ec49500..0e61b375ed8564 100644 --- a/lib/compat/wordpress-7.3/navigation-auto-add-pages.php +++ b/lib/compat/wordpress-7.3/navigation-auto-add-pages.php @@ -209,7 +209,9 @@ function gutenberg_navigation_insert_page_link( &$blocks, $page, $link ) { } $order = $sibling->menu_order <=> $page->menu_order; if ( 0 === $order ) { - $order = strcasecmp( $sibling->post_title, $page->post_title ); + // 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; @@ -291,10 +293,23 @@ function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status ) ); - // Whether, and at which priority, kses filters content the current user - // saves. - $kses_priority = has_filter( 'content_save_pre', 'wp_filter_post_kses' ); - $filters_content = false !== $kses_priority; + // 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 ); @@ -314,25 +329,28 @@ function gutenberg_navigation_auto_add_page_on_publish( $new_status, $old_status * * @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 content filter is - // lifted for this save alone. - if ( false !== $kses_priority ) { - remove_filter( 'content_save_pre', 'wp_filter_post_kses', $kses_priority ); + // 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( serialize_blocks( $blocks ) ), + 'post_content' => wp_slash( $content ), ) ); } finally { - if ( false !== $kses_priority ) { - add_filter( 'content_save_pre', 'wp_filter_post_kses', $kses_priority ); + foreach ( $kses_filters as list( $hook, $callback, $priority ) ) { + add_filter( $hook, $callback, $priority ); } } } diff --git a/packages/core-data/src/resolvers.ts b/packages/core-data/src/resolvers.ts index 34173b8242dd52..421922641f2f61 100644 --- a/packages/core-data/src/resolvers.ts +++ b/packages/core-data/src/resolvers.ts @@ -135,6 +135,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( @@ -271,15 +285,11 @@ export const getEntityRecord = // 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. + // 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 getSavedContent = () => - ( - select.getRawEntityRecord( kind, name, key ) as - { content?: unknown } | undefined - )?.content; const getTransientBlocks = () => select.getEntityRecordEdits( kind, name, key )?.blocks as Block[] | undefined; @@ -290,6 +300,7 @@ export const getEntityRecord = Array.isArray( getTransientBlocks() ) && ! select.hasEditsForEntityRecord( kind, name, key ) && typeof getSavedContent() === 'string' && + getSavedContent() === savedContentBeforeFetch && getSavedContent() !== fetchedContent && __unstableSerializeAndClean( getTransientBlocks()! ) === getSavedContent(); diff --git a/packages/core-data/src/test/resolvers.jsdom.test.ts b/packages/core-data/src/test/resolvers.jsdom.test.ts index cdec9afe02cc5b..0b868e8383b452 100644 --- a/packages/core-data/src/test/resolvers.jsdom.test.ts +++ b/packages/core-data/src/test/resolvers.jsdom.test.ts @@ -477,27 +477,37 @@ describe( 'getEntityRecord', () => { 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; } ) { - apiFetchMock.mockImplementation( () => ( { - json: () => - Promise.resolve( { - id: 1, - content: { raw: fetchedContent }, - } ), - } ) ); + let hasFetched = false; + apiFetchMock.mockImplementation( () => { + hasFetched = true; + return { + json: () => + Promise.resolve( { + id: 1, + content: { raw: fetchedContent }, + } ), + }; + } ); const select = { getRawEntityRecord: vi.fn( () => ( { id: 1, - content: storedContent, + content: hasFetched + ? storedContent + : storedContentBeforeFetch, } ) ), getEntityRecordEdits: vi.fn( () => ( { blocks: [ createBlock( 'test/link', { label } ) ], @@ -561,6 +571,20 @@ describe( 'getEntityRecord', () => { 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, diff --git a/phpunit/navigation-auto-add-pages-test.php b/phpunit/navigation-auto-add-pages-test.php index c3f834910d79cc..ac93ac3f765abc 100644 --- a/phpunit/navigation-auto-add-pages-test.php +++ b/phpunit/navigation-auto-add-pages-test.php @@ -349,6 +349,25 @@ public function test_publishing_leaves_the_kses_filters_as_they_were() { $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( @@ -593,6 +612,18 @@ public function test_pages_with_the_same_order_are_sorted_by_title() { ); } + 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( From 6b70b5746b77f4144263b640a21459977a7b0c03 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Wed, 2 Dec 2026 16:15:04 -0600 Subject: [PATCH 29/30] Navigation: Address review round 3 on auto add new pages - Render the switch only when the menu's REST meta lists the setting, so a WordPress release without the server side doesn't show a switch that resets after saving. - Keep the site editor's menu screen in place while the menu is fetched again after a page publish, instead of swapping it for a spinner, which dropped focus. - Describe the setting as "Adds pages to this navigation when they are published.", the wording the Page List PR uses: the old copy said existing pages are never added, but a draft is added when it publishes. - Cover `getEntityRecord.shouldInvalidate` for menus with unit tests. Co-Authored-By: Claude Opus 5.5 --- .../edit/auto-add-pages-control.tsx | 11 ++-- .../auto-add-pages-control.jsdom.test.tsx | 60 +++++++++++++++++++ .../src/test/resolvers.jsdom.test.ts | 43 +++++++++++++ .../index.jsx | 5 +- .../navigation-edit/auto-add-pages-toggle.tsx | 45 ++++++++++---- routes/navigation-edit/stage.tsx | 7 ++- .../blocks/navigation-auto-add-pages.spec.ts | 2 +- .../navigation-auto-add-pages.spec.ts | 54 ++++++++++++++++- 8 files changed, 203 insertions(+), 24 deletions(-) create mode 100644 packages/block-library/src/navigation/edit/test/auto-add-pages-control.jsdom.test.tsx 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 index b8d5818765a5a5..019308a955a7a6 100644 --- a/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx +++ b/packages/block-library/src/navigation/edit/auto-add-pages-control.tsx @@ -24,7 +24,8 @@ type Props = { * * 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. + * 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 @@ -34,7 +35,7 @@ export default function AutoAddPagesControl( { menuId, className = 'wp-block-navigation__auto-add-pages', }: Props ) { - const { canUpdate, isEnabled } = useSelect( + const { canUpdate, hasSetting, isEnabled } = useSelect( ( select ) => { const { canUser, getEditedEntityRecord } = select( coreStore ); const record = getEditedEntityRecord( @@ -48,6 +49,8 @@ export default function AutoAddPagesControl( { 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 ], }; }, @@ -55,7 +58,7 @@ export default function AutoAddPagesControl( { ); const { editEntityRecord } = useDispatch( coreStore ); - if ( ! canUpdate ) { + if ( ! canUpdate || ! hasSetting ) { return null; } @@ -70,7 +73,7 @@ export default function AutoAddPagesControl( { | 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/core-data/src/test/resolvers.jsdom.test.ts b/packages/core-data/src/test/resolvers.jsdom.test.ts index 0b868e8383b452..7ad33892d79685 100644 --- a/packages/core-data/src/test/resolvers.jsdom.test.ts +++ b/packages/core-data/src/test/resolvers.jsdom.test.ts @@ -595,6 +595,49 @@ describe( 'getEntityRecord', () => { } ); } ); +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', () => { const POST_TYPES = { post: { slug: 'post' }, 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/routes/navigation-edit/auto-add-pages-toggle.tsx b/routes/navigation-edit/auto-add-pages-toggle.tsx index d571d13e2e2fab..8fda4ed8829ac0 100644 --- a/routes/navigation-edit/auto-add-pages-toggle.tsx +++ b/routes/navigation-edit/auto-add-pages-toggle.tsx @@ -12,20 +12,33 @@ type NavigationMenuRecord = { /** * 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. + * 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.id The `wp_navigation` post ID. + * @param props.className Class for the wrapper. */ -export default function AutoAddPagesToggle( { id }: { id: number } ) { - const isEnabled = useSelect( +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 !! record?.meta?.[ META_KEY ]; + return { + // The REST API lists every registered meta key. + hasSetting: !! record?.meta && META_KEY in record.meta, + isEnabled: !! record?.meta?.[ META_KEY ], + }; }, [ id ] ); @@ -37,14 +50,20 @@ export default function AutoAddPagesToggle( { id }: { id: number } ) { } ); }; + if ( ! hasSetting ) { + return null; + } + return ( - +
+ +
); } diff --git a/routes/navigation-edit/stage.tsx b/routes/navigation-edit/stage.tsx index d0ab056e3e4893..3b462a3c36e567 100644 --- a/routes/navigation-edit/stage.tsx +++ b/routes/navigation-edit/stage.tsx @@ -68,9 +68,10 @@ function NavigationEditStage() {
-
- -
+
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 index c6498694511483..da0b1c435fb769 100644 --- a/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.ts +++ b/test/e2e/specs/editor/blocks/navigation-auto-add-pages.spec.ts @@ -391,7 +391,7 @@ test.describe( 'Navigation block: Auto add new pages', () => { name: 'Auto add new pages', } ); await expect( toggle ).toHaveAccessibleDescription( - 'Pages published from now on are added to this menu. Existing pages are not.' + 'Adds pages to this navigation when they are published.' ); await expect( toggle ).toBeChecked(); await toggle.click(); 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 index a220bea34d9743..5def17f32e24fb 100644 --- a/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.ts +++ b/test/e2e/specs/site-editor/navigation-auto-add-pages.spec.ts @@ -82,7 +82,7 @@ test.describe( 'Navigation sidebar: Auto add new pages', () => { .poll( () => distanceFromBottom( page, toggle ) ) .toBeLessThan( 200 ); await expect( toggle ).toHaveAccessibleDescription( - 'Pages published from now on are added to this menu. Existing pages are not.' + 'Adds pages to this navigation when they are published.' ); await expect( toggle ).not.toBeChecked(); await toggle.click(); @@ -105,6 +105,56 @@ test.describe( 'Navigation sidebar: Auto add new pages', () => { .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, @@ -201,7 +251,7 @@ test.describe( 'Navigation menu screen: Auto add new pages', () => { .poll( () => distanceFromBottom( page, toggle ) ) .toBeLessThan( 200 ); await expect( toggle ).toHaveAccessibleDescription( - 'Pages published from now on are added to this menu. Existing pages are not.' + 'Adds pages to this navigation when they are published.' ); await expect( toggle ).not.toBeChecked(); await toggle.click(); From c6d5d670852016ca6b682bd9ddfcecbf7bca1ce6 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Wed, 2 Dec 2026 16:35:57 -0600 Subject: [PATCH 30/30] Navigation: Address review round 4 on auto add new pages - Leave the site editor's menu screen without its footer when the menu has no "Auto add new pages" setting, instead of an empty bordered bar, as the extensible site editor already does. - Read the transient blocks through `select?.` like the saved content, in the resolver. Co-Authored-By: Claude Opus 5.5 --- packages/core-data/src/resolvers.ts | 2 +- .../single-navigation-menu.jsx | 10 ++- .../test/single-navigation-menu.jsdom.test.ts | 88 +++++++++++++++++++ 3 files changed, 98 insertions(+), 2 deletions(-) create mode 100644 packages/edit-site/src/components/sidebar-navigation-screen-navigation-menu/test/single-navigation-menu.jsdom.test.ts diff --git a/packages/core-data/src/resolvers.ts b/packages/core-data/src/resolvers.ts index 421922641f2f61..e0a5194989eaa4 100644 --- a/packages/core-data/src/resolvers.ts +++ b/packages/core-data/src/resolvers.ts @@ -291,7 +291,7 @@ export const getEntityRecord = record.content as { raw?: unknown } | undefined )?.raw; const getTransientBlocks = () => - select.getEntityRecordEdits( kind, name, key )?.blocks as + select?.getEntityRecordEdits( kind, name, key )?.blocks as Block[] | undefined; const shouldDropTransientEdits = ! query && 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 d4edc42ceee12b..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 @@ -9,6 +9,8 @@ import buildNavigationLabel from '../sidebar-navigation-screen-navigation-menus/ const { AutoAddPagesControl } = unlock( blockLibraryPrivateApis ); +const AUTO_ADD_PAGES_META_KEY = 'wp_navigation_auto_add_pages'; + export default function SingleNavigationMenu( { navigationMenu, backPath, @@ -17,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 ( ( { + 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(); + } ); +} );