Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BBT-123]: Add functionality to allow editors to manage multiple style variations #51

Merged
merged 12 commits into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 39 additions & 8 deletions inc/class-rest-api.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ public function register_routes() {
'themer/v1',
'/style-variations',
array(
'methods' => 'GET',
'callback' => array( $this, 'get_all_theme_style_variation_posts' ),
'methods' => 'GET,POST',
'callback' => array( $this, 'handle_theme_style_variations' ),
'permission_callback' => function () {
return true;
return current_user_can( 'edit_theme_options' );
},
)
);
Expand Down Expand Up @@ -145,13 +145,16 @@ public function get_theme_json(): WP_REST_Response|WP_Error {
}

/**
* Returns all 'wp_global_styles' posts linked to the current theme.
* GET request returns all of the `wp_global_styles` posts for the current theme.
* POST request publishes the post with the supplied ID and sets all other posts to draft.
*
* @param WP_REST_Request $request - The request object.
* @return WP_REST_Response|WP_Error
*/
public function get_all_theme_style_variation_posts(): WP_REST_Response|WP_Error {
$theme = get_stylesheet();
$posts = get_posts(
public function handle_theme_style_variations( $request ): WP_REST_Response|WP_Error {
$method = $request->get_method();
$theme = get_stylesheet();
$posts = get_posts(
array(
'post_type' => 'wp_global_styles',
'post_status' => array( 'publish', 'draft' ),
Expand All @@ -176,6 +179,34 @@ public function get_all_theme_style_variation_posts(): WP_REST_Response|WP_Error
return new WP_Error( 'no_theme_styles', __( 'Unable to locate existing styles for the theme', 'themer' ) );
}

return rest_ensure_response( $posts );
if ( 'GET' === $method ) {
return rest_ensure_response( $posts );
}

if ( 'POST' === $method ) {
$json_body = $request->get_json_params();
$global_styles_id = $json_body['globalStylesId'];
$post_ids = array_column( $posts, 'ID' );
if ( ! $global_styles_id || ! in_array( $global_styles_id, $post_ids, true ) ) {
return new WP_Error( 'invalid_global_styles_id', __( 'Invalid global styles ID', 'themer' ) );
}

foreach ( $posts as $post ) {
$post_status = 'draft';
if ( $post->ID === $global_styles_id ) {
$post_status = 'publish';
}
wp_update_post(
array(
'ID' => $post->ID,
'post_status' => $post_status,
)
);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just flagging this as potentially slow, it will perform wp_update_post on all posts regardless of whether they are already draft and there could be many.

We expect (but can't assume) that there's only going to be 1 published post at a time we need to revert.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense - I've added an extra check at the beginning of the loop so any posts that aren't already published and aren't going to be published can be ignored.

if ( 'publish' !== $post->post_status && $post->ID !== $global_styles_id ) {
	continue;
}


return rest_ensure_response( new WP_REST_Response( array( 'message' => __( 'Active theme style variation updated.', 'themer' ) ), 200 ) );
}

return rest_ensure_response( new WP_REST_Response( array( 'error' => __( 'Unsupported request method.', 'themer' ) ), 405 ) );
}
}
104 changes: 94 additions & 10 deletions src/editor/components/ThemerComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
Spinner,
MenuGroup,
MenuItem,
SelectControl,
__experimentalNavigatorProvider as NavigatorProvider,
} from '@wordpress/components';
import { useSelect, dispatch } from '@wordpress/data';
Expand Down Expand Up @@ -37,6 +38,9 @@ const ThemerComponent = () => {
const [ previewExampleIsActive, setPreviewExampleIsActive ] = useState();
const [ schema, setSchema ] = useState( {} );
const [ validThemeJson, setValidThemeJson ] = useState();
const [ globalStylesId, setGlobalStylesId ] = useState( 0 );
const [ styleVariations, setStyleVariations ] = useState( [] );
const [ publishedStylesId, setPublishedStylesId ] = useState( 0 );

const setUserConfig = ( config ) => {
dispatch( 'core' ).editEntityRecord(
Expand All @@ -47,33 +51,38 @@ const ThemerComponent = () => {
);
};

const { globalStylesId, baseConfig, userConfig, savedUserConfig } =
useSelect( ( select ) => {
const { baseConfig, userConfig, savedUserConfig } = useSelect(
( select ) => {
if ( ! globalStylesId ) {
return {
baseConfig: {},
userConfig: {},
savedUserConfig: {},
};
}

const {
__experimentalGetCurrentGlobalStylesId,
__experimentalGetCurrentThemeBaseGlobalStyles,
getEditedEntityRecord,
getEntityRecord,
} = select( 'core' );

const currentGlobalStylesId =
__experimentalGetCurrentGlobalStylesId();

return {
globalStylesId: currentGlobalStylesId, // eslint-disable no-underscore-dangle -- require underscore dangle for experimental functions
baseConfig: __experimentalGetCurrentThemeBaseGlobalStyles(), // eslint-disable no-underscore-dangle -- require underscore dangle for experimental functions
userConfig: getEditedEntityRecord(
'root',
'globalStyles',
currentGlobalStylesId
globalStylesId
),
savedUserConfig: getEntityRecord(
'root',
'globalStyles',
currentGlobalStylesId
globalStylesId
),
};
} );
},
[ globalStylesId ]
);

/**
* Returns merged base and user configs
Expand Down Expand Up @@ -118,6 +127,28 @@ const ThemerComponent = () => {
setValidThemeJson( res );
};

/**
* Retrieve all style variations for the theme and store the global style ID in state.
*
* @return {void}
*/
const getStyleVariations = async () => {
const styleVariationsRes = await apiFetch( {
path: '/themer/v1/style-variations',
method: 'GET',
} );
setStyleVariations( styleVariationsRes );

const activeVariation = styleVariationsRes?.find(
( variation ) => variation.post_status === 'publish'
);
if ( ! activeVariation ) {
return;
}
setPublishedStylesId( activeVariation.ID );
setGlobalStylesId( activeVariation.ID );
};

/**
* Resets preview blocks to default template
*/
Expand All @@ -137,6 +168,10 @@ const ThemerComponent = () => {
validateThemeJson();
}, [] );

useEffect( () => {
getStyleVariations();
}, [] );

/**
* Alert user if they try to leave Themer without saving.
*/
Expand Down Expand Up @@ -179,6 +214,25 @@ const ThemerComponent = () => {
);
};

/**
* Sets the active style variation for the theme.
*/
const activate = async () => {
try {
await apiFetch( {
path: '/themer/v1/style-variations',
method: 'POST',
data: {
globalStylesId,
},
} );
setPublishedStylesId( globalStylesId );
} catch ( err ) {
// eslint-disable-next-line no-console
console.log( err );
}
};

const clearAllCustomisations = () => {
dispatch( 'core' ).editEntityRecord(
'root',
Expand All @@ -196,6 +250,19 @@ const ThemerComponent = () => {
);
}

const selectOptions = [
{
disabled: true,
label: __( 'Select a style variation', 'themer' ),
value: '',
},
,
...styleVariations.map( ( variation ) => ( {
label: variation.post_name,
value: variation.ID,
} ) ),
];

return (
<>
<EditorContext.Provider
Expand Down Expand Up @@ -225,6 +292,15 @@ const ThemerComponent = () => {
{ validThemeJson === true && (
<>
<div className="themer-topbar">
<SelectControl
options={ selectOptions }
value={ globalStylesId }
onChange={ ( value ) =>
setGlobalStylesId(
parseInt( value, 10 )
)
}
/>
<Button
isSecondary
onClick={ () => reset() }
Expand All @@ -237,6 +313,14 @@ const ThemerComponent = () => {
text="Save"
disabled={ ! hasUnsavedChanges }
/>
<Button
isPrimary
onClick={ activate }
text={ __( 'Activate', 'themer' ) }
disabled={
publishedStylesId === globalStylesId
}
/>
<MoreMenuDropdown>
{ () => (
<MenuGroup
Expand Down