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

Block Render and Screenshots #454

Merged
merged 5 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
88 changes: 88 additions & 0 deletions includes/RestApi/BlockRenderController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

namespace NewfoldLabs\WP\Module\Onboarding\RestApi;

use NewfoldLabs\WP\Module\Onboarding\Permissions;
use NewfoldLabs\WP\Module\Onboarding\Data\Services\BlockRenderService;

/**
* Undocumented class
*/
class BlockRenderController {

/**
* The namespace of this controller's route.
*
* @var string
*/
protected $namespace = 'newfold-onboarding/v1';

/**
* The endpoint base
*
* @var string
*/
protected $rest_base = '/block-render';

/**
* Registers rest routes for BlockRenderController class.
*
* @return void
*/
public function register_routes() {
\register_rest_route(
$this->namespace,
$this->rest_base . '/screenshot',
array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array( $this, 'generate_screenshot' ),
'permission_callback' => array( Permissions::class, 'rest_is_authorized_admin' ),
'args' => $this->generate_screenshot_args(),
)
);
}

/**
* Args for Generating the screenshot.
*
* @return array
*/
public function generate_screenshot_args() {
return array(
'width' => array(
'required' => true,
'type' => 'integer',
),
'height' => array(
'required' => true,
'type' => 'integer',
),
'content' => array(
'required' => true,
'type' => 'string',
),
);
}

/**
* Generates a PNG screenshot of the HTML block render.
*
* @param \WP_REST_Request $request The incoming request.
* @return \WP_REST_Response|\WP_Error
*/
public function generate_screenshot( \WP_REST_Request $request ) {
$width = $request->get_param( 'width' );
$height = $request->get_param( 'height' );
$content = $request->get_param( 'content' );

$screenshot = BlockRenderService::generate_screenshot( $width, $height, $content );
if ( is_wp_error( $screenshot ) ) {
return $screenshot;
}

return new \WP_REST_Response(
$screenshot,
201
);
}
}
1 change: 1 addition & 0 deletions includes/RestApi/RestApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ final class RestApi {
'NewfoldLabs\WP\\Module\\Onboarding\\RestApi\\Themes\\ThemeColorsController',
'NewfoldLabs\\WP\\Module\\Onboarding\\RestApi\\SiteClassificationController',
'NewfoldLabs\\WP\\Module\\Onboarding\\RestApi\\SiteGenController',
'NewfoldLabs\\WP\\Module\\Onboarding\\RestApi\\BlockRenderController',
);

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import Animate from '../../Animate';

const BlockPreview = ( {
slug = '',
blockGrammer,
viewportWidth = 1300,
styling = 'large',
Expand Down Expand Up @@ -37,7 +38,7 @@
if ( setIsLoadingParent ) {
setIsLoadingParent( false );
}
}, [ skeletonLoadingTime ] );

Check warning on line 41 in src/OnboardingSPA/components/LivePreview/BlockPreview/index.js

View workflow job for this annotation

GitHub Actions / Run Lint Checks

React Hook useEffect has a missing dependency: 'setIsLoadingParent'. Either include it or remove the dependency array. If 'setIsLoadingParent' changes too often, find the parent component that defines it and wrap that definition in useCallback

const { currentData, storedPreviewSettings } = useSelect( ( select ) => {
return {
Expand Down Expand Up @@ -69,7 +70,7 @@
if ( ! previewSettings ) {
setSettings( storedPreviewSettings );
}
}, [ storedPreviewSettings, currentData ] );

Check warning on line 73 in src/OnboardingSPA/components/LivePreview/BlockPreview/index.js

View workflow job for this annotation

GitHub Actions / Run Lint Checks

React Hook useEffect has a missing dependency: 'previewSettings'. Either include it or remove the dependency array

const SkeletonLivePreviewDefault = memo( () => {
return (
Expand Down Expand Up @@ -122,7 +123,10 @@
};

return (
<div className={ `live-preview__container-${ styling }` }>
<div
data-slug={ `nfd-onboarding-block-preview-${ slug }` }
className={ `live-preview__container-${ styling }` }
>
{ loading && getSkeleton() }
{ blocks && settings && (
<BlockEditorProvider
Expand Down
104 changes: 97 additions & 7 deletions src/OnboardingSPA/steps/SiteGen/Editor/Header/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { __ } from '@wordpress/i18n';
import { Fill } from '@wordpress/components';
import { Icon, chevronRight } from '@wordpress/icons';
import { useSelect, useDispatch } from '@wordpress/data';
import { useEffect, useState, render } from '@wordpress/element';
import { useViewportMatch } from '@wordpress/compose';
// eslint-disable-next-line import/no-extraneous-dependencies
import { cloneDeep } from 'lodash';

import {
HEADER_CENTER,
HEADER_END,
Expand All @@ -8,22 +15,20 @@
SIDEBAR_SITEGEN_EDITOR_PATTERNS,
pluginDashboardPage,
} from '../../../../../constants';
import { Icon, chevronRight } from '@wordpress/icons';
import { store as nfdOnboardingStore } from '../../../../store';

import { useSelect, useDispatch } from '@wordpress/data';

import { useEffect, useState } from '@wordpress/element';
import { setFlow, completeFlow } from '../../../../utils/api/flow';
import Spinner from '../../../../components/Loaders/Spinner';
import { regenerateHomepage } from '../../../../utils/api/siteGen';
import StepEditorHeaderCenter from './center';
import { useViewportMatch } from '@wordpress/compose';
import { getGlobalStyles } from '../../../../utils/api/themes';
import { LivePreview } from '../../../../components/LivePreview';
import { blockRenderScreenshot } from '../../../../utils/api/blockRender';

const StepSiteGenEditorHeader = () => {
const [ homepage, setHomepage ] = useState();
const [ isSaving, setIsSaving ] = useState( false );
const [ isRegenerating, setIsRegenerating ] = useState( false );
const [ globalStyles, setGlobalStyles ] = useState( false );

const isLargeViewport = useViewportMatch( 'medium' );

Expand Down Expand Up @@ -102,11 +107,13 @@
setIsSidebarOpened( true );
};

const handleCustomize = () => {
const handleCustomize = async () => {
const isSidebarOpenedNew =
sideBarView === 'Customize' ? ! isSidebarOpened : isSidebarOpened;
setSidebarActiveView( 'Customize' );
setIsSidebarOpened( isSidebarOpenedNew );
const globalStylesResponse = await getGlobalStyles();
setGlobalStyles( globalStylesResponse.body );
};

const handleRename = ( title ) => {
Expand All @@ -116,8 +123,91 @@
setCurrentOnboardingData( currentData );
};

const buildPreviewsForScreenshot = ( homepages, activeHomepage ) => {
return (
<div className="nfd-onboarding-screenshot-container__pages">
{ Object.keys( homepages ).map( ( slug, idx ) => {
const data = homepages[ slug ];
if ( ! data.isFavorite && slug !== activeHomepage.slug ) {
return false;
}
const newPreviewSettings = cloneDeep( globalStyles[ 0 ] );
newPreviewSettings.settings.color.palette =
data.color.palette;
let blockGrammar = '';
[ 'header', 'content', 'footer' ].forEach( ( part ) => {
if ( part in data ) {
blockGrammar += data[ part ];
}
} );
return (
<LivePreview
key={ idx }
blockGrammer={ blockGrammar }
previewSettings={ newPreviewSettings }
slug={ slug }
tabIndex="0"
role="button"
/>
);
} ) }
</div>
);
};

const saveAndContinue = async () => {
setIsSaving( true );

const homepages = currentData.sitegen.homepages.data;
const activeHomepage = currentData.sitegen.homepages.active;
const finalPreviews = buildPreviewsForScreenshot(
homepages,
activeHomepage
);
const ele = document.querySelector(
'.nfd-onboarding-screenshot-container'
);
if ( ele ) {
render( finalPreviews, ele );

const delay = ( ms ) =>
new Promise( ( res ) => setTimeout( res, ms ) );
await delay( 5000 );

const screenshots = await Promise.all(
Object.keys( homepages ).map( ( slug ) => {
const data = homepages[ slug ];
if ( ! data.isFavorite && slug !== activeHomepage.slug ) {
return false;
}

const iframe = ele.querySelector(
`div > div[data-slug="nfd-onboarding-block-preview-${ slug }"] > .block-editor-block-preview__container > div > iframe`
);
const html = iframe.contentWindow.document.querySelector(
'.block-editor-block-preview__content-iframe'
);

return blockRenderScreenshot( html.innerHTML );
} )
);

Object.keys( homepages ).forEach( ( slug, idx ) => {
if ( screenshots[ idx ]?.body?.screenshot ) {
homepages[ slug ].screenshot =
screenshots[ idx ].body.screenshot;
if ( slug === activeHomepage.slug ) {
activeHomepage.screenshot =
screenshots[ idx ].body.screenshot;
}
}
} );

currentData.sitegen.homepages.data = homepages;
currentData.sitegen.homepages.active = activeHomepage;
setCurrentOnboardingData( currentData );
return currentData;
}
await setFlow( currentData );
await completeFlow();
window.location.replace( pluginDashboardPage );
Expand All @@ -125,7 +215,7 @@

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

Check warning on line 218 in src/OnboardingSPA/steps/SiteGen/Editor/Header/index.js

View workflow job for this annotation

GitHub Actions / Run Lint Checks

React Hook useEffect has a missing dependency: 'handleCustomize'. Either include it or remove the dependency array

useEffect( () => {
if ( currentData?.sitegen?.homepages?.active ) {
Expand Down
1 change: 1 addition & 0 deletions src/OnboardingSPA/steps/SiteGen/Editor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
setDrawerActiveView( false );
loadData();
handleSitemapPagesGeneration();
}, [] );

Check warning on line 63 in src/OnboardingSPA/steps/SiteGen/Editor/index.js

View workflow job for this annotation

GitHub Actions / Run Lint Checks

React Hook useEffect has missing dependencies: 'handleSitemapPagesGeneration', 'loadData', 'setDrawerActiveView', 'setHeaderActiveView', and 'setIsHeaderEnabled'. Either include them or remove the dependency array

useEffect( () => {
if ( currentData?.sitegen?.homepages?.active ) {
Expand Down Expand Up @@ -122,6 +122,7 @@
<div className="nfd-onboarding-step--site-gen__editor__live-preview">
{ buildPreview() }
</div>
<div className="nfd-onboarding-screenshot-container"></div>
</CommonLayout>
);
};
Expand Down
18 changes: 18 additions & 0 deletions src/OnboardingSPA/utils/api/blockRender.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import apiFetch from '@wordpress/api-fetch';

import { onboardingRestURL } from './common';
import { resolve } from './resolve.js';

export async function blockRenderScreenshot( content ) {
return await resolve(
apiFetch( {
url: onboardingRestURL( 'block-render/screenshot' ),
method: 'POST',
data: {
width: 1200,
height: 900,
content,
},
} ).then()
);
}
Loading