Skip to content

Instantly share code, notes, and snippets.

@mcsf
Last active March 19, 2020 06:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcsf/510c3a1cc2695b13c643ced4555cfad1 to your computer and use it in GitHub Desktop.
Save mcsf/510c3a1cc2695b13c643ced4555cfad1 to your computer and use it in GitHub Desktop.
[Per Slack request] Illustrating the use of WordPress data selectors in conjunction with React hooks to react to post saving within a custom sidebar in Gutenberg. Move advanced entity-centric selectors may be used from the 'core' store instead.
<?php
/*
Plugin Name: Test
*/
function my_test_enqueue_scripts() {
wp_enqueue_style(
'my-test-style',
plugins_url( 'style.css', __FILE__ )
);
wp_enqueue_script(
'my-test-plugin',
plugins_url( 'plugin.js', __FILE__ ),
array( 'wp-element', 'wp-components', 'wp-editor', 'wp-edit-post', 'wp-plugins' )
);
}
add_action( 'enqueue_block_editor_assets', 'my_test_enqueue_scripts' );
( function( wp ) {
const { createElement: el, useEffect, useRef } = wp.element;
const { Panel, PanelBody } = wp.components;
const { registerPlugin } = wp.plugins;
const { PluginSidebar } = wp.editPost;
const { useSelect } = wp.data;
registerPlugin( 'my-plugin-sidebar', {
render() {
return el( PluginSidebar,
{
name: 'my-plugin-sidebar',
icon: 'admin-post',
title: 'Save status',
},
el( SaveStatus )
);
},
} );
function SaveStatus() {
const hasJustSaved = useDidSave();
useEffect( () => {
if ( hasJustSaved ) console.log( 'Post saved!' );
}, [ hasJustSaved ] );
return el( Panel, {},
el( PanelBody, {},
'Have we just saved? ',
el( 'span', { className: hasJustSaved ? 'my-test-has-just-saved' : '' },
hasJustSaved ? 'Yes.' : 'No.'
)
)
);
}
function useDidSave() {
const wasSaving = useRef( false );
const { isDirty, isSaving } = useSelect( ( select ) => {
const { isEditedPostDirty, isSavingPost } = select( 'core/editor' );
return {
isDirty: isEditedPostDirty(),
isSaving: isSavingPost(),
};
} );
const hasJustSaved = wasSaving.current && ! isSaving;
if ( isDirty ) wasSaving.current = isSaving;
return hasJustSaved;
}
} )( window.wp );
@keyframes my-test-glow {
from {
text-shadow: 0 0 10px gold;
}
to {
text-shadow: 0 0 0 gold;
}
}
.my-test-has-just-saved {
animation: 1s my-test-glow;
}
@mcsf
Copy link
Author

mcsf commented Mar 16, 2020

screencast

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment