Saturday, August 6, 2022
HomeWordPress Developmentblock editor - Can this react script be optimized? The best way...

block editor – Can this react script be optimized? The best way to make it sooner


That is my first try and work with WordPress blocks and likewise my first time working with React.

The code beneath provides the chance to conditionally present blocks.

My query is said to the “choose pages” part, or the “useSelect”.

I present a listing of pages which have been chosen beforehand. I additionally present a listing of pages primarily based on a search. Every time somebody selects a web page I would like the checkbox to maneuver from the search checklist to the chosen checklist. I can do this by including the ‘pagesArray’ as a dependency to useSelect. However that makes two REST api calls, which is gradual. How can I transfer them with out making the api calls once more?

Proper now the at the moment chosen checklist solely will get up to date when a search is finished.

Additionally, as that is my first React code, any suggestions is welcome!

That is my code:

const { __ }                            = wp.i18n;
const { createHigherOrderComponent }    = wp.compose;
const { Fragment }                      = wp.aspect;
const { InspectorControls }             = wp.blockEditor;
const { PanelBody, ToggleControl, CheckboxControl }      = wp.parts;
import { SearchControl, Spinner } from '@wordpress/parts';
import {useState } from "@wordpress/aspect";
import { useSelect } from '@wordpress/knowledge';
import { retailer as coreDataStore } from '@wordpress/core-data';
import { decodeEntities } from '@wordpress/html-entities';  

// Add attributes
perform addFilterAttribute(settings) {
    if (typeof settings.attributes !== 'undefined') {
        settings.attributes = Object.assign(settings.attributes, {
            hideOnMobile: {
                kind: 'boolean',
            },
            onlyOnHomePage: {
                kind: 'boolean',
            },
            onlyLoggedIn: {
                kind: 'boolean',
            },
            onlyOn: {
                kind: 'object'
            }
        });
    }
    return settings;
}
 
wp.hooks.addFilter(
    'blocks.registerBlockType',
    'sim/block-filter-attribute',
    addFilterAttribute
);

// Add controls to panel
const blockFilterControls = createHigherOrderComponent((BlockEdit) => {
    return ( props ) => {

        const { attributes, setAttributes } = props;

        const [ searchTerm, setSearchTerm ] = useState( '' );

        let pageIds = [];
        if(attributes.onlyOn != undefined){
            pageIds = Object.keys(attributes.onlyOn);
        }

        let checkedPages    = {};
        
        for (const id in attributes.onlyOn) {
            checkedPageshttps://wordpress.stackexchange.com/q/408335 = true;
        }

        const [ pagesArray, setPages ] = useState( checkedPages);

        const PagesList = perform ( { hasResolved, pages, showLoader = true } ) {
            if ( ! hasResolved ) {
                return(
                    <>
                    <Spinner />
                    <br></br>
                    </>
                );
            }
        
            if(attributes.onlyOn == undefined){
                attributes.onlyOn = {};
            }
        
            if ( ! pages?.size ) {
                if(showLoader){
                    return <div> {__('No search outcomes', 'sim')}</div>;
                }

                return '';
            }
        
            const onPagesChanged    = perform(checked){
                let copy = Object.assign({}, pagesArray);
                // that is the web page id
                copy[this]  = checked;
        
                setAttributes({onlyOn: copy});
        
                setPages(copy);
            }
        
            return (
                pages?.map( ( web page ) => {
        
                    return (<CheckboxControl
                        label       = {decodeEntities( web page.title.rendered )}
                        onChange    = {onPagesChanged.bind(web page.id)}
                        checked     = {pagesArray[page.id]}
                    />)
                } )
            );
        }

        const { pages, selectedPages, pagesResolved,  selectedPagesResolved} = useSelect(
            ( choose) => {
                // discover all pages excluding the already chosen pages
                const question = {exclude : pageIds};
                if ( searchTerm ) {
                    question.search = searchTerm;
                }
                const pagesArgs         = [ 'postType', 'page', query ];

                // Discover all chosen pages
                const selectedPagesArgs = [ 'postType', 'page', {include : pageIds} ];

                return {
                    pages: choose( coreDataStore ).getEntityRecords(
                        ...pagesArgs
                    ),
                    selectedPages: choose( coreDataStore ).getEntityRecords(
                        ...selectedPagesArgs
                    ),
                    pagesResolved: choose( coreDataStore ).hasFinishedResolution(
                        'getEntityRecords',
                        pagesArgs
                    ),
                    selectedPagesResolved: choose( coreDataStore ).hasFinishedResolution(
                        'getEntityRecords',
                        selectedPagesArgs
                    )
                };
            },
            [ searchTerm ]
        );

        let selectedPagesControls="";
        if(pageIds.size > 0){
            selectedPagesControls    =   <>
                <i> {__('Presently chosen pages', 'sim')}:</i>
                <br></br>
                <PagesList hasResolved={ selectedPagesResolved } pages={selectedPages} props={ props } showLoader={false}/>
            </>;
        }

        return (
            <Fragment>
                <BlockEdit { ...props } />
                <InspectorControls>
                    <PanelBody title={ __( 'Block Visibility' ) }>
                        <ToggleControl
                            label={__('Conceal on cell', 'sim')}
                            checked={!!attributes.hideOnMobile}
                            onChange={(newval) => setAttributes({ hideOnMobile: !attributes.hideOnMobile })}
                        />

                        <ToggleControl
                            label={__('Solely on dwelling web page', 'sim')}
                            checked={!!attributes.onlyOnHomePage}
                            onChange={(newval) => setAttributes({ onlyOnHomePage: !attributes.onlyOnHomePage })}
                        />

                        <ToggleControl
                            label={__('Conceal if not logged in', 'sim')}
                            checked={!!attributes.onlyLoggedIn}
                            onChange={(newval) => setAttributes({ onlyLoggedIn: !attributes.onlyLoggedIn })}
                        />
                    
                        <sturdy>{__('Choose pages', 'sim')}</sturdy><br></br>
                        {__('Choose pages you need this widget to indicate on', 'sim')}.<br></br>
                        {__('Go away empty for all pages', 'sim')}<br></br>
                        <br></br>
                        {selectedPagesControls}
                        <i>{__('Use searchbox beneath to seek for extra pages to incorporate', 'sim')}</i>
                        <SearchControl onChange={ setSearchTerm } worth={ searchTerm } />
                        <PagesList hasResolved={ pagesResolved } pages={ pages } props={ props }/>
                    </PanelBody>
                </InspectorControls>
            </Fragment>
        );
    };
}, 'blockFilterControls');
 
wp.hooks.addFilter(
    'editor.BlockEdit',
    'sim/block-filter-controls',
    blockFilterControls
);

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments