From 47a85d15fa5724276ffe713aa4e7a32ce4b98d4b Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Mon, 31 Aug 2026 12:22:46 +0200 Subject: [PATCH 1/3] Remove the template activation experiment Removes the `active_templates` experiment and all code gated on `window.__experimentalTemplateActivate`, keeping the experiment-off behavior everywhere: - Delete lib/compat/wordpress-7.0/template-activate.php and the old/static templates REST controllers; unwrap the experiment conditionals in rest-api.php, editor-settings.php and load.php; drop the experiment registration and the separateOption machinery. - core-data: remove the registeredTemplate entity, the wp_template baseURL rewrites and combinedTemplates query param, the wp_id fallback in getDefaultTemplateId and its site-save invalidation. - editor: remove the post-save activation notice, the "Edit template" auto-activation, and template duplication from the actions list. - fields: restore the unconditional rename/reset/duplicate logic. - edit-site and routes/template-list: delete the activation Templates pages and promote the legacy implementations in their place. - Delete the experiment-only e2e specs and phpunit test, prune them from timings.json, and simplify setGutenbergExperiments. Co-Authored-By: Claude Fable 5 --- ...utenberg-rest-old-templates-controller.php | 23 - ...nberg-rest-static-templates-controller.php | 108 --- lib/compat/wordpress-7.0/rest-api.php | 23 +- .../wordpress-7.0/template-activate.php | 842 ------------------ lib/experimental/editor-settings.php | 3 - lib/experimental/experiments/load.php | 20 - lib/load.php | 8 - packages/core-data/CHANGELOG.md | 1 + packages/core-data/src/actions.js | 29 +- packages/core-data/src/entities.js | 21 +- packages/core-data/src/resolvers.js | 52 +- .../e2e-test-utils-playwright/CHANGELOG.md | 4 + .../request-utils/gutenberg-experiments.ts | 37 +- packages/edit-site/CHANGELOG.md | 1 + ...-custom-generic-template-modal-content.jsx | 85 -- .../add-custom-template-modal-content.jsx | 306 ------- .../add-new-template-legacy/index.jsx | 440 --------- .../add-new-template-legacy/utils.js | 757 ---------------- .../add-custom-template-modal-content.jsx | 4 +- .../src/components/add-new-template/index.jsx | 13 +- .../src/components/add-new-template/utils.js | 127 ++- .../src/components/dataviews-actions/index.js | 61 -- .../src/components/page-templates/fields.jsx | 148 +-- .../src/components/page-templates/hooks.js | 93 -- .../page-templates/index-legacy.jsx | 143 --- .../src/components/page-templates/index.jsx | 286 +----- .../components/page-templates/view-utils.js | 50 -- .../content-legacy.jsx | 52 -- .../content.jsx | 125 +-- .../index.jsx | 9 +- .../style.scss | 6 - .../site-editor-routes/templates.jsx | 21 +- packages/edit-site/src/style.scss | 1 - packages/editor/CHANGELOG.md | 1 + .../components/post-template/block-theme.jsx | 45 +- .../editor/src/components/provider/index.jsx | 12 +- .../src/dataviews/store/private-actions.ts | 20 +- packages/editor/src/store/actions.js | 98 +- packages/fields/CHANGELOG.md | 1 + .../fields/src/actions/duplicate-post.tsx | 13 +- packages/fields/src/actions/rename-post.tsx | 19 +- packages/fields/src/actions/reset-post.tsx | 15 - ...rns-in-templates-active-templates-test.php | 504 ----------- routes/experiments-home/api.ts | 2 - routes/experiments-home/stage.tsx | 24 +- .../actions/set-active-template.tsx | 90 -- .../template-list/add-new-template/index.tsx | 8 +- routes/template-list/fields/active.tsx | 24 - routes/template-list/fields/description.tsx | 30 +- routes/template-list/fields/slug.tsx | 34 - routes/template-list/stage-activation.tsx | 371 -------- routes/template-list/stage-legacy.tsx | 325 ------- routes/template-list/stage.tsx | 316 ++++++- routes/template-list/types.ts | 4 +- routes/template-list/use-templates-legacy.ts | 54 -- routes/template-list/use-templates.ts | 136 +-- routes/template-list/view-utils.ts | 52 +- routes/template/route.ts | 11 +- ...save-entity-record-template-compat.spec.js | 148 --- .../site-editor/template-activate.spec.js | 173 ---- .../site-editor/template-id-format.spec.js | 143 --- .../template-registration-activation.spec.js | 405 --------- test/e2e/timings.json | 168 ---- tools/eslint/suppressions.json | 47 +- 64 files changed, 593 insertions(+), 6599 deletions(-) delete mode 100644 lib/compat/wordpress-7.0/class-gutenberg-rest-old-templates-controller.php delete mode 100644 lib/compat/wordpress-7.0/class-gutenberg-rest-static-templates-controller.php delete mode 100644 lib/compat/wordpress-7.0/template-activate.php delete mode 100644 packages/edit-site/src/components/add-new-template-legacy/add-custom-generic-template-modal-content.jsx delete mode 100644 packages/edit-site/src/components/add-new-template-legacy/add-custom-template-modal-content.jsx delete mode 100644 packages/edit-site/src/components/add-new-template-legacy/index.jsx delete mode 100644 packages/edit-site/src/components/add-new-template-legacy/utils.js delete mode 100644 packages/edit-site/src/components/page-templates/hooks.js delete mode 100644 packages/edit-site/src/components/page-templates/index-legacy.jsx delete mode 100644 packages/edit-site/src/components/page-templates/view-utils.js delete mode 100644 packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/content-legacy.jsx delete mode 100644 packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/style.scss delete mode 100644 phpunit/class-resolve-patterns-in-templates-active-templates-test.php delete mode 100644 routes/template-list/actions/set-active-template.tsx delete mode 100644 routes/template-list/fields/active.tsx delete mode 100644 routes/template-list/fields/slug.tsx delete mode 100644 routes/template-list/stage-activation.tsx delete mode 100644 routes/template-list/stage-legacy.tsx delete mode 100644 routes/template-list/use-templates-legacy.ts delete mode 100644 test/e2e/specs/site-editor/save-entity-record-template-compat.spec.js delete mode 100644 test/e2e/specs/site-editor/template-activate.spec.js delete mode 100644 test/e2e/specs/site-editor/template-id-format.spec.js delete mode 100644 test/e2e/specs/site-editor/template-registration-activation.spec.js diff --git a/lib/compat/wordpress-7.0/class-gutenberg-rest-old-templates-controller.php b/lib/compat/wordpress-7.0/class-gutenberg-rest-old-templates-controller.php deleted file mode 100644 index 51c1f40b0acd05..00000000000000 --- a/lib/compat/wordpress-7.0/class-gutenberg-rest-old-templates-controller.php +++ /dev/null @@ -1,23 +0,0 @@ -content ) ); - - // To maintain original behavior, return an empty object rather than a 404 error when no template is found. - $response = $fallback_template ? $this->prepare_item_for_response( $fallback_template, $request ) : new stdClass(); - - return rest_ensure_response( $response ); - } -} diff --git a/lib/compat/wordpress-7.0/class-gutenberg-rest-static-templates-controller.php b/lib/compat/wordpress-7.0/class-gutenberg-rest-static-templates-controller.php deleted file mode 100644 index addcd591a7833d..00000000000000 --- a/lib/compat/wordpress-7.0/class-gutenberg-rest-static-templates-controller.php +++ /dev/null @@ -1,108 +0,0 @@ -rest_base = 'registered-templates'; - $this->namespace = 'wp/v2'; - } - - public function register_routes() { - // Lists all templates. - register_rest_route( - $this->namespace, - '/' . $this->rest_base, - array( - array( - 'methods' => WP_REST_Server::READABLE, - 'callback' => array( $this, 'get_items' ), - 'permission_callback' => array( $this, 'get_items_permissions_check' ), - 'args' => $this->get_collection_params(), - ), - 'schema' => array( $this, 'get_public_item_schema' ), - ) - ); - - // Lists/updates a single template based on the given id. - register_rest_route( - $this->namespace, - // The route. - sprintf( - '/%s/(?P%s%s)', - $this->rest_base, - /* - * Matches theme's directory: `/themes///` or `/themes//`. - * Excludes invalid directory name characters: `/:<>*?"|`. - */ - '([^\/:<>\*\?"\|]+(?:\/[^\/:<>\*\?"\|]+)?)', - // Matches the template name. - '[\/\w%-]+' - ), - array( - 'args' => array( - 'id' => array( - 'description' => __( 'The id of a template' ), - 'type' => 'string', - 'sanitize_callback' => array( $this, '_sanitize_template_id' ), - ), - ), - array( - 'methods' => WP_REST_Server::READABLE, - 'callback' => array( $this, 'get_item' ), - 'permission_callback' => array( $this, 'get_item_permissions_check' ), - 'args' => array( - 'context' => $this->get_context_param( array( 'default' => 'view' ) ), - ), - ), - 'schema' => array( $this, 'get_public_item_schema' ), - ) - ); - } - - public function get_item_schema() { - $schema = parent::get_item_schema(); - $schema['properties']['is_custom'] = array( - 'description' => __( 'Whether a template is a custom template.' ), - 'type' => 'bool', - 'context' => array( 'embed', 'view', 'edit' ), - 'readonly' => true, - ); - $schema['properties']['plugin'] = array( - 'type' => 'string', - 'description' => __( 'Plugin that registered the template.' ), - 'readonly' => true, - 'context' => array( 'view', 'edit', 'embed' ), - ); - return $schema; - } - - public function get_items( $request ) { - $query = array(); - if ( isset( $request['area'] ) ) { - $query['area'] = $request['area']; - } - if ( isset( $request['post_type'] ) ) { - $query['post_type'] = $request['post_type']; - } - $query_result = gutenberg_get_registered_block_templates( $query ); - $templates = array(); - foreach ( $query_result as $template ) { - $item = $this->prepare_item_for_response( $template, $request ); - $templates[] = $this->prepare_response_for_collection( $item ); - } - - return rest_ensure_response( $templates ); - } - - public function get_item( $request ) { - $template = get_block_file_template( $request['id'], 'wp_template' ); - - if ( ! $template ) { - return new WP_Error( 'rest_template_not_found', __( 'No templates exist with that id.' ), array( 'status' => 404 ) ); - } - - $item = $this->prepare_item_for_response( $template, $request ); - return rest_ensure_response( $item ); - } -} diff --git a/lib/compat/wordpress-7.0/rest-api.php b/lib/compat/wordpress-7.0/rest-api.php index b4067d91661199..898cd2ab5e3bad 100644 --- a/lib/compat/wordpress-7.0/rest-api.php +++ b/lib/compat/wordpress-7.0/rest-api.php @@ -16,29 +16,20 @@ function gutenberg_register_block_patterns_controller_endpoints() { add_action( 'rest_api_init', 'gutenberg_register_block_patterns_controller_endpoints' ); /** - * Registers the Registered Templates REST API routes. - * The template activation experiment registers its own routes, so we only register the registered templates controller if the experiment is not enabled. - * See: lib/compat/wordpress-7.0/template-activate.php + * Registers the Templates REST API routes. * - * @see Gutenberg_REST_Registered_Templates_Controller * @see Gutenberg_REST_Templates_Controller_7_0 */ -if ( ! gutenberg_is_experiment_enabled( 'active_templates' ) ) { - function gutenberg_modify_wp_template_post_type_args_7_0( $args ) { - $args['rest_controller_class'] = 'Gutenberg_REST_Templates_Controller_7_0'; - $args['late_route_registration'] = true; - return $args; - } - add_filter( 'register_wp_template_post_type_args', 'gutenberg_modify_wp_template_post_type_args_7_0' ); +function gutenberg_modify_wp_template_post_type_args_7_0( $args ) { + $args['rest_controller_class'] = 'Gutenberg_REST_Templates_Controller_7_0'; + $args['late_route_registration'] = true; + return $args; } +add_filter( 'register_wp_template_post_type_args', 'gutenberg_modify_wp_template_post_type_args_7_0' ); /** - * Registers the Registered Templates Parts REST API routes. - * The template activation experiment does not, however, register the routes for the wp_template_part post type, - * so we need to register the routes for that post type here. - * See: lib/compat/wordpress-7.0/template-activate.php + * Registers the Template Parts REST API routes. * - * @see Gutenberg_REST_Registered_Templates_Controller * @see Gutenberg_REST_Templates_Controller_7_0 */ function gutenberg_modify_wp_template_part_post_type_args_7_0( $args ) { diff --git a/lib/compat/wordpress-7.0/template-activate.php b/lib/compat/wordpress-7.0/template-activate.php deleted file mode 100644 index 4af41f880377ec..00000000000000 --- a/lib/compat/wordpress-7.0/template-activate.php +++ /dev/null @@ -1,842 +0,0 @@ - 'publish', - 'post_type' => 'wp_template', - 'posts_per_page' => -1, - 'no_found_rows' => true, - 'lazy_load_term_meta' => false, - 'tax_query' => array( - array( - 'taxonomy' => 'wp_theme', - 'field' => 'name', - 'terms' => get_stylesheet(), - ), - ), - // Only get templates that are not inactive by default. - 'meta_query' => array( - 'relation' => 'OR', - array( - 'key' => 'is_inactive_by_default', - 'compare' => 'NOT EXISTS', - ), - array( - 'key' => 'is_inactive_by_default', - 'value' => false, - 'compare' => '=', - ), - ), - ); - - $template_query = new WP_Query( $wp_query_args ); - $active_templates = array(); - - foreach ( $template_query->posts as $post ) { - $active_templates[ $post->post_name ] = $post->ID; - } - - return $active_templates; -} - -require_once __DIR__ . '/class-gutenberg-rest-old-templates-controller.php'; - -// How does this work? -// 1. For wp_template, we remove the custom templates controller, so it becomes -// a normal posts endpoint, modified slightly to allow auto-drafts. -add_filter( 'register_post_type_args', 'gutenberg_modify_wp_template_post_type_args', 10, 2 ); -function gutenberg_modify_wp_template_post_type_args( $args, $post_type ) { - // Check active_templates experiment status. - if ( ! gutenberg_is_experiment_enabled( 'active_templates' ) ) { - return $args; - } - if ( 'wp_template' === $post_type ) { - $args['rest_base'] = 'created-templates'; - $args['rest_controller_class'] = 'WP_REST_Posts_Controller'; - $args['autosave_rest_controller_class'] = null; - $args['revisions_rest_controller_class'] = null; - $args['supports'] = array_merge( $args['supports'], array( 'custom-fields' ) ); - } - return $args; -} - -// 2. We maintain the routes for /templates and /templates/lookup. I think we'll -// need to deprecate /templates eventually, but we'll still want to be able -// to lookup the active template for a specific slug, and probably get a list -// of all _active_ templates. For that we can keep /lookup. -// Priority 100, after `create_initial_rest_routes`. -add_action( 'rest_api_init', 'gutenberg_maintain_templates_routes', 100 ); - -/** - * @global array $wp_post_types List of post types. - */ -function gutenberg_maintain_templates_routes() { - // Check active_templates experiment status. - if ( ! gutenberg_is_experiment_enabled( 'active_templates' ) ) { - return; - } - // This should later be changed in core so we don't need initialize - // WP_REST_Templates_Controller with a post type. - global $wp_post_types; - // Register the old templates endpoints. The WP_REST_Templates_Controller - // and sub-controllers used to be linked to the wp_template post type, but - // are no longer. They still require a post type object when constructing the - // class. To maintain backward and changes to these controller classes, we - // make use that the wp_template post type has the right information it - // needs. - $wp_post_types['wp_template']->rest_base = 'templates'; - // Store the classes so they can be restored. - $original_rest_controller_class = $wp_post_types['wp_template']->rest_controller_class; - $original_autosave_rest_controller_class = $wp_post_types['wp_template']->autosave_rest_controller_class; - $original_revisions_rest_controller_class = $wp_post_types['wp_template']->revisions_rest_controller_class; - // Temporarily set the old classes. - $wp_post_types['wp_template']->rest_controller_class = 'WP_REST_Templates_Controller'; - $wp_post_types['wp_template']->autosave_rest_controller_class = 'WP_REST_Template_Autosaves_Controller'; - $wp_post_types['wp_template']->revisions_rest_controller_class = 'WP_REST_Template_Revisions_Controller'; - // Initialize the controllers. The order is important: the autosave - // controller needs both the templates and revisions controllers. - $controller = new Gutenberg_REST_Old_Templates_Controller( 'wp_template' ); - $wp_post_types['wp_template']->rest_controller = $controller; - $revisions_controller = new WP_REST_Template_Revisions_Controller( 'wp_template' ); - $wp_post_types['wp_template']->revisions_rest_controller = $revisions_controller; - $autosaves_controller = new WP_REST_Template_Autosaves_Controller( 'wp_template' ); - // Unset the controller cache, it will be re-initialized when - // get_rest_controller is called. - $wp_post_types['wp_template']->rest_controller = null; - $wp_post_types['wp_template']->revisions_rest_controller = null; - // Restore the original classes. - $wp_post_types['wp_template']->rest_controller_class = $original_rest_controller_class; - $wp_post_types['wp_template']->autosave_rest_controller_class = $original_autosave_rest_controller_class; - $wp_post_types['wp_template']->revisions_rest_controller_class = $original_revisions_rest_controller_class; - // Restore the original base. - $wp_post_types['wp_template']->rest_base = 'created-templates'; - - // Register the old routes. - $autosaves_controller->register_routes(); - $revisions_controller->register_routes(); - $controller->register_routes(); - - $registered_template_controller = new Gutenberg_REST_Static_Templates_Controller(); - $registered_template_controller->register_routes(); - - // Add the same field as wp_registered_template. - register_rest_field( - 'wp_template', - 'theme', - array( - 'get_callback' => function ( $post_arr ) { - // add_additional_fields_to_object is also called for the old - // templates controller, so we need to check if the id is an - // integer to make sure it's the proper post type endpoint. - if ( ! is_int( $post_arr['id'] ) ) { - $template = get_block_template( $post_arr['id'], 'wp_template' ); - return $template ? $template->theme : null; - } - $terms = get_the_terms( $post_arr['id'], 'wp_theme' ); - if ( is_wp_error( $terms ) || empty( $terms ) ) { - return null; - } - return $terms[0]->slug; - }, - ) - ); - - // Allow setting the is_wp_suggestion meta field, which partly determines if - // a template is a custom template. - register_post_meta( - 'wp_template', - 'is_wp_suggestion', - array( - 'type' => 'boolean', - 'show_in_rest' => true, - 'single' => true, - ) - ); -} - -// 3. We need a route to get that raw static templates from themes and plugins. -// I registered this as a post type route because right now the -// EditorProvider assumes templates are posts. -add_action( 'init', 'gutenberg_setup_static_template' ); - -function gutenberg_setup_static_template() { - register_setting( - 'reading', - 'active_templates', - array( - 'type' => 'object', - // Do not set the default value to an empty array! For some reason - // that will prevent the option from being set to an empty array. - 'show_in_rest' => array( - 'schema' => array( - 'type' => 'object', - // Properties can be integers, strings, or false - // (deactivated). - 'additionalProperties' => true, - ), - ), - 'label' => 'Active Templates', - ) - ); -} - -add_filter( 'pre_wp_unique_post_slug', 'gutenberg_allow_template_slugs_to_be_duplicated', 10, 5 ); -function gutenberg_allow_template_slugs_to_be_duplicated( $override, $slug, $post_id, $post_status, $post_type ) { - // Check active_templates experiment status. - if ( ! gutenberg_is_experiment_enabled( 'active_templates' ) ) { - return $override; - } - return 'wp_template' === $post_type ? $slug : $override; -} - -function gutenberg_get_registered_block_templates( $query ) { - $template_files = _get_block_templates_files( 'wp_template', $query ); - $query_result = array(); - - // _get_block_templates_files seems broken in core, it does not object the - // query. - if ( isset( $query['slug__in'] ) && is_array( $query['slug__in'] ) ) { - $template_files = array_filter( - $template_files, - function ( $template_file ) use ( $query ) { - return in_array( $template_file['slug'], $query['slug__in'], true ); - } - ); - } - - foreach ( $template_files as $template_file ) { - $query_result[] = _build_block_template_result_from_file( $template_file, 'wp_template' ); - } - - // Add templates registered in the template registry. Filtering out the ones which have a theme file. - $registered_templates = WP_Block_Templates_Registry::get_instance()->get_by_query( $query ); - $matching_registered_templates = array_filter( - $registered_templates, - function ( $registered_template ) use ( $template_files ) { - foreach ( $template_files as $template_file ) { - if ( $template_file['slug'] === $registered_template->slug ) { - return false; - } - } - return true; - } - ); - - $query_result = array_merge( $query_result, $matching_registered_templates ); - - /** - * Filters the array of queried block templates array after they've been fetched. - * - * @since 5.9.0 - * - * @param WP_Block_Template[] $query_result Array of found block templates. - * @param array $query { - * Arguments to retrieve templates. All arguments are optional. - * - * @type string[] $slug__in List of slugs to include. - * @type int $wp_id Post ID of customized template. - * @type string $area A 'wp_template_part_area' taxonomy value to filter by (for 'wp_template_part' template type only). - * @type string $post_type Post type to get the templates for. - * } - * @param string $template_type wp_template or wp_template_part. - */ - return apply_filters( 'get_block_templates', $query_result, $query, 'wp_template' ); -} - -$template_types = array( - 'index', - '404', - 'search', - 'frontpage', - 'home', - 'privacypolicy', - 'taxonomy', - 'attachment', - 'single', - 'page', - 'singular', - 'category', - 'tag', - 'author', - 'date', - 'archive', -); - -// Unfortunately, there is no general filter. -foreach ( $template_types as $template_type ) { - add_filter( "{$template_type}_template", 'gutenberg_get_template', 0, 3 ); -} - -function gutenberg_get_template( $template, $type, $templates ) { - // Check active_templates experiment status. - if ( ! gutenberg_is_experiment_enabled( 'active_templates' ) ) { - return $template; - } - $template = locate_template( $templates ); - return gutenberg_locate_block_template( $template, $type, $templates ); -} - -/////////////////////////////////////////////////////////////////////// -// This function is a copy of core's, except for the marked section. // -/////////////////////////////////////////////////////////////////////// -/** - * Returns the correct 'wp_template' to render for the request template type. - * - * @access private - * @since 5.8.0 - * @since 5.9.0 Added the `$fallback_template` parameter. - * - * @param string $template_type The current template type. - * @param string[] $template_hierarchy The current template hierarchy, ordered by priority. - * @param string $fallback_template A PHP fallback template to use if no matching block template is found. - * @return WP_Block_Template|null template A template object, or null if none could be found. - */ -function gutenberg_resolve_block_template( $template_type, $template_hierarchy, $fallback_template ) { - if ( ! $template_type ) { - return null; - } - - if ( empty( $template_hierarchy ) ) { - $template_hierarchy = array( $template_type ); - } - - $slugs = array_map( - '_strip_template_file_suffix', - $template_hierarchy - ); - - ////////////////////////////// - // START CORE MODIFICATIONS // - ////////////////////////////// - - $object_id = get_queried_object_id(); - $specific_template = $object_id ? get_page_template_slug( $object_id ) : null; - $active_templates = (array) get_option( 'active_templates', array() ); - - // We expect one template for each slug. Use the active template if it is - // set and exists. Otherwise use the static template. - $templates = array(); - $remaining_slugs = array(); - - foreach ( $slugs as $slug ) { - if ( $slug === $specific_template || empty( $active_templates[ $slug ] ) ) { - $remaining_slugs[] = $slug; - continue; - } - - // TODO: it need to be possible to set a static template as active. - $post = get_post( $active_templates[ $slug ] ); - if ( ! $post || 'publish' !== $post->post_status ) { - $remaining_slugs[] = $slug; - continue; - } - - $template = _build_block_template_result_from_post( $post ); - - // Ensure the active templates are associated with the active theme. - // See _build_block_template_object_from_post_object. - if ( get_stylesheet() !== $template->theme ) { - $remaining_slugs[] = $slug; - continue; - } - - $templates[] = $template; - } - - // Apply the filter to the active templates for backward compatibility. - if ( ! empty( $templates ) ) { - $templates = apply_filters( - 'get_block_templates', - $templates, - array( - 'slug__in' => array_map( - function ( $template ) { - return $template->slug; - }, - $templates - ), - ), - 'wp_template' - ); - } - - // For any remaining slugs, use the static template. - if ( ! empty( $remaining_slugs ) ) { - $query = array( - 'slug__in' => $remaining_slugs, - ); - $templates = array_merge( $templates, gutenberg_get_registered_block_templates( $query ) ); - } - - if ( $specific_template && in_array( $specific_template, $remaining_slugs, true ) ) { - $templates = array_merge( $templates, get_block_templates( array( 'slug__in' => array( $specific_template ) ) ) ); - } - - //////////////////////////// - // END CORE MODIFICATIONS // - //////////////////////////// - - // Order these templates per slug priority. - // Build map of template slugs to their priority in the current hierarchy. - $slug_priorities = array_flip( $slugs ); - - usort( - $templates, - static function ( $template_a, $template_b ) use ( $slug_priorities ) { - return $slug_priorities[ $template_a->slug ] - $slug_priorities[ $template_b->slug ]; - } - ); - - $theme_base_path = get_stylesheet_directory() . DIRECTORY_SEPARATOR; - $parent_theme_base_path = get_template_directory() . DIRECTORY_SEPARATOR; - - // Is the active theme a child theme, and is the PHP fallback template part of it? - if ( - str_starts_with( $fallback_template, $theme_base_path ) && - ! str_contains( $fallback_template, $parent_theme_base_path ) - ) { - $fallback_template_slug = substr( - $fallback_template, - // Starting position of slug. - strpos( $fallback_template, $theme_base_path ) + strlen( $theme_base_path ), - // Remove '.php' suffix. - -4 - ); - - // Is our candidate block template's slug identical to our PHP fallback template's? - if ( - count( $templates ) && - $fallback_template_slug === $templates[0]->slug && - 'theme' === $templates[0]->source - ) { - // Unfortunately, we cannot trust $templates[0]->theme, since it will always - // be set to the active theme's slug by _build_block_template_result_from_file(), - // even if the block template is really coming from the active theme's parent. - // (The reason for this is that we want it to be associated with the active theme - // -- not its parent -- once we edit it and store it to the DB as a wp_template CPT.) - // Instead, we use _get_block_template_file() to locate the block template file. - $template_file = _get_block_template_file( 'wp_template', $fallback_template_slug ); - if ( $template_file && get_template() === $template_file['theme'] ) { - // The block template is part of the parent theme, so we - // have to give precedence to the child theme's PHP template. - array_shift( $templates ); - } - } - } - - return count( $templates ) ? $templates[0] : null; -} - -/////////////////////////////////////////////////////////////////////// -// This function is a copy of core's, except for the marked section. // -/////////////////////////////////////////////////////////////////////// -/** - * Finds a block template with equal or higher specificity than a given PHP template file. - * - * Internally, this communicates the block content that needs to be used by the template canvas through a global variable. - * - * @since 5.8.0 - * @since 6.3.0 Added `$_wp_current_template_id` global for editing of current template directly from the admin bar. - * - * @global string $_wp_current_template_content - * @global string $_wp_current_template_id - * - * @param string $template Path to the template. See locate_template(). - * @param string $type Sanitized filename without extension. - * @param string[] $templates A list of template candidates, in descending order of priority. - * @return string The path to the Site Editor template canvas file, or the fallback PHP template. - */ -function gutenberg_locate_block_template( $template, $type, array $templates ) { - global $_wp_current_template_content, $_wp_current_template_id; - - // Check active_templates experiment status. - if ( ! gutenberg_is_experiment_enabled( 'active_templates' ) ) { - return $template; - } - - if ( ! current_theme_supports( 'block-templates' ) ) { - return $template; - } - - if ( $template ) { - /* - * locate_template() has found a PHP template at the path specified by $template. - * That means that we have a fallback candidate if we cannot find a block template - * with higher specificity. - * - * Thus, before looking for matching block themes, we shorten our list of candidate - * templates accordingly. - */ - - // Locate the index of $template (without the theme directory path) in $templates. - $relative_template_path = str_replace( - array( get_stylesheet_directory() . '/', get_template_directory() . '/' ), - '', - $template - ); - $index = array_search( $relative_template_path, $templates, true ); - - // If the template hierarchy algorithm has successfully located a PHP template file, - // we will only consider block templates with higher or equal specificity. - $templates = array_slice( $templates, 0, $index + 1 ); - } - - ////////////////////////////// - // START CORE MODIFICATIONS // - ////////////////////////////// - $block_template = gutenberg_resolve_block_template( $type, $templates, $template ); - //////////////////////////// - // END CORE MODIFICATIONS // - //////////////////////////// - - if ( $block_template ) { - $_wp_current_template_id = $block_template->id; - - if ( empty( $block_template->content ) ) { - if ( is_user_logged_in() ) { - $_wp_current_template_content = wp_render_empty_block_template_warning( $block_template ); - } else { - if ( $block_template->has_theme_file ) { - // Show contents from theme template if user is not logged in. - $theme_template = _get_block_template_file( 'wp_template', $block_template->slug ); - $_wp_current_template_content = file_get_contents( $theme_template['path'] ); - } else { - $_wp_current_template_content = $block_template->content; - } - } - } elseif ( ! empty( $block_template->content ) ) { - $_wp_current_template_content = $block_template->content; - } - if ( isset( $_GET['_wp-find-template'] ) ) { - wp_send_json_success( $block_template ); - } - } else { - if ( $template ) { - return $template; - } - - if ( 'index' === $type ) { - if ( isset( $_GET['_wp-find-template'] ) ) { - wp_send_json_error( array( 'message' => __( 'No matching template found.' ) ) ); - } - } else { - return ''; // So that the template loader keeps looking for templates. - } - } - - // Add hooks for template canvas. - // Add viewport meta tag. - add_action( 'wp_head', '_block_template_viewport_meta_tag', 0 ); - - // Render title tag with content, regardless of whether theme has title-tag support. - remove_action( 'wp_head', '_wp_render_title_tag', 1 ); // Remove conditional title tag rendering... - add_action( 'wp_head', '_block_template_render_title_tag', 1 ); // ...and make it unconditional. - - // This file will be included instead of the theme's template file. - return ABSPATH . WPINC . '/template-canvas.php'; -} - -// We need to set the theme for the template when it's created. See: -// https://github.com/WordPress/wordpress-develop/blob/b2c8d8d2c8754cab5286b06efb4c11e2b6aa92d5/src/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php#L571-L578 -// Priority 9 so it runs before default hooks like -// `inject_ignored_hooked_blocks_metadata_attributes`. -remove_action( 'rest_pre_insert_wp_template', 'wp_assign_new_template_to_theme', 9 ); -add_action( 'rest_pre_insert_wp_template', 'gutenberg_set_active_template_theme', 9, 2 ); -function gutenberg_set_active_template_theme( $changes, $request ) { - // Check active_templates experiment status. - if ( ! gutenberg_is_experiment_enabled( 'active_templates' ) ) { - return $changes; - } - if ( str_starts_with( $request->get_route(), '/wp/v2/templates' ) ) { - return $changes; - } - $changes->tax_input = array( - 'wp_theme' => $request['theme'] ?? get_stylesheet(), - ); - // All new templates saved will receive meta so we can distinguish between - // templates created the old way as edits and templates created the new way. - $changes->meta_input = array( - 'is_inactive_by_default' => true, - ); - return $changes; -} - -add_action( 'save_post_wp_template', 'gutenberg_maybe_update_active_templates' ); -function gutenberg_maybe_update_active_templates( $post_id ) { - // Check active_templates experiment status. - if ( ! gutenberg_is_experiment_enabled( 'active_templates' ) ) { - return; - } - $post = get_post( $post_id ); - $is_inactive_by_default = get_post_meta( $post_id, 'is_inactive_by_default', true ); - if ( $is_inactive_by_default ) { - return; - } - $active_templates = get_option( 'active_templates', array() ); - $active_templates[ $post->post_name ] = $post->ID; - update_option( 'active_templates', $active_templates ); -} - -add_action( 'pre_get_block_template', 'gutenberg_filter_pre_get_block_template', 10, 3 ); - -/////////////////////////////////////////////////////////////////////// -// This function is a copy of core's, except for the marked section. // -/////////////////////////////////////////////////////////////////////// -function gutenberg_filter_pre_get_block_template( $output, $id, $template_type ) { - // Check active_templates experiment status. - if ( ! gutenberg_is_experiment_enabled( 'active_templates' ) ) { - return $output; - } - if ( 'wp_template' !== $template_type ) { - return $output; - } - $parts = explode( '//', $id, 2 ); - if ( count( $parts ) < 2 ) { - return null; - } - list( $theme, $slug ) = $parts; - - ////////////////////////////// - // START CORE MODIFICATIONS // - ////////////////////////////// - $active_templates = get_option( 'active_templates', array() ); - - if ( ! empty( $active_templates[ $slug ] ) ) { - if ( is_int( $active_templates[ $slug ] ) ) { - $post = get_post( $active_templates[ $slug ] ); - if ( $post && 'publish' === $post->post_status ) { - $template = _build_block_template_result_from_post( $post ); - - if ( ! is_wp_error( $template ) && $theme === $template->theme ) { - return $template; - } - } - } - } - //////////////////////////// - // END CORE MODIFICATIONS // - //////////////////////////// - - $wp_query_args = array( - 'post_name__in' => array( $slug ), - 'post_type' => $template_type, - 'post_status' => array( 'auto-draft', 'draft', 'publish', 'trash' ), - 'posts_per_page' => 1, - 'no_found_rows' => true, - 'tax_query' => array( - array( - 'taxonomy' => 'wp_theme', - 'field' => 'name', - 'terms' => $theme, - ), - ), - ); - $template_query = new WP_Query( $wp_query_args ); - $posts = $template_query->posts; - - if ( count( $posts ) > 0 ) { - $template = _build_block_template_result_from_post( $posts[0] ); - - ////////////////////////////// - // START CORE MODIFICATIONS // - ////////////////////////////// - // Custom templates don't need to be activated, so if it's a custom - // template, return it. - if ( ! is_wp_error( $template ) && $template->is_custom ) { - return $template; - } - //////////////////////////// - // END CORE MODIFICATIONS // - //////////////////////////// - } - - $block_template = get_block_file_template( $id, $template_type ); - - /** - * Filters the queried block template object after it's been fetched. - * - * @since 5.9.0 - * - * @param WP_Block_Template|null $block_template The found block template, or null if there isn't one. - * @param string $id Template unique identifier (example: 'theme_slug//template_slug'). - * @param string $template_type Template type. Either 'wp_template' or 'wp_template_part'. - */ - return apply_filters( 'get_block_template', $block_template, $id, $template_type ); -} - -add_action( 'pre_get_block_templates', 'gutenberg_get_block_templates', 10, 3 ); - -/////////////////////////////////////////////////////////////////////// -// This function is a copy of core's, except for the marked section. // -/////////////////////////////////////////////////////////////////////// -function gutenberg_get_block_templates( $output, $query = array(), $template_type = 'wp_template' ) { - // Check active_templates experiment status. - if ( ! gutenberg_is_experiment_enabled( 'active_templates' ) ) { - return $output; - } - if ( 'wp_template' !== $template_type ) { - return $output; - } - - $post_type = $query['post_type'] ?? ''; - $wp_query_args = array( - 'post_status' => array( 'auto-draft', 'draft', 'publish' ), - 'post_type' => $template_type, - 'posts_per_page' => -1, - 'no_found_rows' => true, - 'lazy_load_term_meta' => false, - 'tax_query' => array( - array( - 'taxonomy' => 'wp_theme', - 'field' => 'name', - 'terms' => get_stylesheet(), - ), - ), - ); - - if ( ! empty( $query['slug__in'] ) ) { - $wp_query_args['post_name__in'] = $query['slug__in']; - $wp_query_args['posts_per_page'] = count( array_unique( $query['slug__in'] ) ); - } - - // This is only needed for the regular templates/template parts post type listing and editor. - if ( isset( $query['wp_id'] ) ) { - $wp_query_args['p'] = $query['wp_id']; - } else { - $wp_query_args['post_status'] = 'publish'; - } - - ////////////////////////////// - // START CORE MODIFICATIONS // - ////////////////////////////// - $active_templates = get_option( 'active_templates', array() ); - //////////////////////////// - // END CORE MODIFICATIONS // - //////////////////////////// - - $template_query = new WP_Query( $wp_query_args ); - $query_result = array(); - foreach ( $template_query->posts as $post ) { - $template = _build_block_template_result_from_post( $post ); - - if ( is_wp_error( $template ) ) { - continue; - } - - if ( $post_type && ! $template->is_custom ) { - continue; - } - - if ( - $post_type && - isset( $template->post_types ) && - ! in_array( $post_type, $template->post_types, true ) - ) { - continue; - } - - ////////////////////////////// - // START CORE MODIFICATIONS // - ////////////////////////////// - if ( $template->is_custom || isset( $query['wp_id'] ) ) { - // Custom templates don't need to be activated, leave them be. - // Also don't filter out templates when querying by wp_id. - $query_result[] = $template; - } elseif ( isset( $active_templates[ $template->slug ] ) && $active_templates[ $template->slug ] === $post->ID ) { - // Only include active templates. - $query_result[] = $template; - } - //////////////////////////// - // END CORE MODIFICATIONS // - //////////////////////////// - } - - if ( ! isset( $query['wp_id'] ) ) { - /* - * If the query has found some user templates, those have priority - * over the theme-provided ones, so we skip querying and building them. - */ - $query['slug__not_in'] = wp_list_pluck( $query_result, 'slug' ); - /* - * We need to unset the post_type query param because some templates - * would be excluded otherwise, like `page.html` when looking for - * `page` templates. We need all templates so we can exclude duplicates - * from plugin-registered templates. - * See: https://github.com/WordPress/gutenberg/issues/65584 - */ - $template_files_query = $query; - unset( $template_files_query['post_type'] ); - $template_files = _get_block_templates_files( $template_type, $template_files_query ); - foreach ( $template_files as $template_file ) { - // If the query doesn't specify a post type, or it does and the template matches the post type, add it. - if ( - ! isset( $query['post_type'] ) || - ( - isset( $template_file['postTypes'] ) && - in_array( $query['post_type'], $template_file['postTypes'], true ) - ) - ) { - $query_result[] = _build_block_template_result_from_file( $template_file, $template_type ); - } elseif ( ! isset( $template_file['postTypes'] ) ) { - // The custom templates with no associated post types are available for all post types as long - // as they are not default templates. - $candidate = _build_block_template_result_from_file( $template_file, $template_type ); - $default_template_types = get_default_block_template_types(); - if ( ! isset( $default_template_types[ $candidate->slug ] ) ) { - $query_result[] = $candidate; - } - } - } - - if ( 'wp_template' === $template_type ) { - // Add templates registered in the template registry. Filtering out the ones which have a theme file. - $registered_templates = WP_Block_Templates_Registry::get_instance()->get_by_query( $query ); - $matching_registered_templates = array_filter( - $registered_templates, - function ( $registered_template ) use ( $template_files ) { - foreach ( $template_files as $template_file ) { - if ( $template_file['slug'] === $registered_template->slug ) { - return false; - } - } - return true; - } - ); - - $matching_registered_templates = array_map( - function ( $template ) { - $template->content = apply_block_hooks_to_content( - $template->content, - $template, - 'insert_hooked_blocks_and_set_ignored_hooked_blocks_metadata' - ); - return $template; - }, - $matching_registered_templates - ); - - $query_result = array_merge( $query_result, $matching_registered_templates ); - } - } - - /** - * Filters the array of queried block templates array after they've been fetched. - * - * @since 5.9.0 - * - * @param WP_Block_Template[] $query_result Array of found block templates. - * @param array $query { - * Arguments to retrieve templates. All arguments are optional. - * - * @type string[] $slug__in List of slugs to include. - * @type int $wp_id Post ID of customized template. - * @type string $area A 'wp_template_part_area' taxonomy value to filter by (for 'wp_template_part' template type only). - * @type string $post_type Post type to get the templates for. - * } - * @param string $template_type wp_template or wp_template_part. - */ - return apply_filters( 'get_block_templates', $query_result, $query, $template_type ); -} diff --git a/lib/experimental/editor-settings.php b/lib/experimental/editor-settings.php index d175ca4a00fd34..9cb7dc74e303ff 100644 --- a/lib/experimental/editor-settings.php +++ b/lib/experimental/editor-settings.php @@ -26,9 +26,6 @@ function gutenberg_enable_experiments() { if ( gutenberg_is_experiment_enabled( 'gutenberg-content-only-inspector-fields' ) ) { wp_add_inline_script( 'wp-block-editor', 'window.__experimentalContentOnlyInspectorFields = true', 'before' ); } - if ( gutenberg_is_experiment_enabled( 'active_templates' ) ) { - wp_add_inline_script( 'wp-block-editor', 'window.__experimentalTemplateActivate = true', 'before' ); - } if ( gutenberg_is_experiment_enabled( 'gutenberg-extensible-site-editor' ) ) { wp_add_inline_script( 'wp-block-editor', 'window.__experimentalExtensibleSiteEditor = true', 'before' ); } diff --git a/lib/experimental/experiments/load.php b/lib/experimental/experiments/load.php index e9654fb3d5c84d..8b3d343af567f7 100644 --- a/lib/experimental/experiments/load.php +++ b/lib/experimental/experiments/load.php @@ -95,18 +95,6 @@ function gutenberg_initialize_experiments_settings() { ), ), ), - array( - 'slug' => 'templates', - 'label' => _x( 'Templates', 'experiments group name', 'gutenberg' ), - 'items' => array( - array( - 'id' => 'active_templates', - 'label' => __( 'Template Activation', 'gutenberg' ), - 'description' => __( 'Allows multiple templates of the same type to be created, of which one can be active at a time. (Warning: when you deactivate this experiment, it is best to delete all created templates except for the active ones.)', 'gutenberg' ), - 'separateOption' => true, - ), - ), - ), array( 'slug' => 'other', 'label' => _x( 'Other', 'experiments group name', 'gutenberg' ), @@ -157,14 +145,6 @@ function gutenberg_initialize_experiments_settings() { 'group_label' => $group['label'], ); - // Metadata-only entry: values for separateOption experiments live in - // their own option (e.g. `active_templates`). Surfaced here so the UI - // can render them from the settings schema. - if ( ! empty( $experiment['separateOption'] ) ) { - $property['separate_option'] = true; - $property['option_name'] = $experiment['id']; - } - $properties[ $experiment['id'] ] = $property; } } diff --git a/lib/load.php b/lib/load.php index d1dd3fac34d83c..75cff4a5fba40c 100644 --- a/lib/load.php +++ b/lib/load.php @@ -38,12 +38,6 @@ * @return bool True when the experiment is enabled. */ function gutenberg_is_experiment_enabled( $name ) { - // Special handling for active_templates - check if the active_templates option exists. - // This is not stored in the experiments array but as a separate option. - if ( 'active_templates' === $name ) { - return is_array( get_option( 'active_templates' ) ); - } - $experiments = get_option( 'gutenberg-experiments' ); return ! empty( $experiments[ $name ] ); } @@ -59,10 +53,8 @@ function gutenberg_is_experiment_enabled( $name ) { require __DIR__ . '/compat/wordpress-7.0/class-gutenberg-rest-revisions-controller.php'; require __DIR__ . '/compat/wordpress-7.0/class-gutenberg-rest-block-patterns-controller-7-0.php'; require __DIR__ . '/compat/wordpress-7.0/class-gutenberg-rest-templates-controller-7-0.php'; - require __DIR__ . '/compat/wordpress-7.0/class-gutenberg-rest-static-templates-controller.php'; require __DIR__ . '/compat/wordpress-7.0/class-wp-icons-registry.php'; require __DIR__ . '/compat/wordpress-7.0/class-wp-rest-icons-controller.php'; - require __DIR__ . '/compat/wordpress-7.0/template-activate.php'; require __DIR__ . '/compat/wordpress-7.0/rest-api.php'; require __DIR__ . '/compat/wordpress-7.0/global-styles.php'; diff --git a/packages/core-data/CHANGELOG.md b/packages/core-data/CHANGELOG.md index f94cc57dd33c94..3c3947643c34c3 100644 --- a/packages/core-data/CHANGELOG.md +++ b/packages/core-data/CHANGELOG.md @@ -4,6 +4,7 @@ ### Internal +- Remove the template activation (`active_templates`) experiment: drop the `registeredTemplate` entity and the experiment-only `wp_template` endpoint rewrites and query params. - Remove unused dependency `@wordpress/is-shallow-equal` ([#82103](https://github.com/WordPress/gutenberg/pull/82103)). - Use the `.jsx` extension for JavaScript source files that contain JSX ([#80990](https://github.com/WordPress/gutenberg/pull/80990)). - Remove tsconfig project references to packages that are not dependencies ([#82106](https://github.com/WordPress/gutenberg/pull/82106)). diff --git a/packages/core-data/src/actions.js b/packages/core-data/src/actions.js index 25e428481508c8..d280ffcf22542f 100644 --- a/packages/core-data/src/actions.js +++ b/packages/core-data/src/actions.js @@ -368,19 +368,7 @@ export const deleteEntityRecord = } ); let hasError = false; - let { baseURL } = entityConfig; - if ( - kind === 'postType' && - name === 'wp_template' && - ( ( recordId && - typeof recordId === 'string' && - ! /^\d+$/.test( recordId ) ) || - ! window?.__experimentalTemplateActivate ) - ) { - baseURL = - baseURL.slice( 0, baseURL.lastIndexOf( '/' ) ) + - '/templates'; - } + const { baseURL } = entityConfig; try { let path = `${ baseURL }/${ recordId }`; @@ -701,20 +689,7 @@ export const saveEntityRecord = let updatedRecord; let error; let hasError = false; - let { baseURL } = entityConfig; - // For "string" IDs, use the old templates endpoint. - if ( - kind === 'postType' && - name === 'wp_template' && - ( ( recordId && - typeof recordId === 'string' && - ! /^\d+$/.test( recordId ) ) || - ! window?.__experimentalTemplateActivate ) - ) { - baseURL = - baseURL.slice( 0, baseURL.lastIndexOf( '/' ) ) + - '/templates'; - } + const { baseURL } = entityConfig; try { const path = `${ baseURL }${ recordId ? '/' + recordId : '' }`; // Skip the raw values check when creating a new record; they don't exist yet. diff --git a/packages/core-data/src/entities.js b/packages/core-data/src/entities.js index a53b9ee5440f32..55ca8338e94f1f 100644 --- a/packages/core-data/src/entities.js +++ b/packages/core-data/src/entities.js @@ -212,14 +212,6 @@ export const rootEntitiesConfig = [ key: 'slug', supportsPagination: false, }, - { - label: __( 'Registered Templates' ), - name: 'registeredTemplate', - kind: 'root', - baseURL: '/wp/v2/registered-templates', - key: 'id', - supportsPagination: false, - }, { label: __( 'Font Collections' ), name: 'fontCollection', @@ -396,22 +388,15 @@ async function loadPostTypeEntities() { prePersistPostType( persistedRecord, edits, name, isTemplate ), __unstable_rest_base: postType.rest_base, // The templates controller returns the whole collection and never - // paginates. It serves `wp_template_part` always, and `wp_template` - // until the template activate experiment moves it to a posts - // controller. - supportsPagination: window?.__experimentalTemplateActivate - ? name !== 'wp_template_part' - : ! isTemplate, + // paginates. + supportsPagination: ! isTemplate, getRevisionsUrl: ( parentId, revisionId ) => `/${ namespace }/${ postType.rest_base }/${ parentId }/revisions${ revisionId ? '/' + revisionId : '' }`, - revisionKey: - isTemplate && ! window?.__experimentalTemplateActivate - ? 'wp_id' - : DEFAULT_ENTITY_KEY, + revisionKey: isTemplate ? 'wp_id' : DEFAULT_ENTITY_KEY, }; if ( ! window.__experimentalEnableRealTimeCollaboration ) { diff --git a/packages/core-data/src/resolvers.js b/packages/core-data/src/resolvers.js index e3e1271ae5649a..786d3a56aadfd4 100644 --- a/packages/core-data/src/resolvers.js +++ b/packages/core-data/src/resolvers.js @@ -107,19 +107,7 @@ export const getEntityRecord = } } - let { baseURL } = entityConfig; - - // For "string" IDs, use the old templates endpoint. - if ( - kind === 'postType' && - name === 'wp_template' && - ( ( key && typeof key === 'string' && ! /^\d+$/.test( key ) ) || - ! window?.__experimentalTemplateActivate ) - ) { - baseURL = - baseURL.slice( 0, baseURL.lastIndexOf( '/' ) ) + - '/templates'; - } + const { baseURL } = entityConfig; const path = addQueryArgs( baseURL + ( key ? '/' + key : '' ), { ...entityConfig.baseURLParams, @@ -418,24 +406,7 @@ export const getEntityRecords = }; } - let { baseURL } = entityConfig; - // `combinedTemplates` means that we fetch templates from the "old" - // /templates endpoint, which combines active user templates with - // the registered templates and rewrites IDs in the form of - // `theme-slug/template-slug`. When turned off, we only fetch - // database templates (posts). To fetch registered templates without - // edits applied, use the `registeredTemplate` entity. - const { combinedTemplates = true } = query; - - if ( - kind === 'postType' && - name === 'wp_template' && - combinedTemplates - ) { - baseURL = - baseURL.slice( 0, baseURL.lastIndexOf( '/' ) ) + - '/templates'; - } + const { baseURL } = entityConfig; const path = addQueryArgs( baseURL, { ...entityConfig.baseURLParams, @@ -1008,12 +979,7 @@ export const getDefaultTemplateId = // Wait for the entities config to be loaded, otherwise receiving // the template as an entity will not work. await resolveSelect.getEntitiesConfig( 'postType' ); - // When active_templates experiment is enabled, use numeric wp_id if it - // exists, otherwise fall back to string ID format (theme//slug) as the - // frontend expects string IDs for templates. - const id = window?.__experimentalTemplateActivate - ? template?.wp_id || template?.id - : template?.id; + const id = template?.id; registry.batch( () => { dispatch.receiveDefaultTemplateId( query, id || '' ); @@ -1035,18 +1001,6 @@ export const getDefaultTemplateId = } ); }; -getDefaultTemplateId.shouldInvalidate = ( action ) => { - // Only invalidate on real saves; `persistedEdits` is absent on - // initial fetches so the kickoff's own site read doesn't wipe - // the just-resolved template id. - return ( - action.type === 'RECEIVE_ITEMS' && - action.kind === 'root' && - action.name === 'site' && - !! action.persistedEdits - ); -}; - /** * Requests an entity's revisions from the REST API. * diff --git a/packages/e2e-test-utils-playwright/CHANGELOG.md b/packages/e2e-test-utils-playwright/CHANGELOG.md index 67fed594946935..c5a70302963213 100644 --- a/packages/e2e-test-utils-playwright/CHANGELOG.md +++ b/packages/e2e-test-utils-playwright/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Internal + +- `setGutenbergExperiments`: Remove the special handling for the removed `active_templates` experiment. + ## 1.54.0 (2026-08-26) ## 1.53.0 (2026-08-12) diff --git a/packages/e2e-test-utils-playwright/src/request-utils/gutenberg-experiments.ts b/packages/e2e-test-utils-playwright/src/request-utils/gutenberg-experiments.ts index cf69618baadcca..841e5b06f3ea92 100644 --- a/packages/e2e-test-utils-playwright/src/request-utils/gutenberg-experiments.ts +++ b/packages/e2e-test-utils-playwright/src/request-utils/gutenberg-experiments.ts @@ -5,54 +5,25 @@ import type { RequestUtils } from './index'; * * @param this * @param experiments Array of experimental flags to enable. Pass in an empty array to disable all experiments. - * Use 'active_templates' for the template activation feature. */ async function setGutenbergExperiments( this: RequestUtils, experiments: string[] ) { - // Separate regular experiments from active_templates. - // active_templates is stored as a separate option, not in the experiments array. - const regularExperiments = experiments.filter( - ( exp ) => exp !== 'active_templates' - ); - const hasActiveTemplates = experiments.includes( 'active_templates' ); - // Build the experiments object with boolean values. // When empty array is passed, we send an empty object to disable all experiments. const experimentsData: Record< string, boolean > = {}; - for ( const experiment of regularExperiments ) { + for ( const experiment of experiments ) { experimentsData[ experiment ] = true; } - const settingsData: Record< string, unknown > = { - 'gutenberg-experiments': experimentsData, - }; - - // active_templates lives in a separate top-level option. Sending `{}` - // enables the experiment; sending `null` deletes the option and disables - // it. - if ( hasActiveTemplates ) { - settingsData.active_templates = {}; - } else { - // WP_REST_Settings_Controller rejects null updates when the stored - // value does not match the `type: 'object'` schema (including when the - // option is absent and `get_option` falls back to `false`), so we only - // send null when the option actually exists. - const currentSiteSettings = - ( await this.getSiteSettings() ) as unknown as { - active_templates?: unknown; - }; - if ( currentSiteSettings.active_templates !== null ) { - settingsData.active_templates = null; - } - } - await this.rest( { path: '/wp/v2/settings', method: 'POST', - data: settingsData, + data: { + 'gutenberg-experiments': experimentsData, + }, } ); } diff --git a/packages/edit-site/CHANGELOG.md b/packages/edit-site/CHANGELOG.md index 3d99817449441b..e6c3acba8bc427 100644 --- a/packages/edit-site/CHANGELOG.md +++ b/packages/edit-site/CHANGELOG.md @@ -13,6 +13,7 @@ ### Internal +- Remove the template activation (`active_templates`) experiment: the Templates page and its sidebar always use the previous (non-activation) implementations. - Remove the `showListViewByDefault` handling from `useAdaptEditorToCanvas`; the `editor` package now applies the preference on the preview ↔ edit transition itself. - Remove unused dependencies `@wordpress/blob`, `@wordpress/date`, `@wordpress/escape-html`, etc. ([#82103](https://github.com/WordPress/gutenberg/pull/82103)). - Use the `.jsx` extension for JavaScript source files that contain JSX ([#80990](https://github.com/WordPress/gutenberg/pull/80990)). diff --git a/packages/edit-site/src/components/add-new-template-legacy/add-custom-generic-template-modal-content.jsx b/packages/edit-site/src/components/add-new-template-legacy/add-custom-generic-template-modal-content.jsx deleted file mode 100644 index b1d6669438360c..00000000000000 --- a/packages/edit-site/src/components/add-new-template-legacy/add-custom-generic-template-modal-content.jsx +++ /dev/null @@ -1,85 +0,0 @@ -import { paramCase as kebabCase } from 'change-case'; -import { useState, useEffect, useRef } from '@wordpress/element'; -import { __ } from '@wordpress/i18n'; -import { - Button, - TextControl, - __experimentalHStack as HStack, - __experimentalVStack as VStack, -} from '@wordpress/components'; - -function AddCustomGenericTemplateModalContent( { createTemplate, onBack } ) { - const [ title, setTitle ] = useState( '' ); - const defaultTitle = __( 'Custom Template' ); - const [ isBusy, setIsBusy ] = useState( false ); - const inputRef = useRef(); - - // Set focus to the name input when the component mounts - useEffect( () => { - if ( inputRef.current ) { - inputRef.current.focus(); - } - }, [] ); - - async function onCreateTemplate( event ) { - event.preventDefault(); - if ( isBusy ) { - return; - } - setIsBusy( true ); - try { - await createTemplate( - { - slug: - kebabCase( title || defaultTitle ) || - 'wp-custom-template', - title: title || defaultTitle, - }, - false - ); - } finally { - setIsBusy( false ); - } - } - return ( -
- - - - - - - -
- ); -} - -export default AddCustomGenericTemplateModalContent; diff --git a/packages/edit-site/src/components/add-new-template-legacy/add-custom-template-modal-content.jsx b/packages/edit-site/src/components/add-new-template-legacy/add-custom-template-modal-content.jsx deleted file mode 100644 index 3680fd0d8be9f9..00000000000000 --- a/packages/edit-site/src/components/add-new-template-legacy/add-custom-template-modal-content.jsx +++ /dev/null @@ -1,306 +0,0 @@ -import { useState, useMemo, useEffect } from '@wordpress/element'; -import { __ } from '@wordpress/i18n'; -import { - Button, - Flex, - FlexItem, - SearchControl, - TextHighlight, - Composite, - __experimentalText as WCText, - __experimentalVStack as VStack, -} from '@wordpress/components'; -import { useEntityRecords } from '@wordpress/core-data'; -import { decodeEntities } from '@wordpress/html-entities'; -import { useDebouncedInput } from '@wordpress/compose'; -import { focus } from '@wordpress/dom'; -import { safeDecodeURI } from '@wordpress/url'; -import { mapToIHasNameAndId } from './utils'; - -const EMPTY_ARRAY = []; - -function SuggestionListItem( { - suggestion, - search, - onSelect, - entityForSuggestions, -} ) { - const baseCssClass = - 'edit-site-custom-template-modal__suggestions_list__list-item'; - return ( - - onSelect( - entityForSuggestions.config.getSpecificTemplate( - suggestion - ) - ) - } - /> - } - > - - - - { suggestion.link && ( - - { safeDecodeURI( suggestion.link ) } - - ) } - - ); -} - -function useSearchSuggestions( entityForSuggestions, search ) { - const { config } = entityForSuggestions; - const query = useMemo( - () => ( { - order: 'asc', - context: 'view', - search, - per_page: search ? 20 : 10, - ...config.queryArgs( search ), - } ), - [ search, config ] - ); - const { records: searchResults, hasResolved: searchHasResolved } = - useEntityRecords( - entityForSuggestions.type, - entityForSuggestions.slug, - query - ); - const [ suggestions, setSuggestions ] = useState( EMPTY_ARRAY ); - useEffect( () => { - if ( ! searchHasResolved ) { - return; - } - let newSuggestions = EMPTY_ARRAY; - if ( searchResults?.length ) { - newSuggestions = searchResults; - if ( config.recordNamePath ) { - newSuggestions = mapToIHasNameAndId( - newSuggestions, - config.recordNamePath - ); - } - } - // Update suggestions only when the query has resolved, so as to keep - // the previous results in the UI. - setSuggestions( newSuggestions ); - }, [ searchResults, searchHasResolved ] ); - return suggestions; -} - -function SuggestionList( { entityForSuggestions, onSelect } ) { - const [ search, setSearch, debouncedSearch ] = useDebouncedInput(); - const suggestions = useSearchSuggestions( - entityForSuggestions, - debouncedSearch - ); - const { labels } = entityForSuggestions; - const [ showSearchControl, setShowSearchControl ] = useState( false ); - if ( ! showSearchControl && suggestions?.length > 9 ) { - setShowSearchControl( true ); - } - return ( - <> - { showSearchControl && ( - - ) } - { !! suggestions?.length && ( - - { suggestions.map( ( suggestion ) => ( - - ) ) } - - ) } - { debouncedSearch && ! suggestions?.length && ( - - { labels.not_found } - - ) } - - ); -} - -function AddCustomTemplateModalContent( { - onSelect, - entityForSuggestions, - onBack, - containerRef, -} ) { - const [ showSearchEntities, setShowSearchEntities ] = useState( - entityForSuggestions.hasGeneralTemplate - ); - - // Focus on the first focusable element when the modal opens. - // We handle focus management in the parent modal, just need to focus on the first focusable element. - useEffect( () => { - if ( containerRef.current ) { - const [ firstFocusable ] = focus.focusable.find( - containerRef.current - ); - firstFocusable?.focus(); - } - }, [ showSearchEntities ] ); - - return ( - - { ! showSearchEntities && ( - <> - - { __( - 'Select whether to create a single template for all items or a specific one.' - ) } - - - { - const { - slug, - title, - description, - templatePrefix, - } = entityForSuggestions.template; - onSelect( { - slug, - title, - description, - templatePrefix, - } ); - } } - > - - { entityForSuggestions.labels.all_items } - - - { - // translators: The user is given the choice to set up a template for all items of a post type or taxonomy, or just a specific one. - __( 'For all items' ) - } - - - { - setShowSearchEntities( true ); - } } - > - - { entityForSuggestions.labels.singular_name } - - - { - // translators: The user is given the choice to set up a template for all items of a post type or taxonomy, or just a specific one. - __( 'For a specific item' ) - } - - - - - - - - ) } - { showSearchEntities && ( - <> - - { __( - 'This template will be used only for the specific item chosen.' - ) } - - - - - - - ) } - - ); -} - -export default AddCustomTemplateModalContent; diff --git a/packages/edit-site/src/components/add-new-template-legacy/index.jsx b/packages/edit-site/src/components/add-new-template-legacy/index.jsx deleted file mode 100644 index 50ab8b14671a45..00000000000000 --- a/packages/edit-site/src/components/add-new-template-legacy/index.jsx +++ /dev/null @@ -1,440 +0,0 @@ -import clsx from 'clsx'; -import { - Button, - Modal, - __experimentalGrid as Grid, - __experimentalText as WCText, - __experimentalVStack as VStack, - Flex, - Icon as WCIcon, -} from '@wordpress/components'; -import { decodeEntities } from '@wordpress/html-entities'; -import { useState, memo, useRef, useEffect } from '@wordpress/element'; -import { useSelect, useDispatch } from '@wordpress/data'; -import { store as coreStore } from '@wordpress/core-data'; -import { useViewportMatch } from '@wordpress/compose'; -import { - archive, - blockMeta, - calendar, - category, - commentAuthorAvatar, - pencil, - home, - layout, - list, - media, - notFound, - page, - pin, - verse, - search, - tag, -} from '@wordpress/icons'; -import { __, sprintf } from '@wordpress/i18n'; -import { store as noticesStore } from '@wordpress/notices'; -import { privateApis as routerPrivateApis } from '@wordpress/router'; -import { focus } from '@wordpress/dom'; -import { TEMPLATE_POST_TYPE } from '../../utils/constants'; -import AddCustomTemplateModalContent from './add-custom-template-modal-content'; -import { - useExistingTemplates, - useDefaultTemplateTypes, - useTaxonomiesMenuItems, - usePostTypeMenuItems, - useAuthorMenuItem, - usePostTypeArchiveMenuItems, -} from './utils'; -import AddCustomGenericTemplateModalContent from './add-custom-generic-template-modal-content'; -import { unlock } from '../../lock-unlock'; - -const { useHistory } = unlock( routerPrivateApis ); - -const DEFAULT_TEMPLATE_SLUGS = [ - 'front-page', - 'home', - 'single', - 'page', - 'index', - 'archive', - 'author', - 'category', - 'date', - 'tag', - 'search', - '404', -]; - -const TEMPLATE_ICONS = { - 'front-page': home, - home: verse, - single: pin, - page, - archive, - search, - 404: notFound, - index: list, - category, - author: commentAuthorAvatar, - taxonomy: blockMeta, - date: calendar, - tag, - attachment: media, -}; - -function TemplateListItem( { - title, - direction, - className, - description, - icon, - onClick, - children, -} ) { - return ( - - ); -} - -const modalContentMap = { - templatesList: 1, - customTemplate: 2, - customGenericTemplate: 3, -}; - -function NewTemplateModal( { onClose } ) { - const [ modalContent, setModalContent ] = useState( - modalContentMap.templatesList - ); - const [ entityForSuggestions, setEntityForSuggestions ] = useState( {} ); - const [ isSubmitting, setIsSubmitting ] = useState( false ); - const missingTemplates = useMissingTemplates( setEntityForSuggestions, () => - setModalContent( modalContentMap.customTemplate ) - ); - const history = useHistory(); - const { saveEntityRecord } = useDispatch( coreStore ); - const { createErrorNotice, createSuccessNotice } = - useDispatch( noticesStore ); - const containerRef = useRef( null ); - const isMobile = useViewportMatch( 'medium', '<' ); - - const homeUrl = useSelect( ( select ) => { - // Site index. - return select( coreStore ).getEntityRecord( 'root', '__unstableBase' ) - ?.home; - }, [] ); - - const TEMPLATE_SHORT_DESCRIPTIONS = { - 'front-page': homeUrl, - date: sprintf( - // translators: %s: The homepage url. - __( 'E.g. %s' ), - homeUrl + '/' + new Date().getFullYear() - ), - }; - - useEffect( () => { - // Focus the first focusable element when component mounts or UI changes - // We don't want to focus on the other modals because they have their own focus management. - if ( - containerRef.current && - modalContent === modalContentMap.templatesList - ) { - const [ firstFocusable ] = focus.focusable.find( - containerRef.current - ); - firstFocusable?.focus(); - } - }, [ modalContent ] ); - - async function createTemplate( template, isWPSuggestion = true ) { - if ( isSubmitting ) { - return; - } - setIsSubmitting( true ); - try { - const { title, description, slug } = template; - const newTemplate = await saveEntityRecord( - 'postType', - TEMPLATE_POST_TYPE, - { - description, - // Slugs need to be strings, so this is for template `404` - slug: slug.toString(), - status: 'publish', - title, - // This adds a post meta field in template that is part of `is_custom` value calculation. - is_wp_suggestion: isWPSuggestion, - }, - { throwOnError: true } - ); - - // Navigate to the created template editor. - history.navigate( - `/${ TEMPLATE_POST_TYPE }/${ newTemplate.id }?canvas=edit` - ); - - createSuccessNotice( - sprintf( - // translators: %s: Title of the created post or template, e.g: "Hello world". - __( '"%s" successfully created.' ), - decodeEntities( newTemplate.title?.rendered || title ) || - __( '(no title)' ) - ), - { - type: 'snackbar', - } - ); - } catch ( error ) { - const errorMessage = - error.message && error.code !== 'unknown_error' - ? error.message - : __( 'An error occurred while creating the template.' ); - - createErrorNotice( errorMessage, { - type: 'snackbar', - } ); - } finally { - setIsSubmitting( false ); - } - } - const onModalClose = () => { - onClose(); - setModalContent( modalContentMap.templatesList ); - }; - - let modalTitle = __( 'Add template' ); - if ( modalContent === modalContentMap.customTemplate ) { - modalTitle = sprintf( - // translators: %s: Name of the post type e.g: "Post". - __( 'Add template: %s' ), - entityForSuggestions.labels.singular_name - ); - } else if ( modalContent === modalContentMap.customGenericTemplate ) { - modalTitle = __( 'Create custom template' ); - } - - return ( - - { modalContent === modalContentMap.templatesList && ( - - - { __( - 'Select what the new template should apply to:' - ) } - - { missingTemplates.map( ( template ) => { - const { title, slug, onClick } = template; - return ( - - onClick - ? onClick( template ) - : createTemplate( template ) - } - /> - ); - } ) } - - setModalContent( - modalContentMap.customGenericTemplate - ) - } - > - - { __( - 'A custom template can be manually applied to any post or page.' - ) } - - - - ) } - { modalContent === modalContentMap.customTemplate && ( - - setModalContent( modalContentMap.templatesList ) - } - containerRef={ containerRef } - /> - ) } - { modalContent === modalContentMap.customGenericTemplate && ( - - setModalContent( modalContentMap.templatesList ) - } - /> - ) } - - ); -} - -function NewTemplate() { - const [ showModal, setShowModal ] = useState( false ); - - const { postType } = useSelect( ( select ) => { - const { getPostType } = select( coreStore ); - - return { - postType: getPostType( TEMPLATE_POST_TYPE ), - }; - }, [] ); - - if ( ! postType ) { - return null; - } - - return ( - <> - - { showModal && ( - setShowModal( false ) } /> - ) } - - ); -} - -function useMissingTemplates( setEntityForSuggestions, onClick ) { - const existingTemplates = useExistingTemplates(); - const defaultTemplateTypes = useDefaultTemplateTypes(); - const existingTemplateSlugs = ( existingTemplates || [] ).map( - ( { slug } ) => slug - ); - const missingDefaultTemplates = ( defaultTemplateTypes || [] ).filter( - ( template ) => - DEFAULT_TEMPLATE_SLUGS.includes( template.slug ) && - ! existingTemplateSlugs.includes( template.slug ) - ); - const onClickMenuItem = ( _entityForSuggestions ) => { - onClick?.(); - setEntityForSuggestions( _entityForSuggestions ); - }; - // We need to replace existing default template types with - // the create specific template functionality. The original - // info (title, description, etc.) is preserved in the - // used hooks. - const enhancedMissingDefaultTemplateTypes = [ ...missingDefaultTemplates ]; - const { defaultTaxonomiesMenuItems, taxonomiesMenuItems } = - useTaxonomiesMenuItems( onClickMenuItem ); - const { defaultPostTypesMenuItems, postTypesMenuItems } = - usePostTypeMenuItems( onClickMenuItem ); - - const authorMenuItem = useAuthorMenuItem( onClickMenuItem ); - [ - ...defaultTaxonomiesMenuItems, - ...defaultPostTypesMenuItems, - authorMenuItem, - ].forEach( ( menuItem ) => { - if ( ! menuItem ) { - return; - } - const matchIndex = enhancedMissingDefaultTemplateTypes.findIndex( - ( template ) => template.slug === menuItem.slug - ); - // Some default template types might have been filtered above from - // `missingDefaultTemplates` because they only check for the general - // template. So here we either replace or append the item, augmented - // with the check if it has available specific item to create a - // template for. - if ( matchIndex > -1 ) { - enhancedMissingDefaultTemplateTypes[ matchIndex ] = menuItem; - } else { - enhancedMissingDefaultTemplateTypes.push( menuItem ); - } - } ); - // Update the sort order to match the DEFAULT_TEMPLATE_SLUGS order. - enhancedMissingDefaultTemplateTypes?.sort( ( template1, template2 ) => { - return ( - DEFAULT_TEMPLATE_SLUGS.indexOf( template1.slug ) - - DEFAULT_TEMPLATE_SLUGS.indexOf( template2.slug ) - ); - } ); - const missingTemplates = [ - ...enhancedMissingDefaultTemplateTypes, - ...usePostTypeArchiveMenuItems(), - ...postTypesMenuItems, - ...taxonomiesMenuItems, - ]; - return missingTemplates; -} - -export default memo( NewTemplate ); diff --git a/packages/edit-site/src/components/add-new-template-legacy/utils.js b/packages/edit-site/src/components/add-new-template-legacy/utils.js deleted file mode 100644 index ef90c8126a3e96..00000000000000 --- a/packages/edit-site/src/components/add-new-template-legacy/utils.js +++ /dev/null @@ -1,757 +0,0 @@ -import { useSelect } from '@wordpress/data'; -import { store as coreStore } from '@wordpress/core-data'; -import { decodeEntities } from '@wordpress/html-entities'; -import { useMemo, useCallback } from '@wordpress/element'; -import { __, _x, sprintf } from '@wordpress/i18n'; -import { blockMeta, post, archive } from '@wordpress/icons'; -import { safeDecodeURI } from '@wordpress/url'; -import { TEMPLATE_POST_TYPE } from '../../utils/constants'; - -const EMPTY_OBJECT = {}; - -/** - * @typedef IHasNameAndId - * @property {string|number} id The entity's id. - * @property {string} name The entity's name. - */ - -const getValueFromObjectPath = ( object, path ) => { - let value = object; - path.split( '.' ).forEach( ( fieldName ) => { - value = value?.[ fieldName ]; - } ); - return value; -}; - -/** - * Helper that adds a prefix to a post slug. The slug needs to be URL-decoded first, - * so that we have raw Unicode characters there. The server will truncate the slug to - * 200 characters, respecing Unicode char boundary. On the other hand, the server - * doesn't detect urlencoded octet boundary and can possibly construct slugs that - * are not valid urlencoded strings. - * @param {string} prefix The prefix to add to the slug. - * @param {string} slug The slug to add the prefix to. - * @return {string} The slug with the prefix. - */ -function prefixSlug( prefix, slug ) { - return `${ prefix }-${ safeDecodeURI( slug ) }`; -} - -/** - * Helper util to map records to add a `name` prop from a - * provided path, in order to handle all entities in the same - * fashion(implementing`IHasNameAndId` interface). - * - * @param {Object[]} entities The array of entities. - * @param {string} path The path to map a `name` property from the entity. - * @return {IHasNameAndId[]} An array of entities that now implement the `IHasNameAndId` interface. - */ -export const mapToIHasNameAndId = ( entities, path ) => { - return ( entities || [] ).map( ( entity ) => ( { - ...entity, - name: decodeEntities( getValueFromObjectPath( entity, path ) ), - } ) ); -}; - -/** - * @typedef {Object} EntitiesInfo - * @property {boolean} hasEntities If an entity has available records(posts, terms, etc..). - * @property {number[]} existingEntitiesIds An array of the existing entities ids. - */ - -export const useExistingTemplates = () => { - return useSelect( - ( select ) => - select( coreStore ).getEntityRecords( - 'postType', - TEMPLATE_POST_TYPE, - { - per_page: -1, - } - ), - [] - ); -}; - -export const useDefaultTemplateTypes = () => { - return useSelect( - ( select ) => - select( coreStore ).getCurrentTheme()?.default_template_types || [], - [] - ); -}; - -const usePublicPostTypes = () => { - const postTypes = useSelect( - ( select ) => select( coreStore ).getPostTypes( { per_page: -1 } ), - [] - ); - return useMemo( () => { - const excludedPostTypes = [ 'attachment' ]; - return postTypes - ?.filter( - ( { viewable, slug } ) => - viewable && ! excludedPostTypes.includes( slug ) - ) - .sort( ( a, b ) => { - // Sort post types alphabetically by name, - // but exclude the built-in 'post' type from sorting. - if ( a.slug === 'post' || b.slug === 'post' ) { - return 0; - } - - return a.name.localeCompare( b.name ); - } ); - }, [ postTypes ] ); -}; - -const usePublicTaxonomies = () => { - const taxonomies = useSelect( - ( select ) => select( coreStore ).getTaxonomies( { per_page: -1 } ), - [] - ); - return useMemo( () => { - return taxonomies?.filter( - ( { visibility } ) => visibility?.publicly_queryable - ); - }, [ taxonomies ] ); -}; - -export function usePostTypeArchiveMenuItems() { - const publicPostTypes = usePublicPostTypes(); - const postTypesWithArchives = useMemo( - () => publicPostTypes?.filter( ( postType ) => postType.has_archive ), - [ publicPostTypes ] - ); - const existingTemplates = useExistingTemplates(); - // We need to keep track of naming conflicts. If a conflict - // occurs, we need to add slug. - const postTypeLabels = useMemo( - () => - publicPostTypes?.reduce( ( accumulator, { labels } ) => { - const singularName = labels.singular_name.toLowerCase(); - accumulator[ singularName ] = - ( accumulator[ singularName ] || 0 ) + 1; - return accumulator; - }, {} ), - [ publicPostTypes ] - ); - const needsUniqueIdentifier = useCallback( - ( { labels, slug } ) => { - const singularName = labels.singular_name.toLowerCase(); - return postTypeLabels[ singularName ] > 1 && singularName !== slug; - }, - [ postTypeLabels ] - ); - return useMemo( - () => - postTypesWithArchives - ?.filter( - ( postType ) => - ! ( existingTemplates || [] ).some( - ( existingTemplate ) => - existingTemplate.slug === - 'archive-' + postType.slug - ) - ) - .map( ( postType ) => { - let title; - if ( needsUniqueIdentifier( postType ) ) { - title = sprintf( - // translators: %1s: Name of the post type e.g: "Post"; %2s: Slug of the post type e.g: "book". - __( 'Archive: %1$s (%2$s)' ), - postType.labels.singular_name, - postType.slug - ); - } else { - title = sprintf( - // translators: %s: Name of the post type e.g: "Post". - __( 'Archive: %s' ), - postType.labels.singular_name - ); - } - return { - slug: 'archive-' + postType.slug, - description: sprintf( - // translators: %s: Name of the post type e.g: "Post". - __( - 'Displays an archive with the latest posts of type: %s.' - ), - postType.labels.singular_name - ), - title, - // `icon` is the `menu_icon` property of a post type. We - // only handle `dashicons` for now, even if the `menu_icon` - // also supports urls and svg as values. - icon: - typeof postType.icon === 'string' && - postType.icon.startsWith( 'dashicons-' ) - ? postType.icon.slice( 10 ) - : archive, - templatePrefix: 'archive', - }; - } ) || [], - [ postTypesWithArchives, existingTemplates, needsUniqueIdentifier ] - ); -} - -export const usePostTypeMenuItems = ( onClickMenuItem ) => { - const publicPostTypes = usePublicPostTypes(); - const existingTemplates = useExistingTemplates(); - const defaultTemplateTypes = useDefaultTemplateTypes(); - // We need to keep track of naming conflicts. If a conflict - // occurs, we need to add slug. - const templateLabels = useMemo( - () => - publicPostTypes?.reduce( ( accumulator, { labels } ) => { - const templateName = ( - labels.template_name || labels.singular_name - ).toLowerCase(); - accumulator[ templateName ] = - ( accumulator[ templateName ] || 0 ) + 1; - return accumulator; - }, {} ), - [ publicPostTypes ] - ); - const needsUniqueIdentifier = useCallback( - ( { labels, slug } ) => { - const templateName = ( - labels.template_name || labels.singular_name - ).toLowerCase(); - return templateLabels[ templateName ] > 1 && templateName !== slug; - }, - [ templateLabels ] - ); - - // `page`is a special case in template hierarchy. - const templatePrefixes = useMemo( - () => - publicPostTypes?.reduce( ( accumulator, { slug } ) => { - let suffix = slug; - if ( slug !== 'page' ) { - suffix = `single-${ suffix }`; - } - accumulator[ slug ] = suffix; - return accumulator; - }, {} ), - [ publicPostTypes ] - ); - const postTypesInfo = useEntitiesInfo( 'postType', templatePrefixes ); - const existingTemplateSlugs = ( existingTemplates || [] ).map( - ( { slug } ) => slug - ); - const menuItems = ( publicPostTypes || [] ).reduce( - ( accumulator, postType ) => { - const { slug, labels, icon } = postType; - // We need to check if the general template is part of the - // defaultTemplateTypes. If it is, just use that info and - // augment it with the specific template functionality. - const generalTemplateSlug = templatePrefixes[ slug ]; - const defaultTemplateType = defaultTemplateTypes?.find( - ( { slug: _slug } ) => _slug === generalTemplateSlug - ); - const hasGeneralTemplate = - existingTemplateSlugs?.includes( generalTemplateSlug ); - const _needsUniqueIdentifier = needsUniqueIdentifier( postType ); - let menuItemTitle = - labels.template_name || - sprintf( - // translators: %s: Name of the post type e.g: "Post". - __( 'Single item: %s' ), - labels.singular_name - ); - if ( _needsUniqueIdentifier ) { - menuItemTitle = labels.template_name - ? sprintf( - // translators: 1: Name of the template e.g: "Single Item: Post". 2: Slug of the post type e.g: "book". - _x( '%1$s (%2$s)', 'post type menu label' ), - labels.template_name, - slug - ) - : sprintf( - // translators: 1: Name of the post type e.g: "Post". 2: Slug of the post type e.g: "book". - _x( - 'Single item: %1$s (%2$s)', - 'post type menu label' - ), - labels.singular_name, - slug - ); - } - const menuItem = defaultTemplateType - ? { - ...defaultTemplateType, - templatePrefix: templatePrefixes[ slug ], - } - : { - slug: generalTemplateSlug, - title: menuItemTitle, - description: sprintf( - // translators: %s: Name of the post type e.g: "Post". - __( 'Displays a single item: %s.' ), - labels.singular_name - ), - // `icon` is the `menu_icon` property of a post type. We - // only handle `dashicons` for now, even if the `menu_icon` - // also supports urls and svg as values. - icon: - typeof icon === 'string' && - icon.startsWith( 'dashicons-' ) - ? icon.slice( 10 ) - : post, - templatePrefix: templatePrefixes[ slug ], - }; - const hasEntities = postTypesInfo?.[ slug ]?.hasEntities; - // We have a different template creation flow only if they have entities. - if ( hasEntities ) { - menuItem.onClick = ( template ) => { - onClickMenuItem( { - type: 'postType', - slug, - config: { - recordNamePath: 'title.rendered', - queryArgs: ( { search } ) => { - return { - _fields: 'id,title,slug,link', - orderBy: search ? 'relevance' : 'modified', - exclude: - postTypesInfo[ slug ] - .existingEntitiesIds, - }; - }, - getSpecificTemplate: ( suggestion ) => { - const templateSlug = prefixSlug( - templatePrefixes[ slug ], - suggestion.slug - ); - return { - title: templateSlug, - slug: templateSlug, - templatePrefix: templatePrefixes[ slug ], - }; - }, - }, - labels, - hasGeneralTemplate, - template, - } ); - }; - } - // We don't need to add the menu item if there are no - // entities and the general template exists. - if ( ! hasGeneralTemplate || hasEntities ) { - accumulator.push( menuItem ); - } - return accumulator; - }, - [] - ); - // Split menu items into two groups: one for the default post types - // and one for the rest. - const postTypesMenuItems = useMemo( - () => - menuItems.reduce( - ( accumulator, postType ) => { - const { slug } = postType; - let key = 'postTypesMenuItems'; - if ( slug === 'page' ) { - key = 'defaultPostTypesMenuItems'; - } - accumulator[ key ].push( postType ); - return accumulator; - }, - { defaultPostTypesMenuItems: [], postTypesMenuItems: [] } - ), - [ menuItems ] - ); - return postTypesMenuItems; -}; - -export const useTaxonomiesMenuItems = ( onClickMenuItem ) => { - const publicTaxonomies = usePublicTaxonomies(); - const existingTemplates = useExistingTemplates(); - const defaultTemplateTypes = useDefaultTemplateTypes(); - // `category` and `post_tag` are special cases in template hierarchy. - const templatePrefixes = useMemo( - () => - publicTaxonomies?.reduce( ( accumulator, { slug } ) => { - let suffix = slug; - if ( ! [ 'category', 'post_tag' ].includes( slug ) ) { - suffix = `taxonomy-${ suffix }`; - } - if ( slug === 'post_tag' ) { - suffix = `tag`; - } - accumulator[ slug ] = suffix; - return accumulator; - }, {} ), - [ publicTaxonomies ] - ); - // We need to keep track of naming conflicts. If a conflict - // occurs, we need to add slug. - const taxonomyLabels = publicTaxonomies?.reduce( - ( accumulator, { labels } ) => { - const templateName = ( - labels.template_name || labels.singular_name - ).toLowerCase(); - accumulator[ templateName ] = - ( accumulator[ templateName ] || 0 ) + 1; - return accumulator; - }, - {} - ); - const needsUniqueIdentifier = ( labels, slug ) => { - if ( [ 'category', 'post_tag' ].includes( slug ) ) { - return false; - } - const templateName = ( - labels.template_name || labels.singular_name - ).toLowerCase(); - return taxonomyLabels[ templateName ] > 1 && templateName !== slug; - }; - const taxonomiesInfo = useEntitiesInfo( 'taxonomy', templatePrefixes ); - const existingTemplateSlugs = ( existingTemplates || [] ).map( - ( { slug } ) => slug - ); - const menuItems = ( publicTaxonomies || [] ).reduce( - ( accumulator, taxonomy ) => { - const { slug, labels } = taxonomy; - // We need to check if the general template is part of the - // defaultTemplateTypes. If it is, just use that info and - // augment it with the specific template functionality. - const generalTemplateSlug = templatePrefixes[ slug ]; - const defaultTemplateType = defaultTemplateTypes?.find( - ( { slug: _slug } ) => _slug === generalTemplateSlug - ); - const hasGeneralTemplate = - existingTemplateSlugs?.includes( generalTemplateSlug ); - const _needsUniqueIdentifier = needsUniqueIdentifier( - labels, - slug - ); - let menuItemTitle = labels.template_name || labels.singular_name; - if ( _needsUniqueIdentifier ) { - menuItemTitle = labels.template_name - ? sprintf( - // translators: 1: Name of the template e.g: "Products by Category". 2: Slug of the taxonomy e.g: "product_cat". - _x( '%1$s (%2$s)', 'taxonomy template menu label' ), - labels.template_name, - slug - ) - : sprintf( - // translators: 1: Name of the taxonomy e.g: "Category". 2: Slug of the taxonomy e.g: "product_cat". - _x( '%1$s (%2$s)', 'taxonomy menu label' ), - labels.singular_name, - slug - ); - } - const menuItem = defaultTemplateType - ? { - ...defaultTemplateType, - templatePrefix: templatePrefixes[ slug ], - } - : { - slug: generalTemplateSlug, - title: menuItemTitle, - description: sprintf( - // translators: %s: Name of the taxonomy e.g: "Product Categories". - __( 'Displays taxonomy: %s.' ), - labels.singular_name - ), - icon: blockMeta, - templatePrefix: templatePrefixes[ slug ], - }; - const hasEntities = taxonomiesInfo?.[ slug ]?.hasEntities; - // We have a different template creation flow only if they have entities. - if ( hasEntities ) { - menuItem.onClick = ( template ) => { - onClickMenuItem( { - type: 'taxonomy', - slug, - config: { - queryArgs: ( { search } ) => { - return { - _fields: 'id,name,slug,link', - orderBy: search ? 'name' : 'count', - exclude: - taxonomiesInfo[ slug ] - .existingEntitiesIds, - }; - }, - getSpecificTemplate: ( suggestion ) => { - const templateSlug = prefixSlug( - templatePrefixes[ slug ], - suggestion.slug - ); - return { - title: templateSlug, - slug: templateSlug, - templatePrefix: templatePrefixes[ slug ], - }; - }, - }, - labels, - hasGeneralTemplate, - template, - } ); - }; - } - // We don't need to add the menu item if there are no - // entities and the general template exists. - if ( ! hasGeneralTemplate || hasEntities ) { - accumulator.push( menuItem ); - } - return accumulator; - }, - [] - ); - // Split menu items into two groups: one for the default taxonomies - // and one for the rest. - const taxonomiesMenuItems = useMemo( - () => - menuItems.reduce( - ( accumulator, taxonomy ) => { - const { slug } = taxonomy; - let key = 'taxonomiesMenuItems'; - if ( [ 'category', 'tag' ].includes( slug ) ) { - key = 'defaultTaxonomiesMenuItems'; - } - accumulator[ key ].push( taxonomy ); - return accumulator; - }, - { defaultTaxonomiesMenuItems: [], taxonomiesMenuItems: [] } - ), - [ menuItems ] - ); - return taxonomiesMenuItems; -}; - -const USE_AUTHOR_MENU_ITEM_TEMPLATE_PREFIX = { user: 'author' }; -const USE_AUTHOR_MENU_ITEM_QUERY_PARAMETERS = { user: { who: 'authors' } }; -export function useAuthorMenuItem( onClickMenuItem ) { - const existingTemplates = useExistingTemplates(); - const defaultTemplateTypes = useDefaultTemplateTypes(); - const authorInfo = useEntitiesInfo( - 'root', - USE_AUTHOR_MENU_ITEM_TEMPLATE_PREFIX, - USE_AUTHOR_MENU_ITEM_QUERY_PARAMETERS - ); - let authorMenuItem = defaultTemplateTypes?.find( - ( { slug } ) => slug === 'author' - ); - if ( ! authorMenuItem ) { - authorMenuItem = { - description: __( - 'Displays latest posts written by a single author.' - ), - slug: 'author', - title: 'Author', - }; - } - const hasGeneralTemplate = !! existingTemplates?.find( - ( { slug } ) => slug === 'author' - ); - if ( authorInfo.user?.hasEntities ) { - authorMenuItem = { ...authorMenuItem, templatePrefix: 'author' }; - authorMenuItem.onClick = ( template ) => { - onClickMenuItem( { - type: 'root', - slug: 'user', - config: { - queryArgs: ( { search } ) => { - return { - _fields: 'id,name,slug,link', - orderBy: search ? 'name' : 'registered_date', - exclude: authorInfo.user.existingEntitiesIds, - who: 'authors', - }; - }, - getSpecificTemplate: ( suggestion ) => { - const templateSlug = prefixSlug( - 'author', - suggestion.slug - ); - return { - title: templateSlug, - slug: templateSlug, - templatePrefix: 'author', - }; - }, - }, - labels: { - singular_name: __( 'Author' ), - search_items: __( 'Search Authors' ), - not_found: __( 'No authors found.' ), - all_items: __( 'All Authors' ), - }, - hasGeneralTemplate, - template, - } ); - }; - } - if ( ! hasGeneralTemplate || authorInfo.user?.hasEntities ) { - return authorMenuItem; - } -} - -/** - * Helper hook that filters all the existing templates by the given - * object with the entity's slug as key and the template prefix as value. - * - * Example: - * `existingTemplates` is: [ { slug: 'tag-apple' }, { slug: 'page-about' }, { slug: 'tag' } ] - * `templatePrefixes` is: { post_tag: 'tag' } - * It will return: { post_tag: ['apple'] } - * - * Note: We append the `-` to the given template prefix in this function for our checks. - * - * @param {Record} templatePrefixes An object with the entity's slug as key and the template prefix as value. - * @return {Record} An object with the entity's slug as key and an array with the existing template slugs as value. - */ -const useExistingTemplateSlugs = ( templatePrefixes ) => { - const existingTemplates = useExistingTemplates(); - const existingSlugs = useMemo( () => { - return Object.entries( templatePrefixes || {} ).reduce( - ( accumulator, [ slug, prefix ] ) => { - const slugsWithTemplates = ( existingTemplates || [] ).reduce( - ( _accumulator, existingTemplate ) => { - const _prefix = `${ prefix }-`; - if ( existingTemplate.slug.startsWith( _prefix ) ) { - _accumulator.push( - existingTemplate.slug.substring( - _prefix.length - ) - ); - } - return _accumulator; - }, - [] - ); - if ( slugsWithTemplates.length ) { - accumulator[ slug ] = slugsWithTemplates; - } - return accumulator; - }, - {} - ); - }, [ templatePrefixes, existingTemplates ] ); - return existingSlugs; -}; - -/** - * Helper hook that finds the existing records with an associated template, - * as they need to be excluded from the template suggestions. - * - * @param {string} entityName The entity's name. - * @param {Record} templatePrefixes An object with the entity's slug as key and the template prefix as value. - * @param {Record} additionalQueryParameters An object with the entity's slug as key and additional query parameters as value. - * @return {Record} An object with the entity's slug as key and the existing records as value. - */ -const useTemplatesToExclude = ( - entityName, - templatePrefixes, - additionalQueryParameters = {} -) => { - const slugsToExcludePerEntity = - useExistingTemplateSlugs( templatePrefixes ); - const recordsToExcludePerEntity = useSelect( - ( select ) => { - return Object.entries( slugsToExcludePerEntity || {} ).reduce( - ( accumulator, [ slug, slugsWithTemplates ] ) => { - const entitiesWithTemplates = select( - coreStore - ).getEntityRecords( entityName, slug, { - _fields: 'id', - context: 'view', - slug: slugsWithTemplates, - ...additionalQueryParameters[ slug ], - } ); - if ( entitiesWithTemplates?.length ) { - accumulator[ slug ] = entitiesWithTemplates; - } - return accumulator; - }, - {} - ); - }, - [ slugsToExcludePerEntity ] - ); - return recordsToExcludePerEntity; -}; - -/** - * Helper hook that returns information about an entity having - * records that we can create a specific template for. - * - * For example we can search for `terms` in `taxonomy` entity or - * `posts` in `postType` entity. - * - * First we need to find the existing records with an associated template, - * to query afterwards for any remaining record, by excluding them. - * - * @param {string} entityName The entity's name. - * @param {Record} templatePrefixes An object with the entity's slug as key and the template prefix as value. - * @param {Record} additionalQueryParameters An object with the entity's slug as key and additional query parameters as value. - * @return {Record} An object with the entity's slug as key and the EntitiesInfo as value. - */ -const useEntitiesInfo = ( - entityName, - templatePrefixes, - additionalQueryParameters = EMPTY_OBJECT -) => { - const recordsToExcludePerEntity = useTemplatesToExclude( - entityName, - templatePrefixes, - additionalQueryParameters - ); - const entitiesHasRecords = useSelect( - ( select ) => { - return Object.keys( templatePrefixes || {} ).reduce( - ( accumulator, slug ) => { - const existingEntitiesIds = - recordsToExcludePerEntity?.[ slug ]?.map( - ( { id } ) => id - ) || []; - const records = select( coreStore ).getEntityRecords( - entityName, - slug, - { - per_page: 1, - _fields: 'id', - context: 'view', - exclude: existingEntitiesIds, - ...additionalQueryParameters[ slug ], - } - ); - accumulator[ slug ] = - records === null || records.length > 0; - return accumulator; - }, - {} - ); - }, - [ - templatePrefixes, - recordsToExcludePerEntity, - entityName, - additionalQueryParameters, - ] - ); - const entitiesInfo = useMemo( () => { - return Object.keys( templatePrefixes || {} ).reduce( - ( accumulator, slug ) => { - const existingEntitiesIds = - recordsToExcludePerEntity?.[ slug ]?.map( - ( { id } ) => id - ) || []; - accumulator[ slug ] = { - hasEntities: entitiesHasRecords[ slug ], - existingEntitiesIds, - }; - return accumulator; - }, - {} - ); - }, [ templatePrefixes, recordsToExcludePerEntity, entitiesHasRecords ] ); - return entitiesInfo; -}; diff --git a/packages/edit-site/src/components/add-new-template/add-custom-template-modal-content.jsx b/packages/edit-site/src/components/add-new-template/add-custom-template-modal-content.jsx index 4931074b712552..3680fd0d8be9f9 100644 --- a/packages/edit-site/src/components/add-new-template/add-custom-template-modal-content.jsx +++ b/packages/edit-site/src/components/add-new-template/add-custom-template-modal-content.jsx @@ -165,7 +165,9 @@ function AddCustomTemplateModalContent( { onBack, containerRef, } ) { - const [ showSearchEntities, setShowSearchEntities ] = useState(); + const [ showSearchEntities, setShowSearchEntities ] = useState( + entityForSuggestions.hasGeneralTemplate + ); // Focus on the first focusable element when the modal opens. // We handle focus management in the parent modal, just need to focus on the first focusable element. diff --git a/packages/edit-site/src/components/add-new-template/index.jsx b/packages/edit-site/src/components/add-new-template/index.jsx index 0d3a3919221f48..50ab8b14671a45 100644 --- a/packages/edit-site/src/components/add-new-template/index.jsx +++ b/packages/edit-site/src/components/add-new-template/index.jsx @@ -38,6 +38,7 @@ import { focus } from '@wordpress/dom'; import { TEMPLATE_POST_TYPE } from '../../utils/constants'; import AddCustomTemplateModalContent from './add-custom-template-modal-content'; import { + useExistingTemplates, useDefaultTemplateTypes, useTaxonomiesMenuItems, usePostTypeMenuItems, @@ -196,9 +197,7 @@ function NewTemplateModal( { onClose } ) { status: 'publish', title, // This adds a post meta field in template that is part of `is_custom` value calculation. - meta: { - is_wp_suggestion: isWPSuggestion, - }, + is_wp_suggestion: isWPSuggestion, }, { throwOnError: true } ); @@ -375,9 +374,15 @@ function NewTemplate() { } function useMissingTemplates( setEntityForSuggestions, onClick ) { + const existingTemplates = useExistingTemplates(); const defaultTemplateTypes = useDefaultTemplateTypes(); + const existingTemplateSlugs = ( existingTemplates || [] ).map( + ( { slug } ) => slug + ); const missingDefaultTemplates = ( defaultTemplateTypes || [] ).filter( - ( template ) => DEFAULT_TEMPLATE_SLUGS.includes( template.slug ) + ( template ) => + DEFAULT_TEMPLATE_SLUGS.includes( template.slug ) && + ! existingTemplateSlugs.includes( template.slug ) ); const onClickMenuItem = ( _entityForSuggestions ) => { onClick?.(); diff --git a/packages/edit-site/src/components/add-new-template/utils.js b/packages/edit-site/src/components/add-new-template/utils.js index 61b4e6c399d810..ef90c8126a3e96 100644 --- a/packages/edit-site/src/components/add-new-template/utils.js +++ b/packages/edit-site/src/components/add-new-template/utils.js @@ -197,6 +197,7 @@ export function usePostTypeArchiveMenuItems() { export const usePostTypeMenuItems = ( onClickMenuItem ) => { const publicPostTypes = usePublicPostTypes(); + const existingTemplates = useExistingTemplates(); const defaultTemplateTypes = useDefaultTemplateTypes(); // We need to keep track of naming conflicts. If a conflict // occurs, we need to add slug. @@ -236,6 +237,9 @@ export const usePostTypeMenuItems = ( onClickMenuItem ) => { [ publicPostTypes ] ); const postTypesInfo = useEntitiesInfo( 'postType', templatePrefixes ); + const existingTemplateSlugs = ( existingTemplates || [] ).map( + ( { slug } ) => slug + ); const menuItems = ( publicPostTypes || [] ).reduce( ( accumulator, postType ) => { const { slug, labels, icon } = postType; @@ -246,6 +250,8 @@ export const usePostTypeMenuItems = ( onClickMenuItem ) => { const defaultTemplateType = defaultTemplateTypes?.find( ( { slug: _slug } ) => _slug === generalTemplateSlug ); + const hasGeneralTemplate = + existingTemplateSlugs?.includes( generalTemplateSlug ); const _needsUniqueIdentifier = needsUniqueIdentifier( postType ); let menuItemTitle = labels.template_name || @@ -326,12 +332,14 @@ export const usePostTypeMenuItems = ( onClickMenuItem ) => { }, }, labels, + hasGeneralTemplate, template, } ); }; } - // We don't need to add the menu item if there are no entities. - if ( hasEntities ) { + // We don't need to add the menu item if there are no + // entities and the general template exists. + if ( ! hasGeneralTemplate || hasEntities ) { accumulator.push( menuItem ); } return accumulator; @@ -564,11 +572,7 @@ export function useAuthorMenuItem( onClickMenuItem ) { suggestion.slug ); return { - title: sprintf( - // translators: %s: Name of the author e.g: "Admin". - __( 'Author: %s' ), - suggestion.name - ), + title: templateSlug, slug: templateSlug, templatePrefix: 'author', }; @@ -590,6 +594,91 @@ export function useAuthorMenuItem( onClickMenuItem ) { } } +/** + * Helper hook that filters all the existing templates by the given + * object with the entity's slug as key and the template prefix as value. + * + * Example: + * `existingTemplates` is: [ { slug: 'tag-apple' }, { slug: 'page-about' }, { slug: 'tag' } ] + * `templatePrefixes` is: { post_tag: 'tag' } + * It will return: { post_tag: ['apple'] } + * + * Note: We append the `-` to the given template prefix in this function for our checks. + * + * @param {Record} templatePrefixes An object with the entity's slug as key and the template prefix as value. + * @return {Record} An object with the entity's slug as key and an array with the existing template slugs as value. + */ +const useExistingTemplateSlugs = ( templatePrefixes ) => { + const existingTemplates = useExistingTemplates(); + const existingSlugs = useMemo( () => { + return Object.entries( templatePrefixes || {} ).reduce( + ( accumulator, [ slug, prefix ] ) => { + const slugsWithTemplates = ( existingTemplates || [] ).reduce( + ( _accumulator, existingTemplate ) => { + const _prefix = `${ prefix }-`; + if ( existingTemplate.slug.startsWith( _prefix ) ) { + _accumulator.push( + existingTemplate.slug.substring( + _prefix.length + ) + ); + } + return _accumulator; + }, + [] + ); + if ( slugsWithTemplates.length ) { + accumulator[ slug ] = slugsWithTemplates; + } + return accumulator; + }, + {} + ); + }, [ templatePrefixes, existingTemplates ] ); + return existingSlugs; +}; + +/** + * Helper hook that finds the existing records with an associated template, + * as they need to be excluded from the template suggestions. + * + * @param {string} entityName The entity's name. + * @param {Record} templatePrefixes An object with the entity's slug as key and the template prefix as value. + * @param {Record} additionalQueryParameters An object with the entity's slug as key and additional query parameters as value. + * @return {Record} An object with the entity's slug as key and the existing records as value. + */ +const useTemplatesToExclude = ( + entityName, + templatePrefixes, + additionalQueryParameters = {} +) => { + const slugsToExcludePerEntity = + useExistingTemplateSlugs( templatePrefixes ); + const recordsToExcludePerEntity = useSelect( + ( select ) => { + return Object.entries( slugsToExcludePerEntity || {} ).reduce( + ( accumulator, [ slug, slugsWithTemplates ] ) => { + const entitiesWithTemplates = select( + coreStore + ).getEntityRecords( entityName, slug, { + _fields: 'id', + context: 'view', + slug: slugsWithTemplates, + ...additionalQueryParameters[ slug ], + } ); + if ( entitiesWithTemplates?.length ) { + accumulator[ slug ] = entitiesWithTemplates; + } + return accumulator; + }, + {} + ); + }, + [ slugsToExcludePerEntity ] + ); + return recordsToExcludePerEntity; +}; + /** * Helper hook that returns information about an entity having * records that we can create a specific template for. @@ -610,10 +699,19 @@ const useEntitiesInfo = ( templatePrefixes, additionalQueryParameters = EMPTY_OBJECT ) => { + const recordsToExcludePerEntity = useTemplatesToExclude( + entityName, + templatePrefixes, + additionalQueryParameters + ); const entitiesHasRecords = useSelect( ( select ) => { return Object.keys( templatePrefixes || {} ).reduce( ( accumulator, slug ) => { + const existingEntitiesIds = + recordsToExcludePerEntity?.[ slug ]?.map( + ( { id } ) => id + ) || []; const records = select( coreStore ).getEntityRecords( entityName, slug, @@ -621,6 +719,7 @@ const useEntitiesInfo = ( per_page: 1, _fields: 'id', context: 'view', + exclude: existingEntitiesIds, ...additionalQueryParameters[ slug ], } ); @@ -631,18 +730,28 @@ const useEntitiesInfo = ( {} ); }, - [ templatePrefixes, entityName, additionalQueryParameters ] + [ + templatePrefixes, + recordsToExcludePerEntity, + entityName, + additionalQueryParameters, + ] ); const entitiesInfo = useMemo( () => { return Object.keys( templatePrefixes || {} ).reduce( ( accumulator, slug ) => { + const existingEntitiesIds = + recordsToExcludePerEntity?.[ slug ]?.map( + ( { id } ) => id + ) || []; accumulator[ slug ] = { hasEntities: entitiesHasRecords[ slug ], + existingEntitiesIds, }; return accumulator; }, {} ); - }, [ templatePrefixes, entitiesHasRecords ] ); + }, [ templatePrefixes, recordsToExcludePerEntity, entitiesHasRecords ] ); return entitiesInfo; }; diff --git a/packages/edit-site/src/components/dataviews-actions/index.js b/packages/edit-site/src/components/dataviews-actions/index.js index 7557c7300c938b..1c1b8723810076 100644 --- a/packages/edit-site/src/components/dataviews-actions/index.js +++ b/packages/edit-site/src/components/dataviews-actions/index.js @@ -2,73 +2,12 @@ import { __ } from '@wordpress/i18n'; import { pencil, drawerRight } from '@wordpress/icons'; import { useMemo } from '@wordpress/element'; import { privateApis as routerPrivateApis } from '@wordpress/router'; -import { useDispatch, useSelect } from '@wordpress/data'; -import { store as coreStore } from '@wordpress/core-data'; import { addQueryArgs } from '@wordpress/url'; import { PATTERN_TYPES } from '../../utils/constants'; import { unlock } from '../../lock-unlock'; const { useLocation, useHistory } = unlock( routerPrivateApis ); -export const useSetActiveTemplateAction = () => { - const activeTheme = useSelect( ( select ) => - select( coreStore ).getCurrentTheme() - ); - const { getEntityRecord } = useSelect( coreStore ); - const { editEntityRecord, saveEditedEntityRecord } = - useDispatch( coreStore ); - return useMemo( - () => ( { - id: 'set-active-template', - label( items ) { - return items.some( ( item ) => item._isActive ) - ? __( 'Deactivate' ) - : __( 'Activate' ); - }, - isPrimary: true, - icon: pencil, - isEligible( item ) { - if ( item.theme !== activeTheme.stylesheet ) { - return false; - } - - // If it's not a created template but a registered template, - // only allow activating (so when it's inactive). - if ( typeof item.id !== 'number' ) { - return item._isActive === false; - } - - return true; - }, - async callback( items ) { - const deactivate = items.some( ( item ) => item._isActive ); - // current active templates - const activeTemplates = { - ...( ( await getEntityRecord( 'root', 'site' ) - .active_templates ) ?? {} ), - }; - for ( const item of items ) { - if ( deactivate ) { - delete activeTemplates[ item.slug ]; - } else { - activeTemplates[ item.slug ] = item.id; - } - } - await editEntityRecord( 'root', 'site', undefined, { - active_templates: activeTemplates, - } ); - await saveEditedEntityRecord( 'root', 'site' ); - }, - } ), - [ - editEntityRecord, - saveEditedEntityRecord, - getEntityRecord, - activeTheme, - ] - ); -}; - export const useEditPostAction = () => { const history = useHistory(); return useMemo( diff --git a/packages/edit-site/src/components/page-templates/fields.jsx b/packages/edit-site/src/components/page-templates/fields.jsx index ef4c0b22a0bb73..fe3e9bd2b8cdd7 100644 --- a/packages/edit-site/src/components/page-templates/fields.jsx +++ b/packages/edit-site/src/components/page-templates/fields.jsx @@ -1,52 +1,16 @@ -import clsx from 'clsx'; -import { - Icon as WCIcon, - __experimentalHStack as HStack, - privateApis as componentsPrivateApis, -} from '@wordpress/components'; -import { __, _x } from '@wordpress/i18n'; -import { useState, useMemo } from '@wordpress/element'; -import { decodeEntities } from '@wordpress/html-entities'; +import { __ } from '@wordpress/i18n'; +import { useMemo } from '@wordpress/element'; import { parse } from '@wordpress/blocks'; import { BlockPreview } from '@wordpress/block-editor'; import { EditorProvider, privateApis as editorPrivateApis, } from '@wordpress/editor'; -import { - privateApis as corePrivateApis, - store as coreStore, -} from '@wordpress/core-data'; -import { useSelect } from '@wordpress/data'; -import { useAddedBy } from './hooks'; -import { useDefaultTemplateTypes } from '../add-new-template/utils'; import usePatternSettings from '../page-patterns/use-pattern-settings'; import { unlock } from '../../lock-unlock'; -const { Badge: WCBadge } = unlock( componentsPrivateApis ); -const { useEntityRecordsWithPermissions } = unlock( corePrivateApis ); const { useStyle } = unlock( editorPrivateApis ); -function useAllDefaultTemplateTypes() { - const defaultTemplateTypes = useDefaultTemplateTypes(); - const { records: staticRecords } = useEntityRecordsWithPermissions( - 'root', - 'registeredTemplate' - ); - return [ - ...defaultTemplateTypes, - ...staticRecords - ?.filter( ( record ) => ! record.is_custom ) - .map( ( record ) => { - return { - slug: record.slug, - title: record.title.rendered, - description: record.description, - }; - } ), - ]; -} - function PreviewField( { item } ) { const settings = usePatternSettings(); const backgroundColor = useStyle( 'color.background' ) ?? 'white'; @@ -85,111 +49,3 @@ export const previewField = { render: PreviewField, enableSorting: false, }; - -export const descriptionField = { - label: __( 'Description' ), - id: 'description', - render: window?.__experimentalTemplateActivate - ? function RenderDescription( { item } ) { - const defaultTemplateTypes = useAllDefaultTemplateTypes(); - const defaultTemplateType = defaultTemplateTypes.find( - ( type ) => type.slug === item.slug - ); - return item.description - ? decodeEntities( item.description ) - : defaultTemplateType?.description; - } - : ( { item } ) => { - return item.description && decodeEntities( item.description ); - }, - enableSorting: false, - enableGlobalSearch: true, -}; - -function AuthorField( { item } ) { - const [ isImageLoaded, setIsImageLoaded ] = useState( false ); - const { text, icon, imageUrl } = useAddedBy( item.type, item.id ); - - return ( - - { imageUrl && ( -
- setIsImageLoaded( true ) } - alt="" - src={ imageUrl } - /> -
- ) } - { ! imageUrl && ( -
- -
- ) } - { text } -
- ); -} - -export const authorField = { - label: __( 'Author' ), - id: 'author', - getValue: ( { item } ) => item.author_text ?? item.author, - render: AuthorField, -}; - -export const activeField = { - label: __( 'Status' ), - id: 'active', - type: 'boolean', - getValue: ( { item } ) => item._isActive, - render: function Render( { item } ) { - const activeLabel = item._isCustom - ? _x( 'Active when used', 'template' ) - : _x( 'Active', 'template' ); - const activeIntent = item._isCustom ? 'info' : 'success'; - const isActive = item._isActive; - return ( - - { isActive ? activeLabel : _x( 'Inactive', 'template' ) } - - ); - }, -}; - -export const useThemeField = () => { - const activeTheme = useSelect( ( select ) => - select( coreStore ).getCurrentTheme() - ); - return useMemo( - () => ( { - label: __( 'Compatible Theme' ), - id: 'theme', - getValue: ( { item } ) => item.theme, - render: function Render( { item } ) { - if ( item.theme === activeTheme.stylesheet ) { - return { item.theme }; - } - return { item.theme }; - }, - } ), - [ activeTheme ] - ); -}; - -export const slugField = { - label: __( 'Template Type' ), - id: 'slug', - getValue: ( { item } ) => item.slug, - render: function Render( { item } ) { - const defaultTemplateTypes = useAllDefaultTemplateTypes(); - const defaultTemplateType = defaultTemplateTypes.find( - ( type ) => type.slug === item.slug - ); - return defaultTemplateType?.title || _x( 'Custom', 'template type' ); - }, -}; diff --git a/packages/edit-site/src/components/page-templates/hooks.js b/packages/edit-site/src/components/page-templates/hooks.js deleted file mode 100644 index f84bfb48eff77c..00000000000000 --- a/packages/edit-site/src/components/page-templates/hooks.js +++ /dev/null @@ -1,93 +0,0 @@ -import { store as coreStore } from '@wordpress/core-data'; -import { useSelect } from '@wordpress/data'; -import { - commentAuthorAvatar as authorIcon, - layout as themeIcon, - plugins as pluginIcon, - globe as globeIcon, -} from '@wordpress/icons'; -import { TEMPLATE_ORIGINS } from '../../utils/constants'; - -/** @typedef {'wp_template'|'wp_template_part'} TemplateType */ - -/** - * @typedef {'theme'|'plugin'|'site'|'user'} AddedByType - * - * @typedef AddedByData - * @type {Object} - * @property {AddedByType} type The type of the data. - * @property {React.JSX.Element} icon The icon to display. - * @property {string} [imageUrl] The optional image URL to display. - * @property {string} [text] The text to display. - * @property {boolean} isCustomized Whether the template has been customized. - * - * @param {TemplateType} postType The template post type. - * @param {number} postId The template post id. - * @return {AddedByData} The added by object or null. - */ -export function useAddedBy( postType, postId ) { - return useSelect( - ( select ) => { - const { getEntityRecord, getUser, getEditedEntityRecord } = - select( coreStore ); - const template = getEditedEntityRecord( - 'postType', - postType, - postId - ); - const originalSource = template?.original_source; - const authorText = template?.author_text; - - switch ( originalSource ) { - case 'theme': { - return { - type: originalSource, - icon: themeIcon, - text: authorText, - isCustomized: - template.source === TEMPLATE_ORIGINS.custom, - }; - } - case 'plugin': { - return { - type: originalSource, - icon: pluginIcon, - text: authorText, - isCustomized: - template.source === TEMPLATE_ORIGINS.custom, - }; - } - case 'site': { - const siteData = getEntityRecord( - 'root', - '__unstableBase' - ); - return { - type: originalSource, - icon: globeIcon, - imageUrl: siteData?.site_logo - ? getEntityRecord( - 'postType', - 'attachment', - siteData.site_logo - )?.source_url - : undefined, - text: authorText, - isCustomized: false, - }; - } - default: { - const user = getUser( template.author ); - return { - type: 'user', - icon: authorIcon, - imageUrl: user?.avatar_urls?.[ 48 ], - text: authorText ?? user?.name, - isCustomized: false, - }; - } - } - }, - [ postType, postId ] - ); -} diff --git a/packages/edit-site/src/components/page-templates/index-legacy.jsx b/packages/edit-site/src/components/page-templates/index-legacy.jsx deleted file mode 100644 index 0fc8ddcc6a72c6..00000000000000 --- a/packages/edit-site/src/components/page-templates/index-legacy.jsx +++ /dev/null @@ -1,143 +0,0 @@ -import { Page } from '@wordpress/admin-ui'; -import { __ } from '@wordpress/i18n'; -import { useState, useMemo, useCallback } from '@wordpress/element'; -import { privateApis as corePrivateApis } from '@wordpress/core-data'; -import { DataViews, filterSortAndPaginate } from '@wordpress/dataviews'; -import { privateApis as routerPrivateApis } from '@wordpress/router'; -import { privateApis as editorPrivateApis } from '@wordpress/editor'; -import { addQueryArgs } from '@wordpress/url'; -import { useEvent } from '@wordpress/compose'; -import { useView, useViewConfig } from '@wordpress/views'; -import AddNewTemplate from '../add-new-template-legacy'; -import { TEMPLATE_POST_TYPE } from '../../utils/constants'; -import { unlock } from '../../lock-unlock'; -import { useEditPostAction } from '../dataviews-actions'; -import { previewField } from './fields'; - -const { usePostActions, usePostFields } = unlock( editorPrivateApis ); -const { useHistory, useLocation } = unlock( routerPrivateApis ); -const { useEntityRecordsWithPermissions } = unlock( corePrivateApis ); - -const VIEW_CONFIG_FIELDS = [ 'default_view', 'default_layouts', 'view_list' ]; - -export default function PageTemplates() { - const { path, query } = useLocation(); - const { activeView = 'all', postId } = query; - const [ selection, setSelection ] = useState( [ postId ] ); - - const { - default_view: defaultView, - default_layouts: defaultLayouts, - view_list: viewList, - } = useViewConfig( { - kind: 'postType', - name: TEMPLATE_POST_TYPE, - fields: VIEW_CONFIG_FIELDS, - } ); - const activeViewOverrides = useMemo( - () => viewList?.find( ( v ) => v.slug === activeView )?.view ?? {}, - [ viewList, activeView ] - ); - const { view, updateView, isModified, resetToDefault } = useView( { - kind: 'postType', - name: TEMPLATE_POST_TYPE, - slug: 'default', - defaultView, - activeViewOverrides, - defaultLayouts, - queryParams: { - page: query.pageNumber, - search: query.search, - }, - onChangeQueryParams: ( newQueryParams ) => { - history.navigate( - addQueryArgs( path, { - ...query, - pageNumber: newQueryParams.page, - search: newQueryParams.search || undefined, - } ) - ); - }, - } ); - - const { records, isResolving: isLoadingData } = - useEntityRecordsWithPermissions( 'postType', TEMPLATE_POST_TYPE, { - per_page: -1, - } ); - const history = useHistory(); - const onChangeSelection = useCallback( - ( items ) => { - setSelection( items ); - if ( view?.type === 'list' ) { - history.navigate( - addQueryArgs( path, { - postId: items.length === 1 ? items[ 0 ] : undefined, - } ) - ); - } - }, - [ history, path, view?.type ] - ); - - const postFields = usePostFields( { postType: TEMPLATE_POST_TYPE } ); - const fields = useMemo( () => { - return [ previewField, ...( postFields || [] ) ]; - }, [ postFields ] ); - - const { data, paginationInfo } = useMemo( () => { - return filterSortAndPaginate( records, view, fields ); - }, [ records, view, fields ] ); - - const postTypeActions = usePostActions( { - postType: TEMPLATE_POST_TYPE, - context: 'list', - } ); - const editAction = useEditPostAction(); - const actions = useMemo( - () => [ editAction, ...postTypeActions ], - [ postTypeActions, editAction ] - ); - - const onChangeView = useEvent( ( newView ) => { - updateView( newView ); - if ( newView.type !== view.type ) { - // Retrigger the routing areas resolution. - history.invalidate(); - } - } ); - - return ( - } - > - true } - onClickItem={ ( { id } ) => { - history.navigate( `/wp_template/${ id }?canvas=edit` ); - } } - selection={ selection } - defaultLayouts={ defaultLayouts } - onReset={ - isModified - ? () => { - resetToDefault(); - history.invalidate(); - } - : false - } - /> - - ); -} diff --git a/packages/edit-site/src/components/page-templates/index.jsx b/packages/edit-site/src/components/page-templates/index.jsx index 22d38d5ed693a8..72d78c14956dfd 100644 --- a/packages/edit-site/src/components/page-templates/index.jsx +++ b/packages/edit-site/src/components/page-templates/index.jsx @@ -1,56 +1,42 @@ import { Page } from '@wordpress/admin-ui'; -import { __, sprintf } from '@wordpress/i18n'; -import { decodeEntities } from '@wordpress/html-entities'; +import { __ } from '@wordpress/i18n'; import { useState, useMemo, useCallback } from '@wordpress/element'; -import { - privateApis as corePrivateApis, - store as coreStore, -} from '@wordpress/core-data'; +import { privateApis as corePrivateApis } from '@wordpress/core-data'; import { DataViews, filterSortAndPaginate } from '@wordpress/dataviews'; import { privateApis as routerPrivateApis } from '@wordpress/router'; import { privateApis as editorPrivateApis } from '@wordpress/editor'; import { addQueryArgs } from '@wordpress/url'; -import { useSelect, useDispatch } from '@wordpress/data'; import { useEvent } from '@wordpress/compose'; -import { useView } from '@wordpress/views'; -import { Modal } from '@wordpress/components'; -import { store as noticesStore } from '@wordpress/notices'; +import { useView, useViewConfig } from '@wordpress/views'; import AddNewTemplate from '../add-new-template'; import { TEMPLATE_POST_TYPE } from '../../utils/constants'; import { unlock } from '../../lock-unlock'; -import { - useEditPostAction, - useSetActiveTemplateAction, -} from '../dataviews-actions'; -import { - authorField, - descriptionField, - previewField, - activeField, - slugField, - useThemeField, -} from './fields'; -import { - defaultLayouts, - DEFAULT_VIEW, - getActiveViewOverridesForTab, -} from './view-utils'; +import { useEditPostAction } from '../dataviews-actions'; +import { previewField } from './fields'; -const { usePostActions, usePostFields, templateTitleField } = - unlock( editorPrivateApis ); +const { usePostActions, usePostFields } = unlock( editorPrivateApis ); const { useHistory, useLocation } = unlock( routerPrivateApis ); const { useEntityRecordsWithPermissions } = unlock( corePrivateApis ); +const VIEW_CONFIG_FIELDS = [ 'default_view', 'default_layouts', 'view_list' ]; + export default function PageTemplates() { const { path, query } = useLocation(); - const { activeView = 'active', postId } = query; + const { activeView = 'all', postId } = query; const [ selection, setSelection ] = useState( [ postId ] ); - const [ selectedRegisteredTemplate, setSelectedRegisteredTemplate ] = - useState( false ); - const defaultView = DEFAULT_VIEW; + + const { + default_view: defaultView, + default_layouts: defaultLayouts, + view_list: viewList, + } = useViewConfig( { + kind: 'postType', + name: TEMPLATE_POST_TYPE, + fields: VIEW_CONFIG_FIELDS, + } ); const activeViewOverrides = useMemo( - () => getActiveViewOverridesForTab( activeView ), - [ activeView ] + () => viewList?.find( ( v ) => v.slug === activeView )?.view ?? {}, + [ viewList, activeView ] ); const { view, updateView, isModified, resetToDefault } = useView( { kind: 'postType', @@ -58,6 +44,7 @@ export default function PageTemplates() { slug: 'default', defaultView, activeViewOverrides, + defaultLayouts, queryParams: { page: query.pageNumber, search: query.search, @@ -73,129 +60,10 @@ export default function PageTemplates() { }, } ); - const { activeTemplatesOption, activeTheme, defaultTemplateTypes } = - useSelect( ( select ) => { - const { getEntityRecord, getCurrentTheme } = select( coreStore ); - return { - activeTemplatesOption: getEntityRecord( 'root', 'site' ) - ?.active_templates, - activeTheme: getCurrentTheme(), - defaultTemplateTypes: - select( coreStore ).getCurrentTheme() - ?.default_template_types, - }; - } ); - // Todo: this will have to be better so that we're not fetching all the - // records all the time. Active templates query will need to move server - // side. - const { records: userRecords, isResolving: isLoadingUserRecords } = + const { records, isResolving: isLoadingData } = useEntityRecordsWithPermissions( 'postType', TEMPLATE_POST_TYPE, { per_page: -1, - combinedTemplates: false, - } ); - const { records: staticRecords, isResolving: isLoadingStaticData } = - useEntityRecordsWithPermissions( 'root', 'registeredTemplate', { - // This should not be needed, the endpoint returns all registered - // templates, but it's not possible right now to turn off pagination - // for entity configs. - per_page: -1, } ); - - const activeTemplates = useMemo( () => { - const _active = [ ...staticRecords ]; - if ( activeTemplatesOption ) { - for ( const activeSlug in activeTemplatesOption ) { - const activeId = activeTemplatesOption[ activeSlug ]; - // Replace the template in the array. - const template = userRecords.find( - ( userRecord ) => - userRecord.id === activeId && - userRecord.theme === activeTheme.stylesheet - ); - if ( template ) { - const index = _active.findIndex( - ( { slug } ) => slug === template.slug - ); - if ( index !== -1 ) { - _active[ index ] = template; - } else { - _active.push( template ); - } - } - } - } - return _active; - }, [ userRecords, staticRecords, activeTemplatesOption, activeTheme ] ); - - let isLoadingData; - if ( activeView === 'active' ) { - isLoadingData = isLoadingUserRecords || isLoadingStaticData; - } else if ( activeView === 'user' ) { - isLoadingData = isLoadingUserRecords; - } else { - isLoadingData = isLoadingStaticData; - } - - const records = useMemo( () => { - function isCustom( record ) { - // For registered templates, the is_custom field is defined. - return ( - record.is_custom ?? - // For user templates it's custom if the is_wp_suggestion meta - // field is not set and the slug is not found in the default - // template types. - ( ! record.meta?.is_wp_suggestion && - ! defaultTemplateTypes.some( - ( type ) => type.slug === record.slug - ) ) - ); - } - - let _records; - if ( activeView === 'active' ) { - // Don't show active custom templates in the active view. - _records = activeTemplates.filter( - ( record ) => ! isCustom( record ) - ); - } else if ( activeView === 'user' ) { - _records = userRecords; - } else { - _records = staticRecords; - } - return _records.map( ( record ) => ( { - ...record, - _isActive: activeTemplates.some( - ( template ) => template.id === record.id - ), - _isCustom: isCustom( record ), - } ) ); - }, [ - activeTemplates, - defaultTemplateTypes, - userRecords, - staticRecords, - activeView, - ] ); - - const users = useSelect( - ( select ) => { - const { getUser } = select( coreStore ); - return records.reduce( ( acc, record ) => { - if ( record.author_text ) { - if ( ! acc[ record.author_text ] ) { - acc[ record.author_text ] = record.author_text; - } - } else if ( record.author ) { - if ( ! acc[ record.author ] ) { - acc[ record.author ] = getUser( record.author ); - } - } - return acc; - }, {} ); - }, - [ records ] - ); - const history = useHistory(); const onChangeSelection = useCallback( ( items ) => { @@ -211,95 +79,23 @@ export default function PageTemplates() { [ history, path, view?.type ] ); - const postTypeFields = usePostFields( { - postType: TEMPLATE_POST_TYPE, - } ); - const dateField = postTypeFields.find( ( field ) => field.id === 'date' ); - const themeField = useThemeField(); + const postFields = usePostFields( { postType: TEMPLATE_POST_TYPE } ); const fields = useMemo( () => { - const _fields = [ - previewField, - templateTitleField, - descriptionField, - activeField, - slugField, - ]; - if ( activeView === 'user' ) { - _fields.push( themeField ); - if ( dateField ) { - _fields.push( dateField ); - } - } - const elements = []; - for ( const author in users ) { - elements.push( { - value: users[ author ]?.id ?? author, - label: users[ author ]?.name ?? author, - } ); - } - _fields.push( { - ...authorField, - elements, - } ); - return _fields; - }, [ users, activeView, themeField, dateField ] ); + return [ previewField, ...( postFields || [] ) ]; + }, [ postFields ] ); const { data, paginationInfo } = useMemo( () => { return filterSortAndPaginate( records, view, fields ); }, [ records, view, fields ] ); - const { createSuccessNotice } = useDispatch( noticesStore ); - const onActionPerformed = useCallback( - ( actionId, items ) => { - switch ( actionId ) { - case 'duplicate-post': - { - const newItem = items[ 0 ]; - const _title = - typeof newItem.title === 'string' - ? newItem.title - : newItem.title?.rendered; - history.navigate( `/template?activeView=user` ); - createSuccessNotice( - sprintf( - // translators: %s: Title of the created post or template, e.g: "Hello world". - __( '"%s" successfully created.' ), - decodeEntities( _title ) || __( '(no title)' ) - ), - { - type: 'snackbar', - id: 'duplicate-post-action', - actions: [ - { - label: __( 'Edit' ), - onClick: () => { - history.navigate( - `/${ newItem.type }/${ newItem.id }?canvas=edit` - ); - }, - }, - ], - } - ); - } - break; - } - }, - [ history, createSuccessNotice ] - ); const postTypeActions = usePostActions( { postType: TEMPLATE_POST_TYPE, context: 'list', - onActionPerformed, } ); const editAction = useEditPostAction(); - const setActiveTemplateAction = useSetActiveTemplateAction(); const actions = useMemo( - () => - activeView === 'user' - ? [ setActiveTemplateAction, editAction, ...postTypeActions ] - : [ setActiveTemplateAction, ...postTypeActions ], - [ postTypeActions, setActiveTemplateAction, editAction, activeView ] + () => [ editAction, ...postTypeActions ], + [ postTypeActions, editAction ] ); const onChangeView = useEvent( ( newView ) => { @@ -310,10 +106,6 @@ export default function PageTemplates() { } } ); - const duplicateAction = actions.find( - ( action ) => action.id === 'duplicate-post' - ); - return ( true } - onClickItem={ ( item ) => { - if ( typeof item.id === 'string' ) { - setSelectedRegisteredTemplate( item ); - } else { - history.navigate( - `/${ item.type }/${ item.id }?canvas=edit` - ); - } + onClickItem={ ( { id } ) => { + history.navigate( `/wp_template/${ id }?canvas=edit` ); } } selection={ selection } defaultLayouts={ defaultLayouts } @@ -352,18 +138,6 @@ export default function PageTemplates() { : false } /> - { selectedRegisteredTemplate && duplicateAction && ( - setSelectedRegisteredTemplate() } - size="small" - > - setSelectedRegisteredTemplate() } - /> - - ) } ); } diff --git a/packages/edit-site/src/components/page-templates/view-utils.js b/packages/edit-site/src/components/page-templates/view-utils.js deleted file mode 100644 index fb7c772efeb568..00000000000000 --- a/packages/edit-site/src/components/page-templates/view-utils.js +++ /dev/null @@ -1,50 +0,0 @@ -export const defaultLayouts = { - table: { - showMedia: false, - }, - grid: { - showMedia: true, - }, - list: { - showMedia: false, - }, -}; - -export const DEFAULT_VIEW = { - type: 'grid', - perPage: 20, - sort: { - field: 'title', - direction: 'asc', - }, - titleField: 'title', - descriptionField: 'description', - mediaField: 'preview', - fields: [ 'author', 'active', 'slug', 'theme' ], - filters: [], - ...defaultLayouts.grid, -}; - -export function getActiveViewOverridesForTab( activeView ) { - // User view: sort by date, newest first - if ( activeView === 'user' ) { - return { - sort: { field: 'date', direction: 'desc' }, - }; - } - // Active view: no overrides - if ( activeView === 'active' ) { - return {}; - } - // Author-based view: filter by author - return { - filters: [ - { - field: 'author', - operator: 'is', - value: activeView, - isLocked: true, - }, - ], - }; -} diff --git a/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/content-legacy.jsx b/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/content-legacy.jsx deleted file mode 100644 index 64ec21fb5010d7..00000000000000 --- a/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/content-legacy.jsx +++ /dev/null @@ -1,52 +0,0 @@ -import { store as coreStore } from '@wordpress/core-data'; -import { useSelect } from '@wordpress/data'; -import { - commentAuthorAvatar, - layout, - plugins as pluginIcon, - globe, -} from '@wordpress/icons'; -import { TEMPLATE_POST_TYPE } from '../../utils/constants'; -import DataViewsSidebarContent from '../sidebar-dataviews'; - -const SOURCE_TO_ICON = { - user: commentAuthorAvatar, - theme: layout, - plugin: pluginIcon, - site: globe, -}; -export default function DataviewsTemplatesSidebarContent() { - const authorSourceMap = useSelect( ( select ) => { - const templates = select( coreStore ).getEntityRecords( - 'postType', - TEMPLATE_POST_TYPE, - { per_page: -1 } - ); - if ( ! templates ) { - return {}; - } - const map = {}; - for ( const template of templates ) { - if ( - template.author_text && - template.original_source && - ! map[ template.author_text ] - ) { - map[ template.author_text ] = template.original_source; - } - } - return map; - }, [] ); - - const resolveIcon = ( view ) => { - const source = authorSourceMap[ view.slug ]; - return SOURCE_TO_ICON[ source ] ?? layout; - }; - - return ( - - ); -} diff --git a/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/content.jsx b/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/content.jsx index 0098f82e09c1b1..64ec21fb5010d7 100644 --- a/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/content.jsx +++ b/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/content.jsx @@ -1,87 +1,52 @@ -import { useEntityRecords } from '@wordpress/core-data'; -import { useMemo } from '@wordpress/element'; -import { __experimentalItemGroup as ItemGroup } from '@wordpress/components'; -import { __ } from '@wordpress/i18n'; -import { privateApis as routerPrivateApis } from '@wordpress/router'; -import { addQueryArgs } from '@wordpress/url'; -import { commentAuthorAvatar, published } from '@wordpress/icons'; -import SidebarNavigationItem from '../sidebar-navigation-item'; -import { useAddedBy } from '../page-templates/hooks'; -import { unlock } from '../../lock-unlock'; - -const { useLocation } = unlock( routerPrivateApis ); - -const EMPTY_ARRAY = []; - -function TemplateDataviewItem( { template, isActive } ) { - const { text, icon } = useAddedBy( template.type, template.id ); - - return ( - - { text } - - ); -} +import { store as coreStore } from '@wordpress/core-data'; +import { useSelect } from '@wordpress/data'; +import { + commentAuthorAvatar, + layout, + plugins as pluginIcon, + globe, +} from '@wordpress/icons'; +import { TEMPLATE_POST_TYPE } from '../../utils/constants'; +import DataViewsSidebarContent from '../sidebar-dataviews'; +const SOURCE_TO_ICON = { + user: commentAuthorAvatar, + theme: layout, + plugin: pluginIcon, + site: globe, +}; export default function DataviewsTemplatesSidebarContent() { - const { - query: { activeView = 'active' }, - } = useLocation(); - const { records } = useEntityRecords( 'root', 'registeredTemplate', { - // This should not be needed, the endpoint returns all registered - // templates, but it's not possible right now to turn off pagination for - // entity configs. - per_page: -1, - } ); - const firstItemPerAuthorText = useMemo( () => { - const firstItemPerAuthor = records?.reduce( ( acc, template ) => { - const author = template.author_text; - if ( author && ! acc[ author ] ) { - acc[ author ] = template; - } - return acc; - }, {} ); - return ( - ( firstItemPerAuthor && Object.values( firstItemPerAuthor ) ) ?? - EMPTY_ARRAY + const authorSourceMap = useSelect( ( select ) => { + const templates = select( coreStore ).getEntityRecords( + 'postType', + TEMPLATE_POST_TYPE, + { per_page: -1 } ); - }, [ records ] ); + if ( ! templates ) { + return {}; + } + const map = {}; + for ( const template of templates ) { + if ( + template.author_text && + template.original_source && + ! map[ template.author_text ] + ) { + map[ template.author_text ] = template.original_source; + } + } + return map; + }, [] ); + + const resolveIcon = ( view ) => { + const source = authorSourceMap[ view.slug ]; + return SOURCE_TO_ICON[ source ] ?? layout; + }; return ( - - - { __( 'Active templates' ) } - - - { - // Let's avoid calling them "custom templates" to avoid - // confusion. "Created" is closest to meaning database - // templates, created by users. - // https://developer.wordpress.org/themes/classic-themes/templates/page-template-files/#creating-custom-page-templates-for-global-use - __( 'Created templates' ) - } - - { firstItemPerAuthorText.map( ( template ) => { - return ( - - ); - } ) } - + ); } diff --git a/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/index.jsx b/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/index.jsx index 6f3fdb26ec2977..d29c5f5e1948aa 100644 --- a/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/index.jsx +++ b/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/index.jsx @@ -1,7 +1,6 @@ import { __ } from '@wordpress/i18n'; import SidebarNavigationScreen from '../sidebar-navigation-screen'; import DataviewsTemplatesSidebarContent from './content'; -import DataviewsTemplatesSidebarContentLegacy from './content-legacy'; export default function SidebarNavigationScreenTemplatesBrowse( { backPath } ) { return ( @@ -11,13 +10,7 @@ export default function SidebarNavigationScreenTemplatesBrowse( { backPath } ) { 'Manage the templates that define the structure of your pages, or reset any customizations made to those supplied by your theme.' ) } backPath={ backPath } - content={ - window?.__experimentalTemplateActivate ? ( - - ) : ( - - ) - } + content={ } /> ); } diff --git a/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/style.scss b/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/style.scss deleted file mode 100644 index 2fdaad998ce951..00000000000000 --- a/packages/edit-site/src/components/sidebar-navigation-screen-templates-browse/style.scss +++ /dev/null @@ -1,6 +0,0 @@ -@use "@wordpress/base-styles/variables" as *; - -.edit-site-sidebar-navigation-screen-templates-browse { - margin-left: -$grid-unit-20; - margin-right: -$grid-unit-20; -} diff --git a/packages/edit-site/src/components/site-editor-routes/templates.jsx b/packages/edit-site/src/components/site-editor-routes/templates.jsx index a340d84888231a..1b7d8a2babbb3d 100644 --- a/packages/edit-site/src/components/site-editor-routes/templates.jsx +++ b/packages/edit-site/src/components/site-editor-routes/templates.jsx @@ -5,7 +5,6 @@ import Editor from '../editor'; import SidebarNavigationScreenTemplatesBrowse from '../sidebar-navigation-screen-templates-browse'; import SidebarNavigationScreenUnsupported from '../sidebar-navigation-screen-unsupported'; import PageTemplates from '../page-templates'; -import PageTemplatesLegacy from '../page-templates/index-legacy'; import { unlock } from '../../lock-unlock'; import { isThemeDataLoaded } from './utils'; @@ -47,13 +46,7 @@ export const templatesRoute = { if ( ! isBlockTheme ) { return undefined; } - // Use the new template activation system if experiment is enabled, - // otherwise use the legacy simple template list. - return window?.__experimentalTemplateActivate ? ( - - ) : ( - - ); + return ; }, async preview( { query, siteData } ) { const isBlockTheme = siteData.currentTheme?.is_block_theme; @@ -77,17 +70,7 @@ export const templatesRoute = { if ( ! isBlockTheme ) { return undefined; } - // Check if the template activation experiment is enabled. - const isTemplateActivateEnabled = - typeof window !== 'undefined' && - window.__experimentalTemplateActivate; - // Use the new template activation system if experiment is enabled, - // otherwise use the legacy simple template list. - return isTemplateActivateEnabled ? ( - - ) : ( - - ); + return ; }, }, widths: { diff --git a/packages/edit-site/src/style.scss b/packages/edit-site/src/style.scss index 9c557f271a1054..ba213248767619 100644 --- a/packages/edit-site/src/style.scss +++ b/packages/edit-site/src/style.scss @@ -23,7 +23,6 @@ @use "./components/sidebar-navigation-screen-patterns/style.scss" as *; @use "./components/sidebar-navigation-screen-navigation-menus/style.scss" as *; @use "./components/sidebar-navigation-screen-main/style.scss" as *; -@use "./components/sidebar-navigation-screen-templates-browse/style.scss" as *; @use "./components/sidebar-dataviews/style.scss" as *; @use "./components/site-hub/style.scss" as *; @use "./components/post-list/style.scss" as *; diff --git a/packages/editor/CHANGELOG.md b/packages/editor/CHANGELOG.md index 460f20dfd12fdf..ec300898a37322 100644 --- a/packages/editor/CHANGELOG.md +++ b/packages/editor/CHANGELOG.md @@ -11,6 +11,7 @@ ### Internal +- Remove the template activation (`active_templates`) experiment: the post-save activation notice, the "Edit template" auto-activation, and template duplication in the actions list. - Remove unused dependencies `@wordpress/reusable-blocks`, `client-zip` and `fast-deep-equal` ([#82103](https://github.com/WordPress/gutenberg/pull/82103)). - Use the `.jsx` extension for JavaScript source files that contain JSX ([#80990](https://github.com/WordPress/gutenberg/pull/80990)). diff --git a/packages/editor/src/components/post-template/block-theme.jsx b/packages/editor/src/components/post-template/block-theme.jsx index 06cf16181d06d2..08b2222eb31f06 100644 --- a/packages/editor/src/components/post-template/block-theme.jsx +++ b/packages/editor/src/components/post-template/block-theme.jsx @@ -20,17 +20,14 @@ export default function BlockThemeControl() { onNavigateToEntityRecord, getEditorSettings, hasGoBack, - hasSpecificTemplate, id, } = useSelect( ( select ) => { const { getRenderingMode, getEditorSettings: _getEditorSettings, - getCurrentPost, getCurrentTemplateId, } = unlock( select( editorStore ) ); const editorSettings = _getEditorSettings(); - const currentPost = getCurrentPost(); return { isTemplateHidden: getRenderingMode() === 'post-only', onNavigateToEntityRecord: editorSettings.onNavigateToEntityRecord, @@ -38,7 +35,6 @@ export default function BlockThemeControl() { hasGoBack: editorSettings.hasOwnProperty( 'onNavigateToPreviousEntityRecord' ), - hasSpecificTemplate: !! currentPost.template, id: getCurrentTemplateId(), }; }, [] ); @@ -50,8 +46,6 @@ export default function BlockThemeControl() { 'wp_template', id ); - const { getEntityRecord } = useSelect( coreStore ); - const { editEntityRecord } = useDispatch( coreStore ); const { createSuccessNotice } = useDispatch( noticesStore ); const { setRenderingMode, setDefaultRenderingMode } = unlock( useDispatch( editorStore ) @@ -126,48 +120,11 @@ export default function BlockThemeControl() { { canCreateTemplate && ( { + onClick={ () => { onNavigateToEntityRecord( { postId: template.id, postType: 'wp_template', } ); - // When editing a global template, - // activate the auto-draft. This is not - // immediately live (we're not saving - // site options), and when nothing is - // saved, the setting will be ignored. - // In the future, we should make the - // duplication explicit, so there - // wouldn't be an "edit" button for - // static theme templates. - if ( - ! hasSpecificTemplate && - window?.__experimentalTemplateActivate - ) { - const activeTemplates = - await getEntityRecord( - 'root', - 'site' - ).active_templates; - if ( - activeTemplates[ - template.slug - ] !== template.id - ) { - editEntityRecord( - 'root', - 'site', - undefined, - { - active_templates: { - ...activeTemplates, - [ template.slug ]: - template.id, - }, - } - ); - } - } onClose(); mayShowTemplateEditNotice(); } } diff --git a/packages/editor/src/components/provider/index.jsx b/packages/editor/src/components/provider/index.jsx index 06d8bf024d085e..3b6057b922e0de 100644 --- a/packages/editor/src/components/provider/index.jsx +++ b/packages/editor/src/components/provider/index.jsx @@ -15,7 +15,6 @@ import { BlockContextProvider, privateApis as blockEditorPrivateApis, } from '@wordpress/block-editor'; -import { store as noticesStore } from '@wordpress/notices'; import { privateApis as editPatternsPrivateApis } from '@wordpress/patterns'; import { createBlock } from '@wordpress/blocks'; import withRegistryProvider from './with-registry-provider'; @@ -333,7 +332,6 @@ export const ExperimentalEditorProvider = withRegistryProvider( }, [ editEntityRecord, post.type, post.id ] ); - const { removeNotice } = useDispatch( noticesStore ); // Ideally this should be synced on each change and not just something you do once. useLayoutEffect( () => { @@ -364,16 +362,8 @@ export const ExperimentalEditorProvider = withRegistryProvider( // Synchronizes the active post with the state useEffect( () => { setEditedPost( post.type, post.id ); - if ( - typeof window !== 'undefined' && - window.__experimentalTemplateActivate - ) { - // Clear any notices dependent on the post context. - removeNotice( 'template-activate-notice' ); - } - return () => setEditedPost( null, null ); - }, [ post.type, post.id, setEditedPost, removeNotice ] ); + }, [ post.type, post.id, setEditedPost ] ); // Opens the entity at the width it asks for. Keyed on the entity as well // as the width, so that moving to another one leaves a width set from diff --git a/packages/editor/src/dataviews/store/private-actions.ts b/packages/editor/src/dataviews/store/private-actions.ts index 91a9e76d2e54f3..123e4ddaa0010a 100644 --- a/packages/editor/src/dataviews/store/private-actions.ts +++ b/packages/editor/src/dataviews/store/private-actions.ts @@ -65,12 +65,6 @@ import { ATTACHMENT_POST_TYPE, DESIGN_POST_TYPES } from '../../store/constants'; import postPreviewField from '../fields/content-preview'; import { unlock } from '../../lock-unlock'; -declare global { - interface Window { - __experimentalTemplateActivate?: boolean; - } -} - /** * Check if a post type supports editor notes. * @@ -204,7 +198,7 @@ export const registerPostTypeSchema = .getEditorSettings(); let canDuplicate = - ! [ 'wp_block', 'wp_template_part' ].includes( + ! [ 'wp_block', 'wp_template_part', 'wp_template' ].includes( postTypeConfig.slug ) && canCreate && @@ -212,17 +206,7 @@ export const registerPostTypeSchema = // @ts-expect-error `globalThis` has no index signature for this build-time global. if ( ! globalThis.IS_GUTENBERG_PLUGIN ) { - // Outside Gutenberg, disable duplication except for wp_template. - if ( 'wp_template' !== postTypeConfig.slug ) { - canDuplicate = undefined; - } - } - - // When template activation experiment is disabled, templates cannot be duplicated. - if ( - postTypeConfig.slug === 'wp_template' && - ! window?.__experimentalTemplateActivate - ) { + // Outside Gutenberg, disable duplication. canDuplicate = undefined; } diff --git a/packages/editor/src/store/actions.js b/packages/editor/src/store/actions.js index 55912dd81aab34..042783f8b16832 100644 --- a/packages/editor/src/store/actions.js +++ b/packages/editor/src/store/actions.js @@ -19,7 +19,7 @@ import { doActionAsync, } from '@wordpress/hooks'; import { store as preferencesStore } from '@wordpress/preferences'; -import { __, sprintf } from '@wordpress/i18n'; +import { __ } from '@wordpress/i18n'; import { localAutosaveSet } from './local-autosave'; import { getNotificationArgumentsForSaveSuccess, @@ -277,17 +277,6 @@ export const savePost = } dispatch( { type: 'REQUEST_POST_UPDATE_FINISH', options } ); - if ( - typeof window !== 'undefined' && - window.__experimentalTemplateActivate && - ! options.isAutosave && - previousRecord.type === 'wp_template' && - ( typeof previousRecord.id === 'number' || - /^\d+$/.test( previousRecord.id ) ) - ) { - templateActivationNotice( { select, dispatch, registry } ); - } - if ( error ) { const args = getNotificationArgumentsForSaveFail( { post: previousRecord, @@ -347,91 +336,6 @@ export const savePost = } }; -async function templateActivationNotice( { select, registry } ) { - const editorSettings = select.getEditorSettings(); - - // Don't open for focused entity. - if ( editorSettings.onNavigateToPreviousEntityRecord ) { - return; - } - - const { id, slug } = select.getCurrentPost(); - const site = await registry - .select( coreStore ) - .getEntityRecord( 'root', 'site' ); - - // Already active. - if ( site.active_templates[ slug ] === id ) { - return; - } - - const currentTheme = await registry - .resolveSelect( coreStore ) - .getCurrentTheme(); - const templateType = currentTheme?.default_template_types.find( - ( type ) => type.slug === slug - ); - - await registry.dispatch( noticesStore ).createNotice( - 'info', - sprintf( - // translators: %s: The name (or slug) of the type of template. - __( 'Do you want to activate this "%s" template?' ), - templateType?.title ?? slug - ), - { - id: 'template-activate-notice', - actions: [ - { - label: __( 'Activate' ), - onClick: async () => { - await registry - .dispatch( noticesStore ) - .createNotice( - 'info', - __( 'Activating template…' ), - { id: 'template-activate-notice' } - ); - try { - const currentSite = await registry - .select( coreStore ) - .getEntityRecord( 'root', 'site' ); - await registry - .dispatch( coreStore ) - .saveEntityRecord( - 'root', - 'site', - { - active_templates: { - ...currentSite.active_templates, - [ slug ]: id, - }, - }, - { throwOnError: true } - ); - await registry - .dispatch( noticesStore ) - .createSuccessNotice( - __( 'Template activated.' ), - { id: 'template-activate-notice' } - ); - } catch ( error ) { - await registry - .dispatch( noticesStore ) - .createErrorNotice( - __( 'Template activation failed.' ), - { id: 'template-activate-notice' } - ); - // Rethrow for debugging. - throw error; - } - }, - }, - ], - } - ); -} - /** * Action for refreshing the current post. * diff --git a/packages/fields/CHANGELOG.md b/packages/fields/CHANGELOG.md index b096bc2fe3b78a..d7d3b5ab3be8f3 100644 --- a/packages/fields/CHANGELOG.md +++ b/packages/fields/CHANGELOG.md @@ -8,6 +8,7 @@ ### Internal +- Remove the template activation (`active_templates`) experiment checks from the rename, reset, and duplicate actions. - Remove unused dependencies `@wordpress/hooks`, `@wordpress/primitives`, `@wordpress/router`, etc. ([#82103](https://github.com/WordPress/gutenberg/pull/82103)). - Update a source reference after its JSX file moved to the `.jsx` extension ([#80990](https://github.com/WordPress/gutenberg/pull/80990)). - Remove tsconfig project references to packages that are not dependencies ([#82106](https://github.com/WordPress/gutenberg/pull/82106)). diff --git a/packages/fields/src/actions/duplicate-post.tsx b/packages/fields/src/actions/duplicate-post.tsx index 8b9eaac4901879..a06f6d59398216 100644 --- a/packages/fields/src/actions/duplicate-post.tsx +++ b/packages/fields/src/actions/duplicate-post.tsx @@ -55,12 +55,10 @@ const duplicatePost: Action< BasePost > = { return; } - const isTemplate = item.type === 'wp_template'; - const newItemObject = { - status: isTemplate ? 'publish' : 'draft', + status: 'draft', title: item.title, - slug: isTemplate ? item.slug : item.title || __( 'No title' ), + slug: item.title || __( 'No title' ), comment_status: item.comment_status, content: typeof item.content === 'string' @@ -138,13 +136,6 @@ const duplicatePost: Action< BasePost > = { return (
- { typeof item.id === 'string' && ( -
- { __( - 'You are about to duplicate a bundled template. Changes will not be live until you activate the new template.' - ) } -
- ) } = { return false; } - // Non-database template cannot be edited. - if ( - post.type === 'wp_template' && - typeof post.id === 'string' && - window?.__experimentalTemplateActivate - ) { - return false; - } - - const specialChecks = [ 'wp_template', 'wp_template_part' ]; - - if ( ! window?.__experimentalTemplateActivate ) { - specialChecks.push( 'wp_template' ); - } - // Templates, template parts and patterns have special checks for renaming. - if ( ! specialChecks.includes( post.type ) ) { + if ( ! [ 'wp_template', 'wp_template_part' ].includes( post.type ) ) { return post.permissions?.update; } // In the case of templates, we can only rename custom templates. - if ( isTemplate( post ) && ! window?.__experimentalTemplateActivate ) { + if ( isTemplate( post ) ) { return ( isTemplateRemovable( post ) && post.is_custom && diff --git a/packages/fields/src/actions/reset-post.tsx b/packages/fields/src/actions/reset-post.tsx index e65104a5ee4430..29c7b6c98f0d27 100644 --- a/packages/fields/src/actions/reset-post.tsx +++ b/packages/fields/src/actions/reset-post.tsx @@ -17,12 +17,6 @@ import apiFetch from '@wordpress/api-fetch'; import { getItemTitle, isTemplateOrTemplatePart } from './utils'; import type { CoreDataError, Template, TemplatePart } from '../types'; -declare global { - interface Window { - __experimentalTemplateActivate?: boolean; - } -} - const isTemplateRevertable = ( templateOrTemplatePart: Template | TemplatePart ) => { @@ -177,15 +171,6 @@ const resetPostAction: Action< Template | TemplatePart > = { id: 'reset-post', label: __( 'Reset' ), isEligible: ( item ) => { - if ( window?.__experimentalTemplateActivate ) { - return ( - item.type === 'wp_template_part' && - item?.source === 'custom' && - item?.has_theme_file - ); - } - - // When experiment is disabled: use wp/6.9 logic for both templates and template parts. return ( isTemplateOrTemplatePart( item ) && item?.source === 'custom' && diff --git a/phpunit/class-resolve-patterns-in-templates-active-templates-test.php b/phpunit/class-resolve-patterns-in-templates-active-templates-test.php deleted file mode 100644 index fecfc72f481e27..00000000000000 --- a/phpunit/class-resolve-patterns-in-templates-active-templates-test.php +++ /dev/null @@ -1,504 +0,0 @@ -user->create( - array( - 'role' => 'administrator', - ) - ); - } - - /** - * Set up before each test. - */ - public function set_up() { - parent::set_up(); - - // Enable the active_templates experiment. - update_option( 'active_templates', array() ); - - // Register test patterns. - register_block_pattern( - 'test/single-root', - array( - 'title' => 'Single Root Pattern', - 'content' => 'Single root content', - 'description' => 'A single root pattern.', - 'categories' => array( 'text' ), - ) - ); - - register_block_pattern( - 'test/nested-pattern', - array( - 'title' => 'Nested Pattern', - 'content' => 'Nested content', - 'description' => 'A nested pattern.', - 'categories' => array( 'featured' ), - ) - ); - - register_block_pattern( - 'test/multiple-blocks', - array( - 'title' => 'Multiple Blocks Pattern', - 'content' => 'First paragraphSecond paragraph', - 'description' => 'A pattern with multiple blocks.', - ) - ); - - // Switch to a block theme for template support. - switch_theme( 'emptytheme' ); - } - - /** - * Tear down after each test. - */ - public function tear_down() { - // Disable the active_templates experiment. - delete_option( 'active_templates' ); - - unregister_block_pattern( 'test/single-root' ); - unregister_block_pattern( 'test/nested-pattern' ); - unregister_block_pattern( 'test/multiple-blocks' ); - - // Clean up registered templates. - $templates = get_block_templates( array(), 'wp_template' ); - foreach ( $templates as $template ) { - if ( isset( $template->wp_id ) && $template->wp_id ) { - wp_delete_post( $template->wp_id, true ); - } - } - - parent::tear_down(); - } - - /** - * @doesNotPerformAssertions - */ - public function test_register_routes() { - // We are testing filters, not controller routes. - } - - /** - * @doesNotPerformAssertions - */ - public function test_context_param() { - // We are testing filters, not controller context. - } - - /** - * @doesNotPerformAssertions - */ - public function test_get_items() { - // We are testing filters, not controller get_items(). - } - - /** - * @doesNotPerformAssertions - */ - public function test_get_item() { - // We are testing filters, not controller get_item(). - } - - /** - * @doesNotPerformAssertions - */ - public function test_create_item() { - // We are testing filters, not controller create_item(). - } - - /** - * @doesNotPerformAssertions - */ - public function test_update_item() { - // We are testing filters, not controller update_item(). - } - - /** - * @doesNotPerformAssertions - */ - public function test_delete_item() { - // We are testing filters, not controller delete_item(). - } - - /** - * @doesNotPerformAssertions - */ - public function test_prepare_item() { - // We are testing filters, not controller prepare_item(). - } - - /** - * @doesNotPerformAssertions - */ - public function test_get_item_schema() { - // We are testing filters, not controller schema. - } - - /** - * Test that pattern blocks are resolved when fetching a single template via REST API with active_templates enabled. - */ - public function test_get_template_resolves_pattern_blocks() { - wp_set_current_user( self::$admin_id ); - $this->assertTrue( gutenberg_is_experiment_enabled( 'active_templates' ), 'The active_templates experiment should be enabled.' ); - - // Register a template with a pattern block. - $template_name = 'test-plugin//test-template-with-pattern'; - register_block_template( - $template_name, - array( - 'title' => 'Test Template With Pattern', - 'content' => 'Before patternAfter pattern', - ) - ); - - // Get template via REST API (use theme slug format for registered templates). - $current_theme = get_stylesheet(); - $request = new WP_REST_Request( 'GET', '/wp/v2/templates/' . $current_theme . '//test-template-with-pattern' ); - $response = rest_get_server()->dispatch( $request ); - $data = $response->get_data(); - - $this->assertSame( 200, $response->get_status() ); - $this->assertArrayHasKey( 'content', $data ); - - // Verify pattern block is resolved. - $blocks = parse_blocks( $data['content']['raw'] ); - $this->assertNotEmpty( $blocks ); - $this->assertGreaterThanOrEqual( 3, count( $blocks ), 'Template should have at least 3 blocks after pattern resolution.' ); - - // Block structure after resolution: - // blocks[0] = "Before pattern" paragraph - // blocks[1] = Resolved pattern content (single paragraph with metadata) - // blocks[2] = "After pattern" paragraph - - // Verify the resolved pattern block (should be at index 1). - $resolved_block = $blocks[1]; - $this->assertSame( 'core/paragraph', $resolved_block['blockName'], 'Resolved pattern should be a paragraph block.' ); - $this->assertStringContainsString( 'Single root content', $resolved_block['innerHTML'] ?? '', 'Resolved pattern should contain expected content.' ); - - // Verify metadata is present on single-root pattern. - $this->assertArrayHasKey( 'metadata', $resolved_block['attrs'], 'Resolved pattern block should have metadata.' ); - $metadata = $resolved_block['attrs']['metadata']; - $this->assertSame( 'test/single-root', $metadata['patternName'], 'Pattern name should match.' ); - $this->assertArrayHasKey( 'name', $metadata, 'Pattern name should be in metadata.' ); - $this->assertArrayHasKey( 'description', $metadata, 'Pattern description should be in metadata.' ); - $this->assertArrayHasKey( 'categories', $metadata, 'Pattern categories should be in metadata.' ); - $this->assertSame( 'Single Root Pattern', $metadata['name'], 'Pattern name should match.' ); - $this->assertSame( 'A single root pattern.', $metadata['description'], 'Pattern description should match.' ); - $this->assertSame( array( 'text' ), $metadata['categories'], 'Pattern categories should match.' ); - - // Verify no pattern blocks remain. - foreach ( $blocks as $block ) { - $this->assertNotSame( 'core/pattern', $block['blockName'], 'Pattern block should be resolved and not present in the content.' ); - } - - unregister_block_template( $template_name ); - } - - /** - * Test that pattern blocks are resolved when fetching multiple templates via REST API with active_templates enabled. - */ - public function test_get_templates_resolves_pattern_blocks() { - wp_set_current_user( self::$admin_id ); - $this->assertTrue( gutenberg_is_experiment_enabled( 'active_templates' ), 'The active_templates experiment should be enabled.' ); - - // Register templates with pattern blocks. - $template_name_1 = 'test-plugin//test-template-1'; - register_block_template( - $template_name_1, - array( - 'title' => 'Test Template 1', - 'content' => '', - ) - ); - - $template_name_2 = 'test-plugin//test-template-2'; - register_block_template( - $template_name_2, - array( - 'title' => 'Test Template 2', - 'content' => '', - ) - ); - - // Get templates via REST API. - $request = new WP_REST_Request( 'GET', '/wp/v2/templates' ); - $response = rest_get_server()->dispatch( $request ); - $data = $response->get_data(); - - $this->assertSame( 200, $response->get_status() ); - $this->assertIsArray( $data ); - - // Find our test templates by slug (REST API may normalize IDs to theme slug format). - $template_1 = null; - $template_2 = null; - foreach ( $data as $template ) { - if ( isset( $template['slug'] ) && 'test-template-1' === $template['slug'] ) { - $template_1 = $template; - } - if ( isset( $template['slug'] ) && 'test-template-2' === $template['slug'] ) { - $template_2 = $template; - } - } - - $this->assertNotNull( $template_1, 'Template 1 should be found. Available template IDs: ' . implode( ', ', wp_list_pluck( $data, 'id' ) ) ); - $this->assertNotNull( $template_2, 'Template 2 should be found. Available template IDs: ' . implode( ', ', wp_list_pluck( $data, 'id' ) ) ); - - // Verify pattern blocks are resolved in template 1. - $blocks = parse_blocks( $template_1['content']['raw'] ); - $this->assertNotEmpty( $blocks, 'Template 1 should have at least one block after pattern resolution.' ); - - // Block structure after resolution: - // blocks[0] = Resolved pattern content (single paragraph with metadata) - - // Verify the resolved pattern block (should be at index 0). - $resolved_block = $blocks[0]; - $this->assertSame( 'core/paragraph', $resolved_block['blockName'], 'Resolved pattern should be a paragraph block.' ); - - // Verify metadata is present on single-root pattern. - $this->assertArrayHasKey( 'metadata', $resolved_block['attrs'], 'Resolved pattern block should have metadata.' ); - $metadata = $resolved_block['attrs']['metadata']; - $this->assertSame( 'test/single-root', $metadata['patternName'], 'Pattern name should match.' ); - $this->assertArrayHasKey( 'name', $metadata, 'Pattern name should be in metadata.' ); - $this->assertArrayHasKey( 'description', $metadata, 'Pattern description should be in metadata.' ); - $this->assertArrayHasKey( 'categories', $metadata, 'Pattern categories should be in metadata.' ); - - // Verify no pattern blocks remain. - foreach ( $blocks as $block ) { - $this->assertNotSame( 'core/pattern', $block['blockName'], 'Pattern block should be resolved in template 1.' ); - } - - // Verify pattern blocks are resolved in template 2. - $blocks = parse_blocks( $template_2['content']['raw'] ); - $has_pattern_block = false; - $paragraph_count = 0; - foreach ( $blocks as $block ) { - if ( 'core/pattern' === $block['blockName'] ) { - $has_pattern_block = true; - } - if ( 'core/paragraph' === $block['blockName'] ) { - ++$paragraph_count; - } - } - $this->assertFalse( $has_pattern_block, 'Pattern block should be resolved in template 2.' ); - $this->assertGreaterThanOrEqual( 2, $paragraph_count, 'Template 2 should have resolved pattern content with multiple blocks.' ); - - unregister_block_template( $template_name_1 ); - unregister_block_template( $template_name_2 ); - } - - /** - * Test that pattern blocks are resolved when fetching a single template part via REST API with active_templates enabled. - */ - public function test_get_template_part_resolves_pattern_blocks() { - wp_set_current_user( self::$admin_id ); - $this->assertTrue( gutenberg_is_experiment_enabled( 'active_templates' ), 'The active_templates experiment should be enabled.' ); - - // Create a template part with a pattern block as a post. - $current_theme = get_stylesheet(); - - $template_part_id = wp_insert_post( - array( - 'post_type' => 'wp_template_part', - 'post_status' => 'publish', - 'post_title' => 'Test Template Part With Pattern', - 'post_name' => 'test-template-part-with-pattern', - 'post_content' => 'Before patternAfter pattern', - 'post_author' => self::$admin_id, - ), - true - ); - $this->assertNotWPError( $template_part_id ); - - // Set the theme taxonomy term. - wp_set_post_terms( $template_part_id, array( $current_theme ), 'wp_theme' ); - - // Set the area taxonomy term. - wp_set_post_terms( $template_part_id, array( 'uncategorized' ), 'wp_template_part_area' ); - - $template_part_name = $current_theme . '//test-template-part-with-pattern'; - - // Get template part via REST API. - $request = new WP_REST_Request( 'GET', '/wp/v2/template-parts/' . $template_part_name ); - $response = rest_get_server()->dispatch( $request ); - $data = $response->get_data(); - - // Clean up template part. - wp_delete_post( $template_part_id, true ); - - $this->assertSame( 200, $response->get_status() ); - $this->assertArrayHasKey( 'content', $data ); - - // Verify pattern block is resolved. - $blocks = parse_blocks( $data['content']['raw'] ); - $this->assertNotEmpty( $blocks ); - $this->assertGreaterThanOrEqual( 3, count( $blocks ), 'Template part should have at least 3 blocks after pattern resolution.' ); - - // Block structure after resolution: - // blocks[0] = "Before pattern" paragraph - // blocks[1] = Resolved pattern content (single paragraph with metadata) - // blocks[2] = "After pattern" paragraph - - // Verify the resolved pattern block (should be at index 1). - $resolved_block = $blocks[1]; - $this->assertSame( 'core/paragraph', $resolved_block['blockName'], 'Resolved pattern should be a paragraph block.' ); - $this->assertStringContainsString( 'Single root content', $resolved_block['innerHTML'] ?? '', 'Resolved pattern should contain expected content.' ); - - // Verify metadata is present on single-root pattern. - $this->assertArrayHasKey( 'metadata', $resolved_block['attrs'], 'Resolved pattern block should have metadata.' ); - $metadata = $resolved_block['attrs']['metadata']; - $this->assertSame( 'test/single-root', $metadata['patternName'], 'Pattern name should match.' ); - $this->assertArrayHasKey( 'name', $metadata, 'Pattern name should be in metadata.' ); - $this->assertArrayHasKey( 'description', $metadata, 'Pattern description should be in metadata.' ); - $this->assertArrayHasKey( 'categories', $metadata, 'Pattern categories should be in metadata.' ); - $this->assertSame( 'Single Root Pattern', $metadata['name'], 'Pattern name should match.' ); - $this->assertSame( 'A single root pattern.', $metadata['description'], 'Pattern description should match.' ); - $this->assertSame( array( 'text' ), $metadata['categories'], 'Pattern categories should match.' ); - - // Verify no pattern blocks remain. - foreach ( $blocks as $block ) { - $this->assertNotSame( 'core/pattern', $block['blockName'], 'Pattern block should be resolved and not present in the content.' ); - } - } - - /** - * Test that pattern blocks are resolved when fetching multiple template parts via REST API with active_templates enabled. - */ - public function test_get_template_parts_resolves_pattern_blocks() { - wp_set_current_user( self::$admin_id ); - $this->assertTrue( gutenberg_is_experiment_enabled( 'active_templates' ), 'The active_templates experiment should be enabled.' ); - - // Create template parts with pattern blocks as posts. - $current_theme = get_stylesheet(); - - $template_part_id_1 = wp_insert_post( - array( - 'post_type' => 'wp_template_part', - 'post_status' => 'publish', - 'post_title' => 'Test Template Part 1', - 'post_name' => 'test-template-part-1', - 'post_content' => '', - 'post_author' => self::$admin_id, - ), - true - ); - $this->assertNotWPError( $template_part_id_1 ); - - // Set the theme taxonomy term. - wp_set_post_terms( $template_part_id_1, array( $current_theme ), 'wp_theme' ); - - // Set the area taxonomy term. - wp_set_post_terms( $template_part_id_1, array( 'uncategorized' ), 'wp_template_part_area' ); - - $template_part_id_2 = wp_insert_post( - array( - 'post_type' => 'wp_template_part', - 'post_status' => 'publish', - 'post_title' => 'Test Template Part 2', - 'post_name' => 'test-template-part-2', - 'post_content' => '', - 'post_author' => self::$admin_id, - ), - true - ); - $this->assertNotWPError( $template_part_id_2 ); - - // Set the theme taxonomy term. - wp_set_post_terms( $template_part_id_2, array( $current_theme ), 'wp_theme' ); - - // Set the area taxonomy term. - wp_set_post_terms( $template_part_id_2, array( 'uncategorized' ), 'wp_template_part_area' ); - - $template_part_name_1 = $current_theme . '//test-template-part-1'; - $template_part_name_2 = $current_theme . '//test-template-part-2'; - - // Get template parts via REST API. - $request = new WP_REST_Request( 'GET', '/wp/v2/template-parts' ); - $response = rest_get_server()->dispatch( $request ); - $data = $response->get_data(); - - // Clean up template parts. - wp_delete_post( $template_part_id_1, true ); - wp_delete_post( $template_part_id_2, true ); - - $this->assertSame( 200, $response->get_status() ); - $this->assertIsArray( $data ); - - // Find our test template parts by ID or slug (REST API may normalize IDs to theme slug format). - $template_part_1 = null; - $template_part_2 = null; - foreach ( $data as $template_part ) { - $id = $template_part['id'] ?? ''; - $slug = $template_part['slug'] ?? ''; - if ( $template_part_name_1 === $id || 'test-template-part-1' === $slug ) { - $template_part_1 = $template_part; - } - if ( $template_part_name_2 === $id || 'test-template-part-2' === $slug ) { - $template_part_2 = $template_part; - } - } - - $this->assertNotNull( $template_part_1, 'Template part 1 should be found. Available template part IDs: ' . implode( ', ', wp_list_pluck( $data, 'id' ) ) ); - $this->assertNotNull( $template_part_2, 'Template part 2 should be found. Available template part IDs: ' . implode( ', ', wp_list_pluck( $data, 'id' ) ) ); - - // Verify pattern blocks are resolved in template part 1. - $blocks = parse_blocks( $template_part_1['content']['raw'] ); - $this->assertNotEmpty( $blocks, 'Template part 1 should have at least one block after pattern resolution.' ); - - // Block structure after resolution: - // blocks[0] = Resolved pattern content (single paragraph with metadata) - - // Verify the resolved pattern block (should be at index 0). - $resolved_block = $blocks[0]; - $this->assertSame( 'core/paragraph', $resolved_block['blockName'], 'Resolved pattern should be a paragraph block.' ); - - // Verify metadata is present on single-root pattern. - $this->assertArrayHasKey( 'metadata', $resolved_block['attrs'], 'Resolved pattern block should have metadata.' ); - $metadata = $resolved_block['attrs']['metadata']; - $this->assertSame( 'test/single-root', $metadata['patternName'], 'Pattern name should match.' ); - $this->assertArrayHasKey( 'name', $metadata, 'Pattern name should be in metadata.' ); - $this->assertArrayHasKey( 'description', $metadata, 'Pattern description should be in metadata.' ); - $this->assertArrayHasKey( 'categories', $metadata, 'Pattern categories should be in metadata.' ); - - // Verify no pattern blocks remain. - foreach ( $blocks as $block ) { - $this->assertNotSame( 'core/pattern', $block['blockName'], 'Pattern block should be resolved in template part 1.' ); - } - - // Verify pattern blocks are resolved in template part 2. - $blocks = parse_blocks( $template_part_2['content']['raw'] ); - $has_pattern_block = false; - $paragraph_count = 0; - foreach ( $blocks as $block ) { - if ( 'core/pattern' === $block['blockName'] ) { - $has_pattern_block = true; - } - if ( 'core/paragraph' === $block['blockName'] ) { - ++$paragraph_count; - } - } - $this->assertFalse( $has_pattern_block, 'Pattern block should be resolved in template part 2.' ); - $this->assertGreaterThanOrEqual( 2, $paragraph_count, 'Template part 2 should have resolved pattern content with multiple blocks.' ); - } -} diff --git a/routes/experiments-home/api.ts b/routes/experiments-home/api.ts index a07cfee54e9412..638e92552b3fb6 100644 --- a/routes/experiments-home/api.ts +++ b/routes/experiments-home/api.ts @@ -19,8 +19,6 @@ interface SettingsSchema { description?: string; group?: string; group_label?: string; - separate_option?: boolean; - option_name?: string; } >; }; diff --git a/routes/experiments-home/stage.tsx b/routes/experiments-home/stage.tsx index acc14ddb1e4001..54621380275c60 100644 --- a/routes/experiments-home/stage.tsx +++ b/routes/experiments-home/stage.tsx @@ -52,14 +52,8 @@ function ExperimentsPage() { combined[ key ] = Boolean( value ); } - // `active_templates` lives in its own top-level WP option. - // An object value means enabled. - const activeTemplates = siteSettings?.active_templates; - combined.active_templates = - typeof activeTemplates === 'object' && activeTemplates !== null; - return combined; - }, [ experiments, gutenbergExperiments, siteSettings ] ); + }, [ experiments, gutenbergExperiments ] ); const setSettings = async ( values: Record< string, boolean > ) => { const [ changedId ] = Object.keys( values ); @@ -67,20 +61,12 @@ function ExperimentsPage() { ( exp ) => exp.id === changedId ); - const editPayload: Record< string, unknown > = {}; - - // `active_templates` lives in its own top-level WP option. - if ( 'active_templates' in values ) { - editPayload.active_templates = values.active_templates ? {} : null; - delete values.active_templates; - } - - if ( Object.keys( values ).length > 0 ) { - editPayload[ 'gutenberg-experiments' ] = { + const editPayload: Record< string, unknown > = { + 'gutenberg-experiments': { ...gutenbergExperiments, ...values, - }; - } + }, + }; const groupLabel = changedExperiment?.groupLabel ?? ''; edit( editPayload ); diff --git a/routes/template-list/actions/set-active-template.tsx b/routes/template-list/actions/set-active-template.tsx deleted file mode 100644 index 382f0af1b3b29c..00000000000000 --- a/routes/template-list/actions/set-active-template.tsx +++ /dev/null @@ -1,90 +0,0 @@ -import { __ } from '@wordpress/i18n'; -import { pencil } from '@wordpress/icons'; -import { useMemo } from '@wordpress/element'; -import { useDispatch, useSelect } from '@wordpress/data'; -import { store as coreStore } from '@wordpress/core-data'; -import type { Action } from '@wordpress/dataviews'; -import type { Template } from '../types'; - -/** - * Hook to create the "Set Active Template" action. - * This action allows users to activate or deactivate templates. - * - * @return {Action