Skip to content

Commit

Permalink
Experiment: capture input in suspense placeholder
Browse files Browse the repository at this point in the history
  • Loading branch information
jsnajdr committed Jan 31, 2024
1 parent e851852 commit 5e969f3
Showing 1 changed file with 51 additions and 3 deletions.
54 changes: 51 additions & 3 deletions packages/block-library/src/utils/lazy-load.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,62 @@
/**
* WordPress dependencies
*/
import { Suspense, lazy } from '@wordpress/element';
import { Suspense, lazy, useEffect, useState } from '@wordpress/element';
import { useBlockProps } from '@wordpress/block-editor';

const FallbackEdit = ( { tempContent, setTempContent } ) => {
const blockProps = useBlockProps();
const onChange = ( e ) => {
setTempContent( e.target.value );
};

return (
<div { ...blockProps }>
<input value={ tempContent } onChange={ onChange } />
</div>
);
};

// Sets the block content on mount
const Init = ( { content, setContent } ) => {
useEffect( () => {
if ( content.length > 0 ) {
setContent( content );
}
}, [] );

return null;
};

// Add delay to the module load for better debugging
const delay = async ( cb, ms = 0 ) => {
if ( ms > 0 ) {
await new Promise( ( r ) => setTimeout( r, ms ) );
}
return await cb();
};

export default function lazyEdit( cb ) {
// eslint-disable-next-line @wordpress/no-unused-vars-before-return
const Load = lazy( cb );
const Load = lazy( () => delay( cb, 3000 ) );
return function Edit( props ) {
// captures what was typed into the placeholder while loading
const [ tempContent, setTempContent ] = useState( '' );
return (
<Suspense fallback={ null }>
<Suspense
fallback={
<FallbackEdit
tempContent={ tempContent }
setTempContent={ setTempContent }
/>
}
>
<Init
content={ tempContent }
setContent={ ( content ) =>
props.setAttributes( { content } )
}
/>
<Load { ...props } />
</Suspense>
);
Expand Down

0 comments on commit 5e969f3

Please sign in to comment.