Skip to content

Commit

Permalink
WIP: Saving styles
Browse files Browse the repository at this point in the history
  • Loading branch information
ribaricplusplus committed Jan 10, 2023
1 parent da5a0e0 commit 975326c
Show file tree
Hide file tree
Showing 7 changed files with 91 additions and 137 deletions.
5 changes: 1 addition & 4 deletions lib/class-wp-theme-json-resolver-gutenberg.php
Original file line number Diff line number Diff line change
Expand Up @@ -782,7 +782,7 @@ public static function get_style_variations() {
}

/**
* Returns the style variations defined by the user.
* Returns all style variations.
*
* @since 6.2.0
*
Expand All @@ -791,8 +791,6 @@ public static function get_style_variations() {
public static function get_user_style_variations() {
$stylesheet = get_stylesheet();

$initial_variation = (int) static::get_user_global_styles_post_id();

$args = array(
'posts_per_page' => -1,
'orderby' => 'date',
Expand All @@ -803,7 +801,6 @@ public static function get_user_style_variations() {
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'post__not_in' => array( $initial_variation ),
'tax_query' => array(
array(
'taxonomy' => 'wp_theme',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,12 @@ public function register_routes() {
'permission_callback' => array( $this, 'create_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);

register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/user/variations',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_user_items' ),
'permission_callback' => array( $this, 'get_user_items_permissions_check' ),
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);

Expand Down Expand Up @@ -127,6 +120,45 @@ public function register_routes() {

}

/**
* Checks if a given request has access to read all theme global styles configs.
*
* @since 6.0.0
*
* @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_items_permissions_check( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
// 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;
}

/**
* Deletes the given global styles config.
*
* @since 6.2
*
* @param WP_REST_Request $request The request instance.
*
* @return WP_REST_Response|WP_Error
*/
public function get_items( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
$variations = WP_Theme_JSON_Resolver_Gutenberg::get_user_style_variations();
$response = rest_ensure_response( $variations );
return $response;
}

/**
* Checks if a given request has access to delete a single global style.
*
Expand Down Expand Up @@ -195,45 +227,6 @@ public function delete_item( $request ) {
return $response;
}

/**
* Returns the user global styles variations.
*
* @since 6.2
*
* @param WP_REST_Request $request The request instance.
*
* @return WP_REST_Response|WP_Error
*/
public function get_user_items( /* @phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable */ $request ) {
$variations = WP_Theme_JSON_Resolver_Gutenberg::get_user_style_variations();
$response = rest_ensure_response( $variations );
return $response;
}

/**
* Checks if a given request has access to read a single user global styles config.
*
* @since 6.2
*
* @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_user_items_permissions_check( /* @phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable */ $request ) {
// 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 write a single global styles config.
*
Expand Down
48 changes: 0 additions & 48 deletions packages/core-data/src/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -857,54 +857,6 @@ export function receiveAutosaves( postId, autosaves ) {
};
}

/**
* @param {Object} globalStylesData Global styles configuration.
*/
export const __experimentalCreateNewGlobalStylesVariation =
( globalStylesData ) =>
async ( { dispatch, select } ) => {
const newVariationData = await apiFetch( {
path: '/wp/v2/global-styles',
method: 'POST',
data: globalStylesData,
} );

// Refresh variations
await dispatch.__experimentalRefreshUserGlobalStylesVariations();

/* eslint-disable dot-notation */
// Discard changes to the previously associated variation
const globalStylesId = select.__experimentalGetCurrentGlobalStylesId();
const userConfig = select.getEditedEntityRecord(
'root',
'globalStyles',
globalStylesId
);
if ( userConfig[ 'associated_style_id' ] ) {
dispatch.__experimentalDiscardRecordChanges(
'root',
'globalStyles',
userConfig[ 'associated_style_id' ]
);
}
/* eslint-enable dot-notation */

return newVariationData;
};

export const __experimentalRefreshUserGlobalStylesVariations =
() =>
async ( { dispatch, resolveSelect } ) => {
const currentTheme = await resolveSelect.getCurrentTheme();
const variations = await apiFetch( {
path: `/wp/v2/global-styles/user/variations`,
} );
dispatch.__experimentalReceiveUserGlobalStyleVariations(
currentTheme.stylesheet,
variations
);
};

/**
* Discards changes in the specified record.
*
Expand Down
2 changes: 1 addition & 1 deletion packages/core-data/src/resolvers.js
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ export const __experimentalGetGlobalStylesVariations =
);
} else {
const variations = await apiFetch( {
path: `/wp/v2/global-styles/user/variations`,
path: `/wp/v2/global-styles`,
} );
dispatch.__experimentalReceiveUserGlobalStyleVariations(
currentTheme.stylesheet,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,11 @@ function useGlobalStylesUserConfig() {
updatedRecord[ 'associated_style_id' ]
) {
associatedStyleIdChanged = true;
__experimentalDiscardRecordChanges(
'root',
'globalStyles',
currentConfig[ 'associated_style_id' ]
);
}

editEntityRecord(
Expand All @@ -171,24 +176,6 @@ function useGlobalStylesUserConfig() {
options
);

// If a theme variation is selected, discard any changes made to the
// associated style record
if (
! updatedRecord[ 'associated_style_id' ] &&
currentConfig[ 'associated_style_id' ] &&
hasFinishedResolution( 'getEditedEntityRecord', [
'root',
'globalStyles',
currentConfig[ 'associated_style_id' ],
] )
) {
__experimentalDiscardRecordChanges(
'root',
'globalStyles',
currentConfig[ 'associated_style_id' ]
);
}

// Also add changes that were made to the user record to the associated record.
if (
! associatedStyleIdChanged &&
Expand Down
50 changes: 40 additions & 10 deletions packages/edit-site/src/components/global-styles/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
__EXPERIMENTAL_PATHS_WITH_MERGE as PATHS_WITH_MERGE,
__EXPERIMENTAL_STYLE_PROPERTY as STYLE_PROPERTY,
} from '@wordpress/blocks';
import { store as coreStore } from '@wordpress/core-data';
import { store as coreStore, useEntityRecords } from '@wordpress/core-data';
import { useSelect, useDispatch } from '@wordpress/data';

/**
Expand Down Expand Up @@ -380,27 +380,57 @@ export function useHasUserModifiedStyles() {
}

export function useCreateNewStyleRecord( title ) {
const { __experimentalCreateNewGlobalStylesVariation } =
useDispatch( coreStore );
const { saveEntityRecord } = useDispatch( coreStore );
const { user } = useContext( GlobalStylesContext );
const callback = useCallback( () => {
return __experimentalCreateNewGlobalStylesVariation( {
const recordData = {
...user,
title,
} );
};
/* eslint-disable dot-notation */
delete recordData[ 'associated_style_id' ];
delete recordData[ 'id' ];
/* eslint-enable dot-notation */
return saveEntityRecord( 'root', 'globalStyles', recordData ).then(
( rawVariation ) => {
return {
...rawVariation,
title: rawVariation?.title?.rendered,
};
}
);
}, [ title, user ] );
return callback;
}

export function useCustomSavedStyles() {
const { variations } = useSelect( ( select ) => {
const { __experimentalGetGlobalStylesVariations } = select( coreStore );
const { globalStylesId } = useSelect( ( select ) => {
return {
variations: __experimentalGetGlobalStylesVariations( 'user' ),
globalStylesId:
select( coreStore ).__experimentalGetCurrentGlobalStylesId(),
};
}, [] );

return variations;
const { records: variations } = useEntityRecords( 'root', 'globalStyles' );

const customVariations = useMemo( () => {
return (
variations
?.filter( ( variation ) => variation.id !== globalStylesId )
?.map( ( variation ) => {
let newVariation = variation;
if ( variation?.title?.rendered !== undefined ) {
newVariation = {
...variation,
title: variation.title.rendered,
};
}

return newVariation;
} ) || []
);
}, [ globalStylesId, variations ] );

return customVariations;
}

export function useUserChangesMatchAnyVariation( variations ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,7 @@ function UserVariation( { variation, userChangesMatchAnyVariation } ) {
const { base, user, setUserConfig } = useContext( GlobalStylesContext );
const associatedStyleId = user[ 'associated_style_id' ];
const { hasEditsForEntityRecord } = useSelect( coreStore );
const {
deleteEntityRecord,
__experimentalRefreshUserGlobalStylesVariations,
} = useDispatch( coreStore );
const { deleteEntityRecord } = useDispatch( coreStore );
const { globalStyleId } = useSelect( ( select ) => {
return {
globalStyleId:
Expand Down Expand Up @@ -237,9 +234,7 @@ function UserVariation( { variation, userChangesMatchAnyVariation } ) {
} ) );
}

deleteEntityRecord( 'root', 'globalStyles', variation.id ).then( () => {
__experimentalRefreshUserGlobalStylesVariations();
} );
deleteEntityRecord( 'root', 'globalStyles', variation.id );
}, [ variation, associatedStyleId ] );

return (
Expand Down

0 comments on commit 975326c

Please sign in to comment.