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

Add/theme header menu #110

Merged
merged 17 commits into from
Dec 7, 2022
Merged
Show file tree
Hide file tree
Changes from 10 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
82 changes: 82 additions & 0 deletions includes/Data/Patterns.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,30 @@ protected static function get_theme_step_patterns() {
'description' => __( 'A page for periodic news, announcements and ideas.', 'wp-module-onboarding' ),
),
),
'header-menu' => array(
abhijitb marked this conversation as resolved.
Show resolved Hide resolved
'site-header-left-logo-navigation-inline' => array(
'active' => true,
),
'homepage-1' => array(
'active' => true,
),
'site-footer' => array(
'active' => true,
),
'site-header-left-logo-navigation-below' => array(
'active' => true,
),
'site-header-centered' => array(
'active' => true,
),
'site-header-centered-logo-split-menu' => array(
'active' => true,
)
),
'header-menu-body' => array(
'homepage-1',
'site-footer',
),
),
);
}
Expand All @@ -98,6 +122,7 @@ public static function get_pattern_from_slug( $pattern_slug ) {
if ( $block_patterns_registry->is_registered( $pattern_name ) ) {
$pattern = $block_patterns_registry->get_registered( $pattern_name );
return array(
'slug' => $pattern['slug'],
abhijitb marked this conversation as resolved.
Show resolved Hide resolved
'title' => $pattern['title'],
'content' => self::cleanup_wp_grammar( $pattern['content'] ),
'name' => $pattern['name'],
Expand Down Expand Up @@ -252,4 +277,61 @@ public static function get_count_of_patterns() {
}
return $theme_pattern_count;
}

public static function get_all_patterns_for_slug($slug_keyword)
abhijitb marked this conversation as resolved.
Show resolved Hide resolved
{
$active_theme = (\wp_get_theme())->get('TextDomain');

$block_patterns_registry = \WP_Block_Patterns_Registry::get_instance();
$all_patterns = $block_patterns_registry->get_all_registered();
abhijitb marked this conversation as resolved.
Show resolved Hide resolved

$filtered_patterns = array();
foreach($all_patterns as $pattern_info) {
if( strpos($pattern_info['slug'], $active_theme) === 0 // making sure the slug name starts with the theme name
&& strpos($pattern_info['slug'], $slug_keyword) !== FALSE ) {
$filtered_patterns[] = $pattern_info;
}
}
return $filtered_patterns;
}

public static function get_default_header()
{
$active_theme = (\wp_get_theme())->get('TextDomain');

$header_menu_page_pattern = array_keys(self::get_theme_step_patterns()[$active_theme]['header-menu']);
abhijitb marked this conversation as resolved.
Show resolved Hide resolved
$header_menu_pattern = preg_grep("/header/", $header_menu_page_pattern);

return ($header_menu_pattern !== FALSE) ? $active_theme.'/'.$header_menu_pattern[0] : FALSE;
}

public static function get_header_pattern_preview($slug, $squash = true)
{
$active_theme = (\wp_get_theme())->get('TextDomain');

$pattern_slugs = self::get_theme_step_patterns()[$active_theme]['header-menu-body'];
$pattern_slugs = array_merge(array($slug), $pattern_slugs);

$block_patterns = array();
$block_patterns_squashed = '';
$block_patterns_registry = \WP_Block_Patterns_Registry::get_instance();

foreach($pattern_slugs as $pattern_slug) {
$pattern_name = (strpos($pattern_slug, $active_theme) === 0) ? $pattern_slug : $active_theme . '/' . $pattern_slug;
if ($block_patterns_registry->is_registered($pattern_name)) {
$pattern = $block_patterns_registry->get_registered($pattern_name);
if (!$squash) {
$block_patterns[] = array(
'slug' => $slug,
'title' => $pattern['title'],
'content' => self::cleanup_wp_grammar($pattern['content']),
'name' => $pattern['name'],
);
continue;
}
$block_patterns_squashed .= self::cleanup_wp_grammar($pattern['content']);
}
}
return $squash ? $block_patterns_squashed : $block_patterns;
abhijitb marked this conversation as resolved.
Show resolved Hide resolved
}
}
100 changes: 100 additions & 0 deletions includes/RestApi/Themes/PatternsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,39 @@ public function register_routes() {
),
)
);
register_rest_route(
$this->namespace,
$this->rest_base . '/header',
array(
array(
'methods' => \WP_REST_Server::READABLE,
'callback' => array( $this, 'get_all_header_patterns' ),
'permission_callback' => array( Permissions::class, 'rest_is_authorized_admin' ),
),
)
);
register_rest_route(
$this->namespace,
$this->rest_base . '/header/default',
array(
array(
'methods' => \WP_REST_Server::READABLE,
'callback' => array( $this, 'get_default_header_pattern' ),
'permission_callback' => array( Permissions::class, 'rest_is_authorized_admin' ),
),
)
);
register_rest_route(
$this->namespace,
$this->rest_base . '/header/preview',
array(
array(
'methods' => \WP_REST_Server::READABLE,
'callback' => array( $this, 'get_header_pattern_preview' ),
'permission_callback' => array( Permissions::class, 'rest_is_authorized_admin' ),
),
)
);
}

public function get_pattern_args() {
Expand Down Expand Up @@ -143,4 +176,71 @@ public function set_pattern( \WP_REST_Request $request ) {

return Patterns::set_theme_step_patterns( $step, $slug );
}

/**
* Retrieves all the header patterns.
*
* @return \WP_Rest_Response|\WP_Error
*/
public function get_all_header_patterns()
{
$slug_keyword = 'header';

$header_patterns = Patterns::get_all_patterns_for_slug($slug_keyword);
if (!$header_patterns) {
return new \WP_Error(
'no_patterns_found',
__('No Patterns Found.'),
array('status' => 404)
);
}

return new \WP_REST_Response(
$header_patterns
);
}

/**
* Retrieves deafult the header pattern.
*
* @return \WP_Rest_Response|\WP_Error
*/
public function get_default_header_pattern()
{
$header_pattern = Patterns::get_default_header();
if (!$header_pattern) {
return new \WP_Error(
'no_default_pattern_found',
__('No Default Pattern Found.'),
array('status' => 404)
);
}

return new \WP_REST_Response(
$header_pattern
);
}

/**
* Retrieves pattern for specific header pattern.
*
* @return \WP_Rest_Response|\WP_Error
*/
public function get_header_pattern_preview(\WP_REST_Request $request)
{
$slug = $request->get_param('slug');
abhijitb marked this conversation as resolved.
Show resolved Hide resolved

$header_pattern_preview = Patterns::get_header_pattern_preview($slug);
if (!$header_pattern_preview) {
return new \WP_Error(
'no_header_preview',
__('Preview for the provided header pattern could not be generated.'),
array('status' => 404)
);
}

return new \WP_REST_Response(
$header_pattern_preview
);
}
}
146 changes: 134 additions & 12 deletions src/OnboardingSPA/components/Drawer/DrawerPanel/DesignHeaderMenu.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,139 @@
import { __ } from '@wordpress/i18n';
import { useSelect, useDispatch } from '@wordpress/data';
import { useState, useEffect } from '@wordpress/element';

import HeaderMenuPreview from '../../HeaderMenuPreview';
import { store as nfdOnboardingStore } from '../../../store';
import { getPatterns, getHeaderMenuPatterns, getDefaultHeaderMenu } from '../../../utils/api/patterns';
import { GlobalStylesProvider } from '../../../components/LivePreview';

import {
THEME_STATUS_ACTIVE,
THEME_STATUS_NOT_ACTIVE,
} from '../../../../constants';

const DesignHomepageMenu = () => {
const headerMenuSlugs = [
abhijitb marked this conversation as resolved.
Show resolved Hide resolved
'yith-wonder/site-header-left-logo-navigation-inline',
'yith-wonder/site-header-left-logo-navigation-below',
'yith-wonder/site-header-centered',
'yith-wonder/site-header-centered-logo-split-menu'
];
const headerMenuBodySlugs = [ 'yith-wonder/homepage-1', 'yith-wonder/site-footer'];

const [ isLoaded, setIsLoaded ] = useState( false );
const [ patterns, setPatterns ] = useState();
const [ headerMenuPreviewData, setHeaderMenuPreviewData ] = useState();
const [ selectedPattern, setSelectedPattern ] = useState( '' );

const { currentStep, currentData, themeStatus } =
useSelect( ( select ) => {
return {
currentStep: select( nfdOnboardingStore ).getCurrentStep(),
currentData:
select( nfdOnboardingStore ).getCurrentOnboardingData(),
themeStatus: select( nfdOnboardingStore ).getThemeStatus(),
};
}, [] );

const {
setCurrentOnboardingData,
updateThemeStatus,
setHeaderMenuData,
} = useDispatch( nfdOnboardingStore );

const getPatternsData = async () => {
const headerMenuPreviewResponse = await getPatterns( currentStep.patternId );
if ( headerMenuPreviewResponse?.error ) {
return updateThemeStatus( THEME_STATUS_NOT_ACTIVE );
}
setHeaderMenuPreviewData(headerMenuPreviewResponse.body);

// let headerMenuPatterns = [];
// headerMenuPreviewResponse.body.forEach( ( pageParts ) => {
// if(headerMenuSlugs.includes(pageParts.slug)){
// console.log(pageParts.content);
// headerMenuPatterns.push(pageParts.content);
// }
// });
// console.log(headerMenuPatterns);

const patternsResponse = await getHeaderMenuPatterns();
if ( patternsResponse?.error ) {
return updateThemeStatus( THEME_STATUS_NOT_ACTIVE );
}
setPatterns( patternsResponse?.body );

if(!currentData.data.partHeader || currentData.data.partHeader == "") {
const defaultHeaderMenu = await getDefaultHeaderMenu();
if ( defaultHeaderMenu?.error ) {
return updateThemeStatus( THEME_STATUS_NOT_ACTIVE );
}
currentData.data.partHeader = defaultHeaderMenu.body;
setCurrentOnboardingData( currentData );
}
setSelectedPattern(currentData.data.partHeader);

let [pageContent, headerContent, pagePreview] = ["", "", ""];
headerMenuPreviewResponse.body.forEach( ( pageParts ) => {
if(headerMenuBodySlugs.includes(pageParts.slug)){
pageContent += pageParts.content;
}
if(pageParts.slug === currentData.data.partHeader){
headerContent += pageParts.content;
}
});
pagePreview = headerContent + pageContent;
setHeaderMenuData( pagePreview );
setIsLoaded( true );
};

useEffect( () => {
if ( ! isLoaded && themeStatus === THEME_STATUS_ACTIVE )
getPatternsData();
}, [ isLoaded, themeStatus ] );

const handleClick = ( idx ) => {
const selectedPattern = patterns[ idx ];

setSelectedPattern( selectedPattern.slug );
currentData.data.partHeader = selectedPattern.slug;
setCurrentOnboardingData( currentData );

let newPagePattern = selectedPattern.content;
headerMenuPreviewData.forEach( ( pageParts ) => {
if(headerMenuBodySlugs.includes(pageParts.slug)){
newPagePattern += pageParts.content;
}
});
setHeaderMenuData( newPagePattern );
};

const buildPreviews = () => {
return patterns?.map( ( pattern, idx ) => {
return (
<HeaderMenuPreview
officiallygod marked this conversation as resolved.
Show resolved Hide resolved
key={ idx }
className={ 'theme-header-menu-preview--drawer__list__item' }
selected={ pattern.slug === selectedPattern }
blockGrammer={ pattern.content }
viewportWidth={ 900 }
styling={ 'custom' }
overlay={ false }
onClick={ () => handleClick( idx ) }
/>
);
} );
};

const DesignHeaderMenu = () => {
return (
<div style={{ padding: '0 16px' }}>
<h2>{__('Pick a Header & Menu Style', 'wp-module-onboarding')}</h2>
<p>
{__(
'Panel will show a few Header Patterns to affect preview pane.',
'wp-module-onboarding'
)}
</p>
</div>
<GlobalStylesProvider>
<div className="theme-header-menu-preview--drawer">
<div className="theme-header-menu-preview--drawer__list">
{ patterns ? buildPreviews(): '' }
abhijitb marked this conversation as resolved.
Show resolved Hide resolved
</div>
</div>
</GlobalStylesProvider>
);
};

export default DesignHeaderMenu;
export default DesignHomepageMenu;
Loading