From 484e609c5be53b071023828dbee1a08e58721ea0 Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Wed, 20 Oct 2021 12:16:06 +0100 Subject: [PATCH 01/15] Start a Global Styles endpoint and use it in the site editor --- ...utenberg-rest-global-styles-controller.php | 365 ++++++++++++++++++ lib/load.php | 1 + lib/rest-api.php | 9 + packages/core-data/src/entities.js | 6 + .../global-styles/global-styles-provider.js | 72 ++-- 5 files changed, 407 insertions(+), 46 deletions(-) create mode 100644 lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php diff --git a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php new file mode 100644 index 00000000000000..80290daab8c1dc --- /dev/null +++ b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php @@ -0,0 +1,365 @@ +namespace = 'wp/v2'; + $this->rest_base = 'global-styles'; + } + + /** + * Registers the controllers routes. + * + * @return void + */ + 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 gloval style variation based on the given id. + register_rest_route( + $this->namespace, + '/' . $this->rest_base . '/(?P[\/\w-]+)', + array( + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => array( $this, 'get_item' ), + 'permission_callback' => array( $this, 'get_item_permissions_check' ), + 'args' => array( + 'id' => array( + 'description' => __( 'The id of a template', 'gutenberg' ), + 'type' => 'string', + ), + ), + ), + array( + 'methods' => WP_REST_Server::EDITABLE, + 'callback' => array( $this, 'update_item' ), + 'permission_callback' => array( $this, 'update_item_permissions_check' ), + 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ), + ), + 'schema' => array( $this, 'get_public_item_schema' ), + ) + ); + } + + /** + * Checks if the user has permissions to make the request. + * + * @return true|WP_Error True if the request has read access, WP_Error object otherwise. + */ + protected function permissions_check() { + // Verify if the current user has edit_theme_options capability. + // This capability is required to edit/view/delete templates. + if ( ! current_user_can( 'edit_theme_options' ) ) { + return new WP_Error( + 'rest_cannot_manage_global_styles', + __( 'Sorry, you are not allowed to access the global styles on this site.', 'gutenberg' ), + array( + 'status' => rest_authorization_required_code(), + ) + ); + } + + return true; + } + + /** + * Checks if a given request has access to read global styles configs. + * + * @param WP_REST_Request $request Full details about the request. + * @return true|WP_Error True if the request has read access, WP_Error object otherwise. + */ + public function get_items_permissions_check( $request ) { + return $this->permissions_check( $request ); + } + + /** + * Returns a list of available global styles variations. + * + * @param WP_REST_Request $request The request instance. + * + * @return WP_REST_Response + */ + public function get_items( $request ) { + $wp_query_args = array( + 'post_status' => array( 'publish' ), + 'post_type' => 'wp_global_styles', + 'posts_per_page' => -1, + 'no_found_rows' => true, + ); + + $query = new WP_Query( $wp_query_args ); + $results = array(); + foreach ( $query->posts as $post ) { + $data = $this->prepare_item_for_response( $post, $request ); + $results[] = $this->prepare_response_for_collection( $data ); + } + + return rest_ensure_response( $results ); + } + + /** + * Checks if a given request has access to read a single global styles config. + * + * @param WP_REST_Request $request Full details about the request. + * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise. + */ + public function get_item_permissions_check( $request ) { + return $this->permissions_check( $request ); + } + + /** + * Returns the given global styles config. + * + * @param WP_REST_Request $request The request instance. + * + * @return WP_REST_Response|WP_Error + */ + public function get_item( $request ) { + $post = get_post( $request['id'] ); + if ( ! $post || 'wp_global_styles' !== $post->post_type ) { + return new WP_Error( 'rest_global_styles_not_found', __( 'No global styles config exist with that id.', 'gutenberg' ), array( 'status' => 404 ) ); + } + + return $this->prepare_item_for_response( $post, $request ); + } + + /** + * Checks if a given request has access to write a single global styles config. + * + * @param WP_REST_Request $request Full details about the request. + * @return true|WP_Error True if the request has write access for the item, WP_Error object otherwise. + */ + public function update_item_permissions_check( $request ) { + return $this->permissions_check( $request ); + } + + /** + * Updates a single global style config. + * + * @param WP_REST_Request $request Full details about the request. + * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. + */ + public function update_item( $request ) { + $post = get_post( $request['id'] ); + if ( ! $post || 'wp_global_styles' !== $post->post_type ) { + return new WP_Error( 'rest_global_styles_not_found', __( 'No global styles config exist with that id.', 'gutenberg' ), array( 'status' => 404 ) ); + } + + $changes = $this->prepare_item_for_database( $request ); + $result = wp_update_post( wp_slash( (array) $changes ), true ); + if ( is_wp_error( $result ) ) { + return $result; + } + + $post = get_post( $request['id'] ); + $fields_update = $this->update_additional_fields_for_object( $post, $request ); + if ( is_wp_error( $fields_update ) ) { + return $fields_update; + } + + return $this->prepare_item_for_response( + get_post( $request['id'] ), + $request + ); + } + + /** + * Prepares a single global styles config for update. + * + * @param WP_REST_Request $request Request object. + * @return stdClass Changes to pass to wp_update_post. + */ + protected function prepare_item_for_database( $request ) { + $changes = new stdClass(); + $changes->ID = $request['id']; + + $post = get_post( $request['id'] ); + $existing_config = $post ? json_decode( $post->post_content, true ) : array( + 'settings' => array(), + 'styles' => array(), + ); + + if ( isset( $request['styles'] ) || isset( $request['settings'] ) ) { + $config = array(); + if ( isset( $request['styles'] ) ) { + $config['styles'] = $request['styles']; + } else { + $config['styles'] = $existing_config['styles']; + } + if ( isset( $request['settings'] ) ) { + $config['settings'] = $request['settings']; + } else { + $config['settings'] = $existing_config['settings']; + } + + $changes->post_content = wp_json_encode( $config ); + } + + if ( isset( $request['title'] ) ) { + $changes->post_title = $request['title']; + } + + return $changes; + } + + /** + * Prepare a global styles config output for response. + * + * @param WP_Post $post Global Styles post object. + * @param WP_REST_Request $request Request object. + * + * @return WP_REST_Response $data + */ + public function prepare_item_for_response( $post, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable + $config = json_decode( $post->post_content, true ); + $result = array( + 'id' => $post->ID, + 'settings' => isset( $config['settings'] ) ? $config['settings'] : new stdClass(), + 'styles' => isset( $config['styles'] ) ? $config['styles'] : new stdClass(), + 'title' => array( + 'raw' => $post->title, + 'rendered' => $post->title, + ), + ); + + $result = $this->add_additional_fields_to_object( $result, $request ); + $response = rest_ensure_response( $result ); + $links = $this->prepare_links( $post->id ); + $response->add_links( $links ); + if ( ! empty( $links['self']['href'] ) ) { + $actions = $this->get_available_actions(); + $self = $links['self']['href']; + foreach ( $actions as $rel ) { + $response->add_link( $rel, $self ); + } + } + + return $response; + } + + + /** + * Prepares links for the request. + * + * @param integer $id ID. + * @return array Links for the given post. + */ + protected function prepare_links( $id ) { + $base = sprintf( '%s/%s', $this->namespace, $this->rest_base ); + + $links = array( + 'self' => array( + 'href' => rest_url( trailingslashit( $base ) . $id ), + ), + 'collection' => array( + 'href' => rest_url( $base ), + ), + ); + + return $links; + } + + /** + * Get the link relations available for the post and current user. + * + * @return array List of link relations. + */ + protected function get_available_actions() { + $rels = array(); + + $post_type = get_post_type_object( 'wp_global_styles' ); + if ( current_user_can( $post_type->cap->publish_posts ) ) { + $rels[] = 'https://api.w.org/action-publish'; + } + + return $rels; + } + + /** + * Retrieves the query params for the global styles collection. + * + * @return array Collection parameters. + */ + public function get_collection_params() { + return array(); + } + + /** + * Retrieves the global styles type' schema, conforming to JSON Schema. + * + * @return array Item schema data. + */ + public function get_item_schema() { + if ( $this->schema ) { + return $this->add_additional_fields_schema( $this->schema ); + } + + $schema = array( + '$schema' => 'http://json-schema.org/draft-04/schema#', + 'title' => 'wp_global_styles', + 'type' => 'object', + 'properties' => array( + 'id' => array( + 'description' => __( 'ID of global styles config.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'embed', 'view', 'edit' ), + 'readonly' => true, + ), + 'styles' => array( + 'description' => __( 'Global styles.', 'gutenberg' ), + 'type' => array( 'object' ), + 'default' => '', + 'context' => array( 'embed', 'view', 'edit' ), + ), + 'settings' => array( + 'description' => __( 'Global settings.', 'gutenberg' ), + 'type' => array( 'object' ), + 'default' => '', + 'context' => array( 'embed', 'view', 'edit' ), + ), + 'title' => array( + 'description' => __( 'Title of the global styles variation.', 'gutenberg' ), + 'type' => array( 'object', 'string' ), + 'default' => '', + 'context' => array( 'embed', 'view', 'edit' ), + ), + ), + ); + + $this->schema = $schema; + + return $this->add_additional_fields_schema( $this->schema ); + } +} diff --git a/lib/load.php b/lib/load.php index 14dac73e96e6f3..68d6d23f51cb86 100644 --- a/lib/load.php +++ b/lib/load.php @@ -109,6 +109,7 @@ function gutenberg_is_experiment_enabled( $name ) { require __DIR__ . '/full-site-editing/edit-site-page.php'; require __DIR__ . '/full-site-editing/edit-site-export.php'; require __DIR__ . '/compat/wordpress-5.9/default-theme-supports.php'; +require __DIR__ . '/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php'; require __DIR__ . '/blocks.php'; require __DIR__ . '/block-patterns.php'; diff --git a/lib/rest-api.php b/lib/rest-api.php index aa74c373f8b5b1..4829b6367711d8 100644 --- a/lib/rest-api.php +++ b/lib/rest-api.php @@ -224,3 +224,12 @@ function gutenberg_rest_user_collection_params_has_published_posts( $query_param return $query_params; } add_filter( 'rest_user_collection_params', 'gutenberg_rest_user_collection_params_has_published_posts' ); + +/** + * Registers the Global Styles REST API routes. + */ +function gutenberg_register_global_styles_endpoints() { + $editor_settings = new Gutenberg_REST_Global_Styles_Controller(); + $editor_settings->register_routes(); +} +add_action( 'rest_api_init', 'gutenberg_register_global_styles_endpoints' ); diff --git a/packages/core-data/src/entities.js b/packages/core-data/src/entities.js index 03fafbe099bcc4..d4bbe90a914d47 100644 --- a/packages/core-data/src/entities.js +++ b/packages/core-data/src/entities.js @@ -127,6 +127,12 @@ export const defaultEntities = [ label: __( 'Menu Location' ), key: 'name', }, + { + label: __( 'Global Styles' ), + name: 'globalStyles', + kind: 'root', + baseURL: '/wp/v2/global-styles', + }, ]; export const kinds = [ diff --git a/packages/edit-site/src/components/global-styles/global-styles-provider.js b/packages/edit-site/src/components/global-styles/global-styles-provider.js index f83e0804167e61..724fd4e4408005 100644 --- a/packages/edit-site/src/components/global-styles/global-styles-provider.js +++ b/packages/edit-site/src/components/global-styles/global-styles-provider.js @@ -55,67 +55,47 @@ function removeUserOriginFromSettings( settingsToRemove ) { } function useGlobalStylesUserConfig() { - const { globalStylesId, content } = useSelect( ( select ) => { + const { globalStylesId, settings, styles } = useSelect( ( select ) => { const _globalStylesId = select( editSiteStore ).getSettings() .__experimentalGlobalStylesUserEntityId; + const record = select( coreStore ).getEditedEntityRecord( + 'root', + 'globalStyles', + _globalStylesId + ); return { globalStylesId: _globalStylesId, - content: select( coreStore ).getEditedEntityRecord( - 'postType', - 'wp_global_styles', - _globalStylesId - )?.content, + settings: record?.settings, + styles: record?.styles, }; }, [] ); const { getEditedEntityRecord } = useSelect( coreStore ); const { editEntityRecord } = useDispatch( coreStore ); - const parseContent = ( contentToParse ) => { - let parsedConfig; - try { - parsedConfig = contentToParse ? JSON.parse( contentToParse ) : {}; - // It is very important to verify if the flag isGlobalStylesUserThemeJSON is true. - // If it is not true the content was not escaped and is not safe. - if ( ! parsedConfig.isGlobalStylesUserThemeJSON ) { - parsedConfig = {}; - } else { - parsedConfig = { - ...parsedConfig, - settings: addUserOriginToSettings( parsedConfig.settings ), - }; - } - } catch ( e ) { - /* eslint-disable no-console */ - console.error( 'Global Styles User data is not valid' ); - console.error( e ); - /* eslint-enable no-console */ - parsedConfig = {}; - } - - return parsedConfig; - }; - const config = useMemo( () => { - return parseContent( content ); - }, [ content ] ); + return { + settings: addUserOriginToSettings( settings ?? {} ), + styles: styles ?? {}, + }; + }, [ settings, styles ] ); const setConfig = useCallback( ( callback ) => { - const currentConfig = parseContent( - getEditedEntityRecord( - 'postType', - 'wp_global_styles', - globalStylesId - )?.content + const record = getEditedEntityRecord( + 'root', + 'globalStyles', + globalStylesId ); + const currentConfig = { + styles: record?.styles ?? {}, + settings: addUserOriginToSettings( record?.settings ?? {} ), + }; const updatedConfig = callback( currentConfig ); - editEntityRecord( 'postType', 'wp_global_styles', globalStylesId, { - content: JSON.stringify( { - ...updatedConfig, - settings: removeUserOriginFromSettings( - updatedConfig.settings - ), - } ), + editEntityRecord( 'root', 'globalStyles', globalStylesId, { + styles: updatedConfig.styles, + settings: removeUserOriginFromSettings( + updatedConfig.settings + ), } ); }, [ globalStylesId ] From 369183ed9fcc60d2872eafce30415fb19cfcb117 Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Thu, 21 Oct 2021 10:29:44 +0100 Subject: [PATCH 02/15] Add the active global styles ID to the themes endpoint --- ...-rest-block-editor-settings-controller.php | 6 --- .../rest-active-global-styles.php | 39 +++++++++++++++++++ lib/global-styles.php | 1 - lib/load.php | 1 + packages/core-data/src/actions.js | 16 ++++++++ packages/core-data/src/reducer.js | 18 +++++++++ packages/core-data/src/resolvers.js | 23 +++++++++++ packages/core-data/src/selectors.js | 11 ++++++ .../global-styles/global-styles-provider.js | 17 ++++---- .../provider/use-block-editor-settings.js | 1 - 10 files changed, 118 insertions(+), 15 deletions(-) create mode 100644 lib/compat/wordpress-5.9/rest-active-global-styles.php diff --git a/lib/class-wp-rest-block-editor-settings-controller.php b/lib/class-wp-rest-block-editor-settings-controller.php index 8207d1b6bacbc6..717e2e7e56270a 100644 --- a/lib/class-wp-rest-block-editor-settings-controller.php +++ b/lib/class-wp-rest-block-editor-settings-controller.php @@ -134,12 +134,6 @@ public function get_item_schema() { 'context' => array( 'post-editor', 'site-editor', 'widgets-editor', 'mobile' ), ), - '__experimentalGlobalStylesUserEntityId' => array( - 'description' => __( 'Global styles user entity ID.', 'gutenberg' ), - 'type' => 'integer', - 'context' => array( 'site-editor' ), - ), - '__experimentalGlobalStylesBaseConfig' => array( 'description' => __( 'Settings and styles consolidated from core and theme origins.', 'gutenberg' ), 'type' => 'object', diff --git a/lib/compat/wordpress-5.9/rest-active-global-styles.php b/lib/compat/wordpress-5.9/rest-active-global-styles.php new file mode 100644 index 00000000000000..b9e70b848808de --- /dev/null +++ b/lib/compat/wordpress-5.9/rest-active-global-styles.php @@ -0,0 +1,39 @@ + array( 'publish' ), + 'post_type' => 'wp_global_styles', + 'posts_per_page' => 1, + 'no_found_rows' => true, + 'tax_query' => array( + array( + 'taxonomy' => 'wp_theme', + 'field' => 'name', + 'terms' => $theme->get_stylesheet(), + ), + ), + ); + $global_styles_query = new WP_Query( $wp_query_args ); + if ( count( $global_styles_query->posts ) ) { + $response->add_link( + 'global-styles', + get_rest_url( null, 'wp/v2/global-styles/' . $global_styles_query->posts[0]->ID ) + ); + } + + return $response; +} + +add_filter( 'rest_prepare_theme', 'gutenberg_add_active_global_styles_link', 10, 2 ); diff --git a/lib/global-styles.php b/lib/global-styles.php index e33f79bb758b8a..877c9cb326cfa2 100644 --- a/lib/global-styles.php +++ b/lib/global-styles.php @@ -125,7 +125,6 @@ function_exists( 'gutenberg_is_edit_site_page' ) && $theme = WP_Theme_JSON_Resolver_Gutenberg::get_merged_data( $settings, 'theme' ); $user_cpt_id = WP_Theme_JSON_Resolver_Gutenberg::get_user_custom_post_type_id(); - $settings['__experimentalGlobalStylesUserEntityId'] = $user_cpt_id; $settings['__experimentalGlobalStylesBaseConfig']['styles'] = $theme->get_raw_data()['styles']; $settings['__experimentalGlobalStylesBaseConfig']['settings'] = $theme->get_settings(); } diff --git a/lib/load.php b/lib/load.php index 68d6d23f51cb86..511ac6f1568f79 100644 --- a/lib/load.php +++ b/lib/load.php @@ -110,6 +110,7 @@ function gutenberg_is_experiment_enabled( $name ) { require __DIR__ . '/full-site-editing/edit-site-export.php'; require __DIR__ . '/compat/wordpress-5.9/default-theme-supports.php'; require __DIR__ . '/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php'; +require __DIR__ . '/compat/wordpress-5.9/rest-active-global-styles.php'; require __DIR__ . '/blocks.php'; require __DIR__ . '/block-patterns.php'; diff --git a/packages/core-data/src/actions.js b/packages/core-data/src/actions.js index ba70a25395a0f0..0b184f8fec4e7f 100644 --- a/packages/core-data/src/actions.js +++ b/packages/core-data/src/actions.js @@ -117,6 +117,22 @@ export function receiveCurrentTheme( currentTheme ) { }; } +/** + * Returns an action object used in signalling that the current global styles id has been received. + * + * @param {string} currentGlobalStylesId The current global styles id. + * + * @return {Object} Action object. + */ +export function __experimentalReceiveCurrentGlobalStylesId( + currentGlobalStylesId +) { + return { + type: 'RECEIVE_CURRENT_GLOBAL_STYLES_ID', + id: currentGlobalStylesId, + }; +} + /** * Returns an action object used in signalling that the index has been received. * diff --git a/packages/core-data/src/reducer.js b/packages/core-data/src/reducer.js index f78e6fd76eff9d..8404b59a5a59cd 100644 --- a/packages/core-data/src/reducer.js +++ b/packages/core-data/src/reducer.js @@ -119,6 +119,23 @@ export function currentTheme( state = undefined, action ) { return state; } +/** + * Reducer managing the current global styles id. + * + * @param {string} state Current state. + * @param {Object} action Dispatched action. + * + * @return {string} Updated state. + */ +export function currentGlobalStylesId( state = undefined, action ) { + switch ( action.type ) { + case 'RECEIVE_CURRENT_GLOBAL_STYLES_ID': + return action.id; + } + + return state; +} + /** * Reducer managing installed themes. * @@ -570,6 +587,7 @@ export default combineReducers( { terms, users, currentTheme, + currentGlobalStylesId, currentUser, taxonomies, themes, diff --git a/packages/core-data/src/resolvers.js b/packages/core-data/src/resolvers.js index 7ff03976a8b4b0..11fb3a2d72faea 100644 --- a/packages/core-data/src/resolvers.js +++ b/packages/core-data/src/resolvers.js @@ -418,3 +418,26 @@ __experimentalGetTemplateForLink.shouldInvalidate = ( action ) => { action.name === 'wp_template' ); }; + +export const __experimentalGetCurrentGlobalStylesId = () => async ( { + dispatch, +} ) => { + const activeThemes = await apiFetch( { + path: '/wp/v2/themes?status=active', + } ); + const globalStylesURL = get( activeThemes, [ + 0, + '_links', + 'global-styles', + 0, + 'href', + ] ); + if ( globalStylesURL ) { + const globalStylesObject = await apiFetch( { + path: globalStylesURL, + } ); + dispatch.__experimentalReceiveCurrentGlobalStylesId( + globalStylesObject.id + ); + } +}; diff --git a/packages/core-data/src/selectors.js b/packages/core-data/src/selectors.js index c0c6de522a4fe7..46f3bf8043e899 100644 --- a/packages/core-data/src/selectors.js +++ b/packages/core-data/src/selectors.js @@ -687,6 +687,17 @@ export function getCurrentTheme( state ) { return state.themes[ state.currentTheme ]; } +/** + * Return the ID of the current global styles object. + * + * @param {Object} state Data state. + * + * @return {string} The current global styles ID. + */ +export function __experimentalGetCurrentGlobalStylesId( state ) { + return state.currentGlobalStylesId; +} + /** * Return theme supports data in the index. * diff --git a/packages/edit-site/src/components/global-styles/global-styles-provider.js b/packages/edit-site/src/components/global-styles/global-styles-provider.js index 724fd4e4408005..eac6e7d3471a38 100644 --- a/packages/edit-site/src/components/global-styles/global-styles-provider.js +++ b/packages/edit-site/src/components/global-styles/global-styles-provider.js @@ -56,13 +56,16 @@ function removeUserOriginFromSettings( settingsToRemove ) { function useGlobalStylesUserConfig() { const { globalStylesId, settings, styles } = useSelect( ( select ) => { - const _globalStylesId = select( editSiteStore ).getSettings() - .__experimentalGlobalStylesUserEntityId; - const record = select( coreStore ).getEditedEntityRecord( - 'root', - 'globalStyles', - _globalStylesId - ); + const _globalStylesId = select( + coreStore + ).__experimentalGetCurrentGlobalStylesId(); + const record = _globalStylesId + ? select( coreStore ).getEditedEntityRecord( + 'root', + 'globalStyles', + _globalStylesId + ) + : undefined; return { globalStylesId: _globalStylesId, settings: record?.settings, diff --git a/packages/editor/src/components/provider/use-block-editor-settings.js b/packages/editor/src/components/provider/use-block-editor-settings.js index 03cd44e35f2af6..c9235140c01f13 100644 --- a/packages/editor/src/components/provider/use-block-editor-settings.js +++ b/packages/editor/src/components/provider/use-block-editor-settings.js @@ -95,7 +95,6 @@ function useBlockEditorSettings( settings, hasTemplate ) { '__experimentalBlockPatterns', '__experimentalFeatures', '__experimentalGlobalStylesBaseConfig', - '__experimentalGlobalStylesUserEntityId', '__experimentalPreferredStyleVariations', '__experimentalSetIsInserterOpened', '__unstableGalleryWithImageBlocks', From efd6dc7e1366e5207e8a3132e95b8b2e53ac7dc2 Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Tue, 26 Oct 2021 10:17:51 +0100 Subject: [PATCH 03/15] Changes per review --- ...utenberg-rest-global-styles-controller.php | 26 ++++++++++++++++--- .../rest-active-global-styles.php | 4 +-- packages/core-data/src/resolvers.js | 2 +- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php index 80290daab8c1dc..318eab356cbc8a 100644 --- a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php +++ b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php @@ -227,8 +227,13 @@ protected function prepare_item_for_database( $request ) { $changes->post_content = wp_json_encode( $config ); } + // Post title. if ( isset( $request['title'] ) ) { - $changes->post_title = $request['title']; + if ( is_string( $request['title'] ) ) { + $changes->post_title = $request['title']; + } elseif ( ! empty( $request['title']['raw'] ) ) { + $changes->post_title = $request['title']['raw']; + } } return $changes; @@ -250,7 +255,7 @@ public function prepare_item_for_response( $post, $request ) { // phpcs:ignore V 'styles' => isset( $config['styles'] ) ? $config['styles'] : new stdClass(), 'title' => array( 'raw' => $post->title, - 'rendered' => $post->title, + 'rendered' => get_the_title( $post ), ), ); @@ -340,13 +345,13 @@ public function get_item_schema() { 'styles' => array( 'description' => __( 'Global styles.', 'gutenberg' ), 'type' => array( 'object' ), - 'default' => '', + 'default' => array(), 'context' => array( 'embed', 'view', 'edit' ), ), 'settings' => array( 'description' => __( 'Global settings.', 'gutenberg' ), 'type' => array( 'object' ), - 'default' => '', + 'default' => array(), 'context' => array( 'embed', 'view', 'edit' ), ), 'title' => array( @@ -354,6 +359,19 @@ public function get_item_schema() { 'type' => array( 'object', 'string' ), 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), + 'properties' => array( + 'raw' => array( + 'description' => __( 'Title for the global styles variation, as it exists in the database.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view', 'edit', 'embed' ), + ), + 'rendered' => array( + 'description' => __( 'HTML title for the post, transformed for display.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view', 'edit', 'embed' ), + 'readonly' => true, + ), + ), ), ), ); diff --git a/lib/compat/wordpress-5.9/rest-active-global-styles.php b/lib/compat/wordpress-5.9/rest-active-global-styles.php index b9e70b848808de..9a33afe7d57d59 100644 --- a/lib/compat/wordpress-5.9/rest-active-global-styles.php +++ b/lib/compat/wordpress-5.9/rest-active-global-styles.php @@ -28,8 +28,8 @@ function gutenberg_add_active_global_styles_link( $response, $theme ) { $global_styles_query = new WP_Query( $wp_query_args ); if ( count( $global_styles_query->posts ) ) { $response->add_link( - 'global-styles', - get_rest_url( null, 'wp/v2/global-styles/' . $global_styles_query->posts[0]->ID ) + 'https://api.w.org/global-styles', + rest_url( 'wp/v2/global-styles/' . $global_styles_query->posts[0]->ID ) ); } diff --git a/packages/core-data/src/resolvers.js b/packages/core-data/src/resolvers.js index 11fb3a2d72faea..92020cd2c6226d 100644 --- a/packages/core-data/src/resolvers.js +++ b/packages/core-data/src/resolvers.js @@ -428,7 +428,7 @@ export const __experimentalGetCurrentGlobalStylesId = () => async ( { const globalStylesURL = get( activeThemes, [ 0, '_links', - 'global-styles', + 'wp:global-styles', 0, 'href', ] ); From 7da64bc61367a2bd3daee2bf3b0816477d5bc67a Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Tue, 26 Oct 2021 10:41:20 +0100 Subject: [PATCH 04/15] Add unit test --- ...utenberg-rest-global-styles-controller.php | 2 +- ...erg-rest-global-styles-controller-test.php | 144 ++++++++++++++++++ 2 files changed, 145 insertions(+), 1 deletion(-) create mode 100644 phpunit/class-gutenberg-rest-global-styles-controller-test.php diff --git a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php index 318eab356cbc8a..4edf5aa474c927 100644 --- a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php +++ b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php @@ -254,7 +254,7 @@ public function prepare_item_for_response( $post, $request ) { // phpcs:ignore V 'settings' => isset( $config['settings'] ) ? $config['settings'] : new stdClass(), 'styles' => isset( $config['styles'] ) ? $config['styles'] : new stdClass(), 'title' => array( - 'raw' => $post->title, + 'raw' => $post->post_title, 'rendered' => get_the_title( $post ), ), ); diff --git a/phpunit/class-gutenberg-rest-global-styles-controller-test.php b/phpunit/class-gutenberg-rest-global-styles-controller-test.php new file mode 100644 index 00000000000000..de6ed422ba96bb --- /dev/null +++ b/phpunit/class-gutenberg-rest-global-styles-controller-test.php @@ -0,0 +1,144 @@ +user->create( + array( + 'role' => 'administrator', + ) + ); + // This creates the global styles for the current theme. + self::$global_styles_id = wp_insert_post( + array( + 'post_content' => '{"version": ' . WP_Theme_JSON_Gutenberg::LATEST_SCHEMA . ', "isGlobalStylesUserThemeJSON": true }', + 'post_status' => 'publish', + 'post_title' => __( 'Custom Styles', 'default' ), + 'post_type' => 'wp_global_styles', + 'post_name' => 'wp-global-styles-tt1-blocks', + 'tax_input' => array( + 'wp_theme' => 'tt1-blocks', + ), + ), + true + ); + } + + public function test_register_routes() { + $routes = rest_get_server()->get_routes(); + $this->assertArrayHasKey( '/wp/v2/global-styles', $routes ); + $this->assertArrayHasKey( '/wp/v2/global-styles/(?P[\/\w-]+)', $routes ); + } + + public function test_context_param() { + // TODO: Implement test_context_param() method. + $this->markTestIncomplete(); + } + + public function test_get_items() { + wp_set_current_user( 0 ); + $request = new WP_REST_Request( 'GET', '/wp/v2/global-styles' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_cannot_manage_global_styles', $response, 401 ); + + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'GET', '/wp/v2/global-styles' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertEquals( + array( + 'id' => self::$global_styles_id, + 'title' => array( + 'raw' => 'Custom Styles', + 'rendered' => 'Custom Styles', + ), + 'settings' => new stdClass(), + 'styles' => new stdClass(), + ), + $this->find_and_normalize_global_styles_by_id( $data, self::$global_styles_id ) + ); + } + + public function test_get_item() { + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'GET', '/wp/v2/global-styles/' . self::$global_styles_id ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + unset( $data['_links'] ); + + $this->assertEquals( + array( + 'id' => self::$global_styles_id, + 'title' => array( + 'raw' => 'Custom Styles', + 'rendered' => 'Custom Styles', + ), + 'settings' => new stdClass(), + 'styles' => new stdClass(), + ), + $data + ); + } + + public function test_create_item() { + $this->markTestIncomplete(); + } + + public function test_update_item() { + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'PUT', '/wp/v2/global-styles/' . self::$global_styles_id ); + $request->set_body_params( + array( + 'title' => 'My new global styles title', + ) + ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $this->assertEquals( 'My new global styles title', $data['title']['raw'] ); + } + + public function test_delete_item() { + $this->markTestIncomplete(); + } + + public function test_prepare_item() { + // TODO: Implement test_prepare_item() method. + $this->markTestIncomplete(); + } + + public function test_get_item_schema() { + // TODO: Implement test_get_item_schema() method. + $this->markTestIncomplete(); + } +} From 57fbca222c751250f35c08a248d14b6b137923b0 Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Tue, 26 Oct 2021 10:53:26 +0100 Subject: [PATCH 05/15] Small tweaks --- lib/compat/wordpress-5.9/rest-active-global-styles.php | 2 +- lib/global-styles.php | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/lib/compat/wordpress-5.9/rest-active-global-styles.php b/lib/compat/wordpress-5.9/rest-active-global-styles.php index 9a33afe7d57d59..1b05fc22e146d6 100644 --- a/lib/compat/wordpress-5.9/rest-active-global-styles.php +++ b/lib/compat/wordpress-5.9/rest-active-global-styles.php @@ -12,7 +12,7 @@ * @param WP_Theme $theme The theme object. */ function gutenberg_add_active_global_styles_link( $response, $theme ) { - $wp_query_args = array( + $wp_query_args = array( 'post_status' => array( 'publish' ), 'post_type' => 'wp_global_styles', 'posts_per_page' => 1, diff --git a/lib/global-styles.php b/lib/global-styles.php index 877c9cb326cfa2..acbd8c1123d9d2 100644 --- a/lib/global-styles.php +++ b/lib/global-styles.php @@ -122,8 +122,7 @@ function_exists( 'gutenberg_is_edit_site_page' ) && } if ( 'site-editor' === $context && gutenberg_experimental_is_site_editor_available() ) { - $theme = WP_Theme_JSON_Resolver_Gutenberg::get_merged_data( $settings, 'theme' ); - $user_cpt_id = WP_Theme_JSON_Resolver_Gutenberg::get_user_custom_post_type_id(); + $theme = WP_Theme_JSON_Resolver_Gutenberg::get_merged_data( $settings, 'theme' ); $settings['__experimentalGlobalStylesBaseConfig']['styles'] = $theme->get_raw_data()['styles']; $settings['__experimentalGlobalStylesBaseConfig']['settings'] = $theme->get_settings(); From 6532a3a1d268fc98c4f95e6db336e01f28bc5517 Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Tue, 26 Oct 2021 17:28:58 +0100 Subject: [PATCH 06/15] Remove list endpoint --- ...utenberg-rest-global-styles-controller.php | 50 ------------------- ...erg-rest-global-styles-controller-test.php | 23 +-------- 2 files changed, 1 insertion(+), 72 deletions(-) diff --git a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php index 4edf5aa474c927..5e2047f587cc07 100644 --- a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php +++ b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php @@ -31,21 +31,6 @@ public function __construct() { * @return void */ 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 gloval style variation based on the given id. register_rest_route( $this->namespace, @@ -94,41 +79,6 @@ protected function permissions_check() { return true; } - /** - * Checks if a given request has access to read global styles configs. - * - * @param WP_REST_Request $request Full details about the request. - * @return true|WP_Error True if the request has read access, WP_Error object otherwise. - */ - public function get_items_permissions_check( $request ) { - return $this->permissions_check( $request ); - } - - /** - * Returns a list of available global styles variations. - * - * @param WP_REST_Request $request The request instance. - * - * @return WP_REST_Response - */ - public function get_items( $request ) { - $wp_query_args = array( - 'post_status' => array( 'publish' ), - 'post_type' => 'wp_global_styles', - 'posts_per_page' => -1, - 'no_found_rows' => true, - ); - - $query = new WP_Query( $wp_query_args ); - $results = array(); - foreach ( $query->posts as $post ) { - $data = $this->prepare_item_for_response( $post, $request ); - $results[] = $this->prepare_response_for_collection( $data ); - } - - return rest_ensure_response( $results ); - } - /** * Checks if a given request has access to read a single global styles config. * diff --git a/phpunit/class-gutenberg-rest-global-styles-controller-test.php b/phpunit/class-gutenberg-rest-global-styles-controller-test.php index de6ed422ba96bb..83add34ff317b1 100644 --- a/phpunit/class-gutenberg-rest-global-styles-controller-test.php +++ b/phpunit/class-gutenberg-rest-global-styles-controller-test.php @@ -66,28 +66,7 @@ public function test_context_param() { } public function test_get_items() { - wp_set_current_user( 0 ); - $request = new WP_REST_Request( 'GET', '/wp/v2/global-styles' ); - $response = rest_get_server()->dispatch( $request ); - $this->assertErrorResponse( 'rest_cannot_manage_global_styles', $response, 401 ); - - wp_set_current_user( self::$admin_id ); - $request = new WP_REST_Request( 'GET', '/wp/v2/global-styles' ); - $response = rest_get_server()->dispatch( $request ); - $data = $response->get_data(); - - $this->assertEquals( - array( - 'id' => self::$global_styles_id, - 'title' => array( - 'raw' => 'Custom Styles', - 'rendered' => 'Custom Styles', - ), - 'settings' => new stdClass(), - 'styles' => new stdClass(), - ), - $this->find_and_normalize_global_styles_by_id( $data, self::$global_styles_id ) - ); + $this->markTestIncomplete(); } public function test_get_item() { From 847abef1e47f6c599f8c6145379fe814a1ddcde7 Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Tue, 26 Oct 2021 17:30:43 +0100 Subject: [PATCH 07/15] changes per review --- ...gutenberg-rest-global-styles-controller.php | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php index 5e2047f587cc07..66641843146161 100644 --- a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php +++ b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php @@ -155,11 +155,15 @@ protected function prepare_item_for_database( $request ) { $changes = new stdClass(); $changes->ID = $request['id']; - $post = get_post( $request['id'] ); - $existing_config = $post ? json_decode( $post->post_content, true ) : array( - 'settings' => array(), - 'styles' => array(), - ); + $post = get_post( $request['id'] ); + if ( $post ) { + $existing_config = json_decode( $post->post_content, true ); + } else { + $existing_config = array( + 'settings' => array(), + 'styles' => array(), + ); + } if ( isset( $request['styles'] ) || isset( $request['settings'] ) ) { $config = array(); @@ -296,13 +300,13 @@ public function get_item_schema() { 'description' => __( 'Global styles.', 'gutenberg' ), 'type' => array( 'object' ), 'default' => array(), - 'context' => array( 'embed', 'view', 'edit' ), + 'context' => array( 'view', 'edit' ), ), 'settings' => array( 'description' => __( 'Global settings.', 'gutenberg' ), 'type' => array( 'object' ), 'default' => array(), - 'context' => array( 'embed', 'view', 'edit' ), + 'context' => array( 'view', 'edit' ), ), 'title' => array( 'description' => __( 'Title of the global styles variation.', 'gutenberg' ), From ca75f741cbacdb56644ba4afec65f161b5702220 Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Wed, 27 Oct 2021 09:25:28 +0100 Subject: [PATCH 08/15] Better entity config --- packages/core-data/src/entities.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/core-data/src/entities.js b/packages/core-data/src/entities.js index d4bbe90a914d47..4fd73ea2b86912 100644 --- a/packages/core-data/src/entities.js +++ b/packages/core-data/src/entities.js @@ -132,6 +132,9 @@ export const defaultEntities = [ name: 'globalStyles', kind: 'root', baseURL: '/wp/v2/global-styles', + baseURLParams: { context: 'edit' }, + plural: 'globalStylesVariations', // should be different than name + getTitle: ( record ) => record?.title?.rendered || record?.title, }, ]; From d5355dd6c69a13ef87973c75f00eadb32d0b28c7 Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Wed, 27 Oct 2021 09:26:58 +0100 Subject: [PATCH 09/15] Use Full URL instead of path --- packages/core-data/src/resolvers.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core-data/src/resolvers.js b/packages/core-data/src/resolvers.js index 92020cd2c6226d..49589253422878 100644 --- a/packages/core-data/src/resolvers.js +++ b/packages/core-data/src/resolvers.js @@ -434,7 +434,7 @@ export const __experimentalGetCurrentGlobalStylesId = () => async ( { ] ); if ( globalStylesURL ) { const globalStylesObject = await apiFetch( { - path: globalStylesURL, + url: globalStylesURL, } ); dispatch.__experimentalReceiveCurrentGlobalStylesId( globalStylesObject.id From 1c0fa26012c07ebddc6ce48270fa651a79e3967e Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Wed, 27 Oct 2021 09:28:56 +0100 Subject: [PATCH 10/15] Rename link to user global styles --- lib/compat/wordpress-5.9/rest-active-global-styles.php | 2 +- packages/core-data/src/resolvers.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/compat/wordpress-5.9/rest-active-global-styles.php b/lib/compat/wordpress-5.9/rest-active-global-styles.php index 1b05fc22e146d6..6d4a0d9d4b1828 100644 --- a/lib/compat/wordpress-5.9/rest-active-global-styles.php +++ b/lib/compat/wordpress-5.9/rest-active-global-styles.php @@ -28,7 +28,7 @@ function gutenberg_add_active_global_styles_link( $response, $theme ) { $global_styles_query = new WP_Query( $wp_query_args ); if ( count( $global_styles_query->posts ) ) { $response->add_link( - 'https://api.w.org/global-styles', + 'https://api.w.org/user-global-styles', rest_url( 'wp/v2/global-styles/' . $global_styles_query->posts[0]->ID ) ); } diff --git a/packages/core-data/src/resolvers.js b/packages/core-data/src/resolvers.js index 49589253422878..1b66ae40751765 100644 --- a/packages/core-data/src/resolvers.js +++ b/packages/core-data/src/resolvers.js @@ -428,7 +428,7 @@ export const __experimentalGetCurrentGlobalStylesId = () => async ( { const globalStylesURL = get( activeThemes, [ 0, '_links', - 'wp:global-styles', + 'wp:user-global-styles', 0, 'href', ] ); From a4a579c21ca713c547dd1aca43caff38a682b06f Mon Sep 17 00:00:00 2001 From: Jorge Date: Wed, 27 Oct 2021 17:29:57 +0100 Subject: [PATCH 11/15] Add escaping, version and other fixes --- ...utenberg-rest-global-styles-controller.php | 23 ++++++++------ .../global-styles/global-styles-provider.js | 31 ++++++++++++++++--- 2 files changed, 39 insertions(+), 15 deletions(-) diff --git a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php index 66641843146161..1bdea611137a74 100644 --- a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php +++ b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php @@ -156,13 +156,17 @@ protected function prepare_item_for_database( $request ) { $changes->ID = $request['id']; $post = get_post( $request['id'] ); + $empty_config = array( + 'settings' => new stdClass(), + 'styles' => new stdClass(), + ); if ( $post ) { $existing_config = json_decode( $post->post_content, true ); + if( ! isset( $existing_config['isGlobalStylesUserThemeJSON'] ) || ! $existing_config['isGlobalStylesUserThemeJSON'] ) { + $existing_config = $empty_config; + } } else { - $existing_config = array( - 'settings' => array(), - 'styles' => array(), - ); + $existing_config = $empty_config; } if ( isset( $request['styles'] ) || isset( $request['settings'] ) ) { @@ -177,7 +181,8 @@ protected function prepare_item_for_database( $request ) { } else { $config['settings'] = $existing_config['settings']; } - + $config['isGlobalStylesUserThemeJSON'] = true; + $config['version'] = WP_Theme_JSON_Gutenberg::LATEST_SCHEMA; $changes->post_content = wp_json_encode( $config ); } @@ -203,16 +208,16 @@ protected function prepare_item_for_database( $request ) { */ public function prepare_item_for_response( $post, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable $config = json_decode( $post->post_content, true ); + $is_global_styles_user_theme_json = isset( $config['isGlobalStylesUserThemeJSON'] ) && true === $config['isGlobalStylesUserThemeJSON']; $result = array( 'id' => $post->ID, - 'settings' => isset( $config['settings'] ) ? $config['settings'] : new stdClass(), - 'styles' => isset( $config['styles'] ) ? $config['styles'] : new stdClass(), + 'settings' => ! empty( $config['settings'] ) && $is_global_styles_user_theme_json ? $config['settings'] : new stdClass(), + 'styles' => ! empty( $config['styles'] ) && $is_global_styles_user_theme_json ? $config['styles'] : new stdClass(), 'title' => array( 'raw' => $post->post_title, 'rendered' => get_the_title( $post ), ), ); - $result = $this->add_additional_fields_to_object( $result, $request ); $response = rest_ensure_response( $result ); $links = $this->prepare_links( $post->id ); @@ -299,13 +304,11 @@ public function get_item_schema() { 'styles' => array( 'description' => __( 'Global styles.', 'gutenberg' ), 'type' => array( 'object' ), - 'default' => array(), 'context' => array( 'view', 'edit' ), ), 'settings' => array( 'description' => __( 'Global settings.', 'gutenberg' ), 'type' => array( 'object' ), - 'default' => array(), 'context' => array( 'view', 'edit' ), ), 'title' => array( diff --git a/packages/edit-site/src/components/global-styles/global-styles-provider.js b/packages/edit-site/src/components/global-styles/global-styles-provider.js index eac6e7d3471a38..79b911067bf570 100644 --- a/packages/edit-site/src/components/global-styles/global-styles-provider.js +++ b/packages/edit-site/src/components/global-styles/global-styles-provider.js @@ -1,7 +1,17 @@ /** * External dependencies */ -import { get, cloneDeep, set, mergeWith } from 'lodash'; +import { + get, + cloneDeep, + set, + mergeWith, + pickBy, + isEmpty, + isObject, + identity, + mapValues, +} from 'lodash'; /** * WordPress dependencies @@ -53,6 +63,16 @@ function removeUserOriginFromSettings( settingsToRemove ) { } ); return newSettings; } +const cleanEmptyObject = ( object ) => { + if ( ! isObject( object ) || Array.isArray( object ) ) { + return object; + } + const cleanedNestedObjects = pickBy( + mapValues( object, cleanEmptyObject ), + identity + ); + return isEmpty( cleanedNestedObjects ) ? undefined : cleanedNestedObjects; +}; function useGlobalStylesUserConfig() { const { globalStylesId, settings, styles } = useSelect( ( select ) => { @@ -95,10 +115,11 @@ function useGlobalStylesUserConfig() { }; const updatedConfig = callback( currentConfig ); editEntityRecord( 'root', 'globalStyles', globalStylesId, { - styles: updatedConfig.styles, - settings: removeUserOriginFromSettings( - updatedConfig.settings - ), + styles: cleanEmptyObject( updatedConfig.styles ) || {}, + settings: + cleanEmptyObject( + removeUserOriginFromSettings( updatedConfig.settings ) + ) || {}, } ); }, [ globalStylesId ] From 70a95d6905ace086d3328bef1850a33bcae6941e Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Thu, 28 Oct 2021 09:18:08 +0100 Subject: [PATCH 12/15] Create initial global styles object for current theme --- lib/compat/wordpress-5.9/rest-active-global-styles.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/compat/wordpress-5.9/rest-active-global-styles.php b/lib/compat/wordpress-5.9/rest-active-global-styles.php index 6d4a0d9d4b1828..6a62bd50ec3d63 100644 --- a/lib/compat/wordpress-5.9/rest-active-global-styles.php +++ b/lib/compat/wordpress-5.9/rest-active-global-styles.php @@ -12,6 +12,11 @@ * @param WP_Theme $theme The theme object. */ function gutenberg_add_active_global_styles_link( $response, $theme ) { + if ( $theme->get_stylesheet() === wp_get_theme()->get_stylesheet() ) { + // This creates a record for the current theme if not existant. + WP_Theme_JSON_Resolver_Gutenberg::get_user_custom_post_type_id(); + } + $wp_query_args = array( 'post_status' => array( 'publish' ), 'post_type' => 'wp_global_styles', From a498b15b430bd3b1ea998c5f5cdf8fca1fdd9c44 Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Thu, 28 Oct 2021 09:23:21 +0100 Subject: [PATCH 13/15] Fix unit tests --- .../class-gutenberg-rest-global-styles-controller-test.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/phpunit/class-gutenberg-rest-global-styles-controller-test.php b/phpunit/class-gutenberg-rest-global-styles-controller-test.php index 83add34ff317b1..e933bfbba98e07 100644 --- a/phpunit/class-gutenberg-rest-global-styles-controller-test.php +++ b/phpunit/class-gutenberg-rest-global-styles-controller-test.php @@ -1,8 +1,5 @@ get_routes(); - $this->assertArrayHasKey( '/wp/v2/global-styles', $routes ); $this->assertArrayHasKey( '/wp/v2/global-styles/(?P[\/\w-]+)', $routes ); } From 2e2caa26bd251b2cb6aed57c8658b0d9a028915a Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Thu, 28 Oct 2021 09:44:52 +0100 Subject: [PATCH 14/15] Fix phpcs --- ...utenberg-rest-global-styles-controller.php | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php index 1bdea611137a74..7405af5e384946 100644 --- a/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php +++ b/lib/compat/wordpress-5.9/class-gutenberg-rest-global-styles-controller.php @@ -155,14 +155,15 @@ protected function prepare_item_for_database( $request ) { $changes = new stdClass(); $changes->ID = $request['id']; - $post = get_post( $request['id'] ); + $post = get_post( $request['id'] ); $empty_config = array( 'settings' => new stdClass(), 'styles' => new stdClass(), ); if ( $post ) { $existing_config = json_decode( $post->post_content, true ); - if( ! isset( $existing_config['isGlobalStylesUserThemeJSON'] ) || ! $existing_config['isGlobalStylesUserThemeJSON'] ) { + if ( ! isset( $existing_config['isGlobalStylesUserThemeJSON'] ) || + ! $existing_config['isGlobalStylesUserThemeJSON'] ) { $existing_config = $empty_config; } } else { @@ -182,8 +183,8 @@ protected function prepare_item_for_database( $request ) { $config['settings'] = $existing_config['settings']; } $config['isGlobalStylesUserThemeJSON'] = true; - $config['version'] = WP_Theme_JSON_Gutenberg::LATEST_SCHEMA; - $changes->post_content = wp_json_encode( $config ); + $config['version'] = WP_Theme_JSON_Gutenberg::LATEST_SCHEMA; + $changes->post_content = wp_json_encode( $config ); } // Post title. @@ -207,9 +208,9 @@ protected function prepare_item_for_database( $request ) { * @return WP_REST_Response $data */ public function prepare_item_for_response( $post, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable - $config = json_decode( $post->post_content, true ); + $config = json_decode( $post->post_content, true ); $is_global_styles_user_theme_json = isset( $config['isGlobalStylesUserThemeJSON'] ) && true === $config['isGlobalStylesUserThemeJSON']; - $result = array( + $result = array( 'id' => $post->ID, 'settings' => ! empty( $config['settings'] ) && $is_global_styles_user_theme_json ? $config['settings'] : new stdClass(), 'styles' => ! empty( $config['styles'] ) && $is_global_styles_user_theme_json ? $config['styles'] : new stdClass(), @@ -218,9 +219,9 @@ public function prepare_item_for_response( $post, $request ) { // phpcs:ignore V 'rendered' => get_the_title( $post ), ), ); - $result = $this->add_additional_fields_to_object( $result, $request ); - $response = rest_ensure_response( $result ); - $links = $this->prepare_links( $post->id ); + $result = $this->add_additional_fields_to_object( $result, $request ); + $response = rest_ensure_response( $result ); + $links = $this->prepare_links( $post->id ); $response->add_links( $links ); if ( ! empty( $links['self']['href'] ) ) { $actions = $this->get_available_actions(); From b91a650052c9556fa110f12e8323c1ffff75cfa1 Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Thu, 28 Oct 2021 09:57:16 +0100 Subject: [PATCH 15/15] Avoid duplicate queries --- .../rest-active-global-styles.php | 37 ++++++++++--------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/lib/compat/wordpress-5.9/rest-active-global-styles.php b/lib/compat/wordpress-5.9/rest-active-global-styles.php index 6a62bd50ec3d63..b0aa325f8cf483 100644 --- a/lib/compat/wordpress-5.9/rest-active-global-styles.php +++ b/lib/compat/wordpress-5.9/rest-active-global-styles.php @@ -14,27 +14,30 @@ function gutenberg_add_active_global_styles_link( $response, $theme ) { if ( $theme->get_stylesheet() === wp_get_theme()->get_stylesheet() ) { // This creates a record for the current theme if not existant. - WP_Theme_JSON_Resolver_Gutenberg::get_user_custom_post_type_id(); - } + $id = WP_Theme_JSON_Resolver_Gutenberg::get_user_custom_post_type_id(); + } else { - $wp_query_args = array( - 'post_status' => array( 'publish' ), - 'post_type' => 'wp_global_styles', - 'posts_per_page' => 1, - 'no_found_rows' => true, - 'tax_query' => array( - array( - 'taxonomy' => 'wp_theme', - 'field' => 'name', - 'terms' => $theme->get_stylesheet(), + $wp_query_args = array( + 'post_status' => array( 'publish' ), + 'post_type' => 'wp_global_styles', + 'posts_per_page' => 1, + 'no_found_rows' => true, + 'tax_query' => array( + array( + 'taxonomy' => 'wp_theme', + 'field' => 'name', + 'terms' => $theme->get_stylesheet(), + ), ), - ), - ); - $global_styles_query = new WP_Query( $wp_query_args ); - if ( count( $global_styles_query->posts ) ) { + ); + $global_styles_query = new WP_Query( $wp_query_args ); + $id = count( $global_styles_query->posts ) ? $global_styles_query->posts[0]->ID : null; + } + + if ( $id ) { $response->add_link( 'https://api.w.org/user-global-styles', - rest_url( 'wp/v2/global-styles/' . $global_styles_query->posts[0]->ID ) + rest_url( 'wp/v2/global-styles/' . $id ) ); }