Skip to content

Instantly share code, notes, and snippets.

@fumikito
Created November 27, 2020 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fumikito/fcba4760c790415d61e00d3c1317a31e to your computer and use it in GitHub Desktop.
Save fumikito/fcba4760c790415d61e00d3c1317a31e to your computer and use it in GitHub Desktop.
Display notice depending on the contents in WordPress block editor
/*!
* Test document.
*
* @deps wp-data, wp-dom-ready
*/
const { data, domReady } = wp;
const wordLimiter = {
80: false,
140: false,
};
const stripTags = ( text ) => {
// Remove comment.
text = text.replace( /<!--(.*?)-->/g, '' );
// Remove tags.
text = text.replace( /<([^>]+)>/g, '' );
// Remove sequential line breaks.
text = text.replace( /\n{2,}/g, "\n" );
return text;
};
domReady( () => {
//
data.subscribe( () => {
const count = stripTags( data.select( 'core/editor' ).getEditedPostContent() ).length;
if ( ! wordLimiter[80] && 80 < count ) {
wordLimiter[80] = true;
data.dispatch( 'core/notices' ).createNotice( 'success', 'Great, you\'ve written 80 letters long.', {
type: 'snackbar'
} ).then( ( res ) => {
setTimeout( () => {
data.dispatch( 'core/notices' ).removeNotice( res.notice.id );
}, 3000 );
} );
} else if ( ! wordLimiter[140] && 140 < count ) {
wordLimiter[140] = true;
data.dispatch( 'core/notices' ).createNotice( 'error', 'Over 140 letter, too long!', {
type: 'snackbar'
} ).then( ( res ) => {
setTimeout( () => {
data.dispatch( 'core/notices' ).removeNotice( res.notice.id );
}, 3000 );
} );
}
} );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment